**Exercise:**

Write a Java Program to calculate the sum of natural numbers up to 50.

#### 1.Compute sum using for loop.

**Click Here to View the Solution!**

`public`` `

class SumNaturalNumbers `{`

` `

` `

public static void main(String[] args) `{`

` `

` `

int` num = `

50`, sum = `

0`;`

` `

` `

for`(`

int` i = `

1`; i <= num; ++i)`

` {`

` sum += i;`

` }`

` `

` System.out.println(`

"Sum = "` + sum);`

` }`

`}`

**Click Here to View the Output!**

Sum = 1275

**Click Here to View the Explanation!**

- This program is used for calculating the sum of all the natural numbers initialized in the program by using the for loop.
- The natural numbers start from 1 till the given number. A given number 50 is stored in an integer variable
`num`

. Hence all the numbers starting from 1 will be added till 50. - A
`for loop`

is used for stating the condition expression which will loop the numbers starting from 1 and till`num`

and keep adding numbers in the variable`sum`

which was initially 0. - Finally, the sum of all the natural numbers will be printed as “Sum = 1275” for
`num = 50`

#### 2.Compute sum using While loop.

**Click Here to View the Solution!**

`public`` `

class SumNaturalNumbers `{`

` `

` `

public static void main(String[] args) `{`

` `

` `

int` num = `

100`, i = `

1`, sum = `

0`;`

` `

` `

while`(i <= num)`

` {`

` sum += i;`

` i++;`

` }`

` `

` System.out.println(`

"Sum = "` + sum);`

` }`

`}`

**Click Here to View the Output!**

Sum = 5050

**Click Here to View the Explanation!**

- This program is used for finding the sum of natural numbers by using a while loop.
- Initially, a number 100 is stored into the variable
`num`

which will be the number till where the addition occurs, a variable i as 1 and a variable sum as 0. - Like the above program using for loop, this program loops and increments the variable
`i`

,`num`

number of times inside the body of the`while`

loop and keeps adding its value into the variable`sum`

. - Both the
`for`

loop and`while`

loop are considered to be appropriate for performing this task however, for loop is considered a better option since it knows the number of iterations till the variable`num`

. - The result is stored in the variable
`sum`

and is displayed as “Sum = 5050”.