Write a Java Program to Calculate the Sum of Natural Numbers

Java Program to Calculate the Sum of Natural Numbers

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Calculate the Sum of Natural Numbers
Java Program to Calculate the Sum of Natural Numbers

Write a Java Program to Calculate the Sum of Natural Numbers

PROGRAM: Java Program to Calculate the Sum of Natural Numbers

/* Java Program to Calculate the Sum of Natural Numbers*/

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *