Sunday, July 13, 2008

Find the sum of 'N' natural numbers

/* Write a C program to find the sum of 'N' natural numbers*/

#include stdio.h
#include conio.h

void main()
{
int i, N, sum = 0;

clrscr();

printf("Enter an integer number\n");
scanf ("%d", &N);

for (i=1; i <= N; i++)
{
sum = sum + i;
}

printf ("Sum of first %d natural numbers = %d\n", N, sum);
}

/*----------------------------------------
Output
RUN1

Enter an integer number
10
Sum of first 10 natural numbers = 55


RUN2

Enter an integer number
50
Sum of first 50 natural numbers = 1275
------------------------------------------*/

Another straight forward program which uses a for loop to increment the number. The sum value is pre instiantiated to zero and we use a for loop to increment it. The output is displayed. The other way to execute this program is using the fornula for addition of n natural numbers

2 comments:

sri said...

good n easy code

Irie said...

Do you know how can i do the exactly same program apart from thing I want to print method of finding sum? For example, N=4
1+2=3
1+2+3=6
1+2+3+4=10