Algorithm


1. Start
2. Initialize variables:
   - sum = 0
   - n (input for the last natural number)
3. Read the value of n from the user
4. Loop from i = 1 to n:
   a. Add i to sum
5. Display the sum
6. End

Code Examples

#1 Code Example- Sum of Natural Numbers using for loop

Code - Java Programming

public class SumNatural {

    public static void main(String[] args) {

        int num = 100, sum = 0;

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

        System.out.println("Sum = " + sum);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Sum = 5050

#2 Code Example- Sum of Natural Numbers using while loop

Code - Java Programming

public class SumNatural {

    public static void main(String[] args) {

        int num = 50, i = 1, sum = 0;

        while(i  < = num)
        {
            sum += i;
            i++;
        }

        System.out.println("Sum = " + sum);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Sum = 1275
Advertisements

Demonstration


Java Programing Example to Calculate the Sum of Natural Numbers-DevsEnv