The program adds first N natural numbers (starts from 1) and prints the sum in the console.

We recommend that you try this on your own first and then compare the solutions.

Problem Definition

Natural numbers are all positive numbers greater than number 0 and it does not include the number zero.

For example

Natural\hspace{2mm} numbers = 1, 2, 3, 4, 5, \cdots

The program reads the value of number N which is a natural number and then sum all other natural numbers up to number N start from 1. Suppose N = 10 then

Sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Flowchart – Sum of First N Natural Numbers

Figure 1 - Flowchart for program that compute sum of first N natural numbers
Figure 1 – Flowchart for program that compute sum of first N natural numbers

Program Codes – Sum of First N Natural Numbers

/* Program for sum of First N Natural Numbers */ 
#include <stdio.h>
#include <stdlib.h> 
main() {     
int num,i,sum;
    sum = 0; /* read the number */     
    printf("Enter number to sum:");
    scanf("%d",&num);     
    for(i=1;i<=num;i++)     {         
    sum = sum + i;     
}     
printf("sum of %d number is %d\n",num,sum);     
    getch();
    return 0;
}
/* Program for sum of First N Natural Numbers */
#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;

    cout << "Enter number to sum:";
    cin >> num;

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

    cout << "sum of " << num << " number is " << sum << endl;
    return 0;
}
/* Program for sum of First N Natural Numbers */
import java.util.Scanner;

public class SumOfN {
    public static void main(String[] args) {
        int num, sum = 0;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number to sum:");
        num = sc.nextInt();

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

        System.out.println("sum of " + num + " number is " + sum);
        sc.close();
    }
}
# Program for sum of First N Natural Numbers

num = int(input("Enter number to sum:"))
sum = 0

for i in range(1, num + 1):
    sum += i

print(f"sum of {num} number is {sum}")

The most important piece of code in the above example is the for loop.

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

The for loop starts from 1 and goes through each digit between 1 and num because variable i is incremented with each iteration ( i++).  The value of num is user input and it can be a large number.

The value of i is added to variable sum using the following statement. The value of sum also increments with each iteration of the variable i in the for loop.

sum = sum + i;

The final value of the sum is printed as output.

Output

How many numbers to add?:10

sum of 10 number is 55