QuestionApril 24, 2025

Write a C program that calculates the sum of the first n natural numbers using a while loop. The program should prompt the user to input a positive integer n and then compute the sum of all numbers from 1 to n.

Write a C program that calculates the sum of the first n natural numbers using a while loop. The program should prompt the user to input a positive integer n and then compute the sum of all numbers from 1 to n.
Write a C program that calculates the sum of the first n natural numbers using a while loop. The program should prompt
the user to input a positive integer n and then compute the sum of all numbers from 1 to n.

Solution
4.1(177 votes)

Answer

```c #include int main() { int n, sum = 0, counter = 1; printf("Enter a positive integer: "); scanf("%d", &n); while (counter <= n) { sum += counter; counter++; } printf("Sum of first %d natural numbers is: %d\n", n, sum); return 0; } ``` Explanation 1. Initialize Variables Declare variables for the sum and counter. Initialize `sum` to 0 and `counter` to 1. 2. Prompt User Input Use `printf` to ask the user for a positive integer and `scanf` to read the input into variable `n`. 3. Calculate Sum Using While Loop Use a `while` loop to iterate from 1 to `n`. In each iteration, add the current value of `counter` to `sum`, then increment `counter`. 4. Display Result Use `printf` to output the calculated sum.

Explanation

1. Initialize Variables<br /> Declare variables for the sum and counter. Initialize `sum` to 0 and `counter` to 1.<br /><br />2. Prompt User Input<br /> Use `printf` to ask the user for a positive integer and `scanf` to read the input into variable `n`.<br /><br />3. Calculate Sum Using While Loop<br /> Use a `while` loop to iterate from 1 to `n`. In each iteration, add the current value of `counter` to `sum`, then increment `counter`.<br /><br />4. Display Result<br /> Use `printf` to output the calculated sum.
Click to rate: