Thursday, April 2, 2020

C program to sum of all natural number using while loop

C program to Sum of All Natural Number Using While Loop


#include 
int main()
{
    int n, i, sum = 0; // integer value
    printf("Enter a positive integer: "); // enter user positive number
    scanf("%d", &n); // storing number
    i = 1; 

    while (i <= n) // while loop 
    {
        sum = sum + i; // total sum
        ++i;
    }

    printf("Sum = %d", sum); // print sum numbers
    return 0;
}

Output

Enter positive integer = 100
Sum = 5050

  • In this program, loop is iterated n number of times. And, in each iterated, the value of  ' i '  is added to sum and  is increment by 1.  

0 comments:

Post a Comment

Recent Posts