Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate the sum of numbers from 1 to 10

C Code Example — Loop Programs

ADVERTISEMENT

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

  1. Declare an integer i and initialize a sum variable to 0: sum = 0.
  2. Start a for loop with i = 1, condition i <= 10, and increment i++.
  3. Inside the loop, add i to sum: sum = sum + i.
  4. 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 for loop is used when the exact number of iterations is known in advance.
  • It is crucial to initialize sum = 0 before 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)
ADVERTISEMENT