1. Introduction
Natural numbers are a part of number system which includes all the positive integers from 1 till infinity and are used for counting. In this Java program, we are going to find the sum of natural numbers using a while loop. This is a fundamental example showcasing the usage of loops and conditional statements in Java.
2. Program Steps
1. Define a class named SumOfNaturalNumbers.
2. Inside the main method, define an integer num up to which we want to calculate the sum.
3. Initialize two variables sum and i to 0. sum will hold the final result, and i is our counter variable.
4. Use a while loop to iterate until i is less than or equal to num.
5. In each iteration, add the value of i to sum.
6. Increment the value of i in each iteration.
7. After exiting the loop, print the value of sum.
3. Code Program
public class SumOfNaturalNumbers { // Step 1: Define a class named SumOfNaturalNumbers
public static void main(String[] args) { // Main method
int num = 100; // Step 2: Define an integer num up to which we want to calculate the sum
int sum = 0; // Step 3: Initialize sum to 0
int i = 1; // Step 3: Initialize counter variable i to 1
// Step 4: Use a while loop to iterate until i is less than or equal to num
while (i <= num) {
sum = sum + i; // Step 5: In each iteration, add the value of i to sum
i++; // Step 6: Increment the value of i in each iteration
}
// Step 7: Print the value of sum
System.out.println("Sum of Natural Numbers up to " + num + " is: " + sum);
}
}
Output:
Sum of Natural Numbers up to 100 is: 5050
4. Step By Step Explanation
– Step 1: We define a class named SumOfNaturalNumbers.
– Step 2: Inside the main method, we define an integer num up to which we want to calculate the sum. In this example, we have taken num as 100.
– Step 3: We initialize two variables sum and i to 0 and 1 respectively. sum will hold the final result, and i is our counter variable.
– Steps 4 to 6: We use a while loop to iterate until i is less than or equal to num. In each iteration, we add the value of i to sum and increment the value of i.
– Step 7: After exiting the loop, we print the value of sum, which holds the sum of natural numbers up to num.