ADVERTISEMENT
Sum of N Numbers
This code takes a user-defined number ‘n’, calculates the sum of all natural numbers from 0 to ‘n’, and then prints the result. It uses a for loop to iterate through the numbers and an accumulator variable sum to keep track of the total.
#include<stdio.h>
main()
{
int i,n,sum=0;
printf("Enter a number\n");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
sum=sum+i;
}
printf("%d\n",sum);
}C Programming ExamplesExplanation:
This C program calculates the sum of all natural numbers from 0 to a user-defined number ‘n’. Here’s a step-by-step explanation of the code:
Header File:
- The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
- The main function is the entry point of the program.
Variable Declaration:
Two variables are declared:
- i (int): It is used as a loop counter to iterate through the natural numbers.
- n (int): This variable will store the user input for the upper limit ‘n’.
- sum (int): This variable will store the sum of the natural numbers.
User Input:
- The program prompts the user to enter a number by displaying the message “Enter a number”.
- The user’s input is read and stored in the variable n using scanf.
For Loop:
- The for loop is used to iterate from 0 to ‘n’, including both 0 and ‘n’.
- i is initialized to 0, and the loop continues as long as i is less than or equal to n.
- In each iteration of the loop, the value of i is added to the sum.
Accumulating Sum:
- Within the loop, the value of i is added to the sum. This accumulates the sum of natural numbers from 0 to ‘n’.
Print Result:
- After the loop completes, the program uses printf to display the calculated sum. The format specifier %d is used to print the integer value of sum.
End of Program:
- Once the result is displayed, the program reaches the end of the main function and terminates.