C Program To find the sum and display first n natural numbers

This page has a C Program To find sum and display first n natural numbers. There are three ways(for loop, while loop, and do . . . while loop) to find the sum of first n natural numbers and display first n natural numbers. For example: if an integer 6 is given as input, then the below given C program will display the natural numbers as 1,2,3,4,5,6 and sum as 21. The below given C program will find sum and display first n natural numbers. Kindly check out the program to find the sum of first n natural numbers and display first n natural numbers

Program to find sum of first n natural numbers and display first n natural numbers

Program Using For Loop

#include<stdio.h>

int main(){

int n,a,sum=0;

printf("Enter an integer number for n : ");

scanf("%d",&n); printf("



The natural numbers are : ");

for(a=1;a<=n;++a){

printf("

%d",a);

sum = sum + a;

}

printf("



Sum of the first %d natural numbers is %d", n, sum);

return(0);

}

Program Using While Loop

#include<stdio.h>

int main(){

int n,a,sum=0;

printf("Enter an integer number for n : ");

scanf("%d",&n);

a = 1;

printf("



The natural numbers are : ");

while(a <= n)

{

printf("

%d",a);

sum += a;

++a;

}

printf("



Sum of the first %d natural numbers is %d", n, sum);

return(0);

} Sample Output: Enter an integer number for n : 5

The natural numbers are :

1 2 3 4 5

Sum of the first 5 natural numbers is 15



Related Popular Posts: