C Program to find the sum of first 50 natural numbers


March 21, 2022, Learn eTutorial
1115

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this C program, Here we want to find out the sum of the first 50 natural numbers. For doing this, we have to declare the integer variable 'num, Sum'. And set sum = '0'. By using a For loop  calculate 'sum=sum+num', 50 times. Then display the Sum.

How to calculate the sum of n natural numbers?

In Mathematics using Arithmetic Progression, we can find out the sum of n numbers by using the formula " Sn = n/2*[2*a+(n-1)*d]". For example, The Sum of 50 natural numbers is,
'S50 = 50/2*[2*a+(50-1)*d]', a is the first term in Arithmetic Progression and 'd' is the common difference of A.P. Here first 'term = a = 1' and Common 'Difference = d = 1'
So

 
S50 = 25*[2*1+(49)*1]

    = 25*[2+49]

    = 51*25

    = 1275

What is the syntax of for loop?

In this program, for loop is used. The syntax of for loop is given by


for (initializationStatement; testExpression; updateStatement)

     {
          // codes
     }

Here the initialization statement is executed only once. Initially, evaluate the test expression. If the test expression is False, terminate the for a loop. But if the test expression is True, then run the code inside the for loop and update the expression. This process continues until the test expression is False. This type of loop will use only when the number of iterations is finite.

ALGORITHM

STEP 1: Include the header files to use the built-in header files into the C program.

STEP 2: Declare the integer variables num, Sum, and set sum=0.

STEP 3: Set num=1.

STEP 4: By using the for loop with the condition 'num<=50', do step 5.

STEP 5: Calculate sum=sum+num.

STEP 6: Repeat step 4.

STEP 7: Display sum.

C Source Code

                                          #include <stdio.h>

void main() {
  int num, sum = 0;
  for (num = 1; num <= 50; num++) {
    sum = sum + num;
  }
  printf("Sum = %d\n", sum);
}
                                      

OUTPUT

Sum = 1275