Hello students and self-learners, here is another interesting program for you to learn the basics of C programming.
In this post, you are going to learn how to print natural number from 1 to n using C programming language.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include<stdio.h> int main() { int n, sum = 0; //get a positive integer printf("Enter n:"); scanf("%d", &n); //loop till n and calculate the values from 1 to n for(int i=1; i<=n; i++) { sum = sum + i; } //print the final output printf("Sum of natural numbers (1 to %d) is: %d", n, sum); return 0; } |
It’s a very simple program. First, we are getting the value of n from the user. Then using for loop we are calculating the values from 1 to n.
The output of the above program will be:
1 2 3 4 5 |
Enter n:5 Sum of natural numbers (1 to 5) is: 15 -------------------------------- Process exited after 3.019 seconds with return value 0 Press any key to continue . . . |
Enjoy learning something new every day!