﻿ C Program: Display the sum of first 10 natural numbers - w3resource

# C Exercises: Display the sum of first 10 natural numbers

## C For Loop: Exercise-2 with Solution

Write a C program to compute the sum of the first 10 natural numbers.

This C program calculates the sum of the first 10 natural numbers. It utilizes a "for" loop to iterate through numbers 1 to 10, accumulating their sum, and then prints the total. This exercise is helpful for understanding basic loop constructs and arithmetic operations in C.

Visual Presentation:

Pseudo code to find the sum of the first 10 natural numbers:

• Initialize a variable "sum" to 0
• Initialize a loop variable "i" to 1
• Repeat the following steps while i <= 10: a. Add i to the sum variable b. Increment i by 1
• Print the "sum" variable value

Sample Solution:

C Code:

``````#include <stdio.h>  // Include the standard input/output header file.

int main() {
int j, sum = 0;  // Declare variables 'j' for the loop counter and 'sum' to store the sum.

printf("The first 10 natural numbers are :\n");  // Print a message to indicate the output.

for (j = 1; j <= 10; j++)  // Start a for loop to iterate from 1 to 10.
{
sum = sum + j;  // Add the current value of 'j' to the sum.
printf("%d ", j);  // Print the current value of 'j'.
}

printf("\nThe Sum is : %d\n", sum);  // Print the sum of the first 10 natural numbers.
return 0;  // Indicate successful execution of the program.
}
```
```

Output:

```The first 10 natural number is :
1 2 3 4 5 6 7 8 9 10
The Sum is : 55
```

Explanation:

```for (j = 1; j <= 10; j++) {
sum = sum + j;
printf("%d ", j);
}
```

In the above for loop, the variable j is initialized to 1, and the loop will continue as long as j is less than or equal to 10. In each iteration of the loop, the sum variable will add the value of j to itself, and the printf function will print the value of j to the console, followed by a space character.

Finally, the loop will increment the value of j by 1, and the process will repeat until the condition j <= 10 is no longer true.

Flowchart:

C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿