0% found this document useful (0 votes)
237 views

Java Program To Calculate The Sum of Natural Numbers

The document provides two examples of calculating the sum of natural numbers from 1 to a given number. The first example uses a for loop to iterate from 1 to the given number, adding each number to a running sum variable. The second example uses a while loop in the same manner. While both work, a for loop is preferred here since the number of iterations is known beforehand. The document also notes there is a way to calculate this sum recursively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
237 views

Java Program To Calculate The Sum of Natural Numbers

The document provides two examples of calculating the sum of natural numbers from 1 to a given number. The first example uses a for loop to iterate from 1 to the given number, adding each number to a running sum variable. The second example uses a while loop in the same manner. While both work, a for loop is preferred here since the number of iterations is known beforehand. The document also notes there is a way to calculate this sum recursively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Example 1: Sum of Natural Numbers using for loop

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);


}
}

Output

Sum = 5050

The above program loops from 1 to the given num (100) and adds all numbers to the
variable sum .

You can solve this problem using a while loop as follows:

Example 2: Sum of Natural Numbers using while loop


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);


}
}

Output

Sum = 1275

In the above program, unlike a for loop, we have to increment the value of i inside the
body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It's
because the number of iteration (up to num ) is known.

Visit this page to learn how to find the sum of natural numbers using recursion.

You might also like