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.
#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:
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!