w3resource

C Exercises: Display n natural numbers and their sum

C For Loop: Exercise-3 with Solution

Write a program in C to display n terms of natural numbers and their sum.

Visual Presentation:

Display n natural numbers and their sum

Sample Solution:

C Code:

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

int main() {
    int i, n, sum = 0;  // Declare variables 'i' for loop counter, 'n' for the number of terms, and 'sum' to store the sum.

    printf("Input Value of terms : ");  // Print a message to prompt user input.
    scanf("%d", &n);  // Read the value of 'n' from the user.

    printf("\nThe first %d natural numbers are:\n", n);  // Print a message to indicate the output.

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

    printf("\nThe Sum of natural numbers upto %d terms : %d \n", n, sum);  // Print the sum of natural numbers.
    return 0;
}

Sample Output:

Input Value of terms : 7                                                                                      
                                                                                                              
The first 7 natural number is :                                                                               
1 2 3 4 5 6 7                                                                                                 
The Sum of Natural Number upto 7 terms : 28 

Explanation:

for (i = 1; i <= n; i++) {
  printf("%d ", i);
  sum += i;
}

In the above for loop, the variable i is initialized to 1, and the loop will continue as long as i is less than or equal to the value of variable 'n'. In each iteration of the loop, the printf() function will print the value of i to the console, followed by a space character. Additionally, the value of i will be added to the variable 'sum' in each iteration of the loop.

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

Flowchart:

Flowchart: Display n natural numbers and their sum

C Programming Code Editor:

Previous: Write a C program to find the sum of first 10 natural numbers.
Next: Write a program in C to read 10 numbers from keyboard and find their sum and average.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.