Coding Practice

Write a C program to find sum of all natural numbers between 1 to n

Find sum of all natural numbers between 1 to n
Sample Output
Enter a number: 6

Natural numbers are...

1

2

3

4

5

6

Sum: 21

Process returned 0 (0x0)   execution time : 11.998 s
Press any key to continue.
Source Code
#include<stdio.h>

int main()
{
    int n, num, sum = 0;

    printf("Enter a number: ");
    scanf("%d", &num);

    printf("\nNatural numbers are...\n");

    for(n = 1; n <= num; n++)
    {
        sum += n; // Or, sum = sum + n;

        printf("\n%d\n", n);
    }
    printf("\nSum: %d\n", sum);

    return 0;
}
Sample Output
Enter a number: 6

Natural numbers are...

1

2

3

4

5

6

Sum: 21

Process returned 0 (0x0)   execution time : 11.998 s
Press any key to continue.

No comments:

Post a Comment

Change Theme
X