Coding Practice

Write a Java program to find sum of all-natural numbers between 1 to n

Find sum of all natural numbers between 1 to n
Sample Output
Find sum of all natural numbers between 1 to n.

Enter a number: 4
Natural numbers are...
1
2
3
4
Sum: 10
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int n, number, sum = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("Find sum of all natural numbers between 1 to n.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        System.out.println("Natural numbers are...");

        for (n = 1; n <= number; n++) {
            sum += n; // Or, sum = sum + n;
            System.out.println(n);
            
        }
        System.out.println("Sum: " + sum);
    }
}
Sample Output
Find sum of all natural numbers between 1 to n.

Enter a number: 6
Natural numbers are...
1
2
3
4
5
6
Sum: 21

No comments:

Post a Comment

Change Theme
X