Sum of Natural Numbers in C-Programming

FOR LOOP

#include <stdio.h>
int main()
{
int n, i, sum = 0;

printf("Enter a positive integer: ");
scanf("%d",&n);

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

printf("Sum = %d",sum);

return 0;
}

 

 

While Loop

#include <stdio.h>
int main()
{
int n, i, sum = 0;

printf("Enter a positive integer: ");
scanf("%d",&n);

i = 1;
while ( i <=n )
{
sum += i;
++i;
}

printf("Sum = %d",sum);

return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image