Index « Previous Next »

Question

Write a program that asks the user for a positive integer value. The program should calculate the sum of all the integers from 1 up to the number entered. For example, if the user enters 20, the loop will find the sum of 1, 2, 3, 4, ... 20.

Source Code

#include <stdio.h>

int main()
{
    int i, n, sum = 0;
    
    printf("Enter a positive integer :");
    scanf("%d", &n);

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

    printf("The sum of first %d numbers is %d.", n, sum);
    
    return 0;
}

Output

Enter a positive integer :20
The sum of first 20 numbers is 210.