C Program to calculate the sum of numbers from 1 to 10
Objective
Write a C program to calculate the sum of numbers from 1 to 10 using a loop.
Algorithm / Approach
- Declare an integer
iand initialize a sum variable to 0:sum = 0. - Start a
forloop withi = 1, conditioni <= 10, and incrementi++. - Inside the loop, add
itosum:sum = sum + i. - After the loop terminates, print the final value of
sum.
main.c
#include<stdio.h>
int main( ) {
int i, sum=0;
for(i=1; i<=10; i++)
{
sum = sum+i;
}
printf("SUM IS : %d\n"+sum);
return 0;
}
Expected Output
SUM IS : 55
Explanation of the Program
- A
forloop is used when the exact number of iterations is known in advance. - It is crucial to initialize
sum = 0before the loop. If you don't initialize a local variable in C, it will contain random "garbage" data left over in memory, which will completely corrupt your calculation.
Complexity
Time Complexity
O(n) - Where n is the number of iterations (10).
Space Complexity
O(1)