Python/C/C++/JAVA

Basic Practice Programs with Code and Concept

By D.S

Sum of all Natural Numbers

In this example, we're going to discuss how to calculate the sum of all natural numbers up to a given positive integer using different programming languages. This concept is fundamental in programming and is often used in various mathematical computations.

(a.) C Code

#include <stdio.h>

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

        printf("Enter a positive integer: ");
        scanf("%d", &num);

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

        printf("Sum of natural numbers up to %d is: %d
", num, sum);

        return 0;
    }
Output:-
Enter a positive integer: 5
Sum of natural numbers up to 5 is: 15

(b.) C++ Code

#include <iostream>

    using namespace std;

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

        cout << "Enter a positive integer: ";
        cin >> num;

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

        cout << "Sum of natural numbers up to " << num << " is: " << sum << endl;

        return 0;
    }
Output:-
Enter a positive integer: 5
Sum of natural numbers up to 5 is: 15

(c.) Python Code

def main():
        num = int(input("Enter a positive integer: "))
        sum = 0

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

        print("Sum of natural numbers up to", num, "is:", sum)

    if __name__ == "__main__":
        main()
Output:-
Enter a positive integer: 5
Sum of natural numbers up to 5 is: 15

(d.) Java Code

import java.util.Scanner;

    public class SumOfNaturalNumbers {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a positive integer: ");
            int num = scanner.nextInt();
            int sum = 0;

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

            System.out.println("Sum of natural numbers up to " + num + " is: " + sum);
        }
    }
Output:-
Enter a positive integer: 5
Sum of natural numbers up to 5 is: 15