C program to find sum of n natural numbers using for, while and do-loop

 C program to find sum of n natural numbers using loops

To find the sum of n natural number using for loop we first take the input and store in variable n and the loop till n and add each number to sum and then output the sum.


C program to find sum of n natural numbers
C program to find sum of n natural numbers using for loop


For Example:-

Sum of first 10 numbers sum = 1+2+3+5+6+7+8+9+10 = 55

Algorithm:-

  1. Start.
  2. Take input n.
  3. initialize sum to zero.
  4. Take loop For i=1 to n in steps of 1.
  5. Add each value i to sum. 
  6. Print sum.
  7. Stop.
In this program we will take the value of n from the user and initially we are initializing a sum variable to zero which will store the final value of the sum (result which will be printed). When the user inputs the value of n will set the counter of the loop to run n times by using an integer variable i which will also be initialize to one before entering the loop.

Program:-

C program to find the sum of n natural numbers using for loop.

#include <stdio.h>

int main()
{
    int n, i;
    
    printf("Enter the number: ");
    scanf("%d", &n);
    
    int sum=0;
    
    for(i=1; i<=n; i++){
        sum = sum + i;
    }
    
    printf("Sum = %d", sum);
    

    return 0;
}


Output:-


Enter the number: 15                                                                                                  
Sum = 120  

Enter the number: 10                                                                                                  
Sum = 55  

Program:-

C program to find the sum of n natural numbers using while loop.


#include <stdio.h>

int main()
{
    int n, i;
    
    printf("Enter the number: ");
    scanf("%d", &n);
    
    int sum=0;
    
    while(i<=n){
        sum = sum + i;
        i++;
    }
    
    printf("Sum = %d", sum);
    

    return 0;
}

Output:-

Enter the number: 15                                                                                                  
Sum = 120  

Program:-

C program to find the sum of n natural numbers using do-while loop.

#include <stdio.h>

int main()
{
    int n, i;
    
    printf("Enter the number: ");
    scanf("%d", &n);
    
    int sum=0;
    
    do{
        sum = sum + i;
        i++;
    }while(i<=n);
    
    printf("Sum = %d", sum);
    

    return 0;
}

Output:-

Enter the number: 10                                                                                                  
Sum = 55 

Post a Comment

0 Comments