Java Tutorial

Java Program for Sum of First N Numbers

Java Program for Sum of First N Numbers using for loop

This java program is used to compute the sum of first n numbers using for loop.

Gets the limit value as user input and calculates the sum till limit value and prints the sum value.

```import java.util.Scanner;

class SumTest {
public static void main(String[] values) {
int sum = 0, limit;
Scanner sc = new Scanner(System.in);
System.out.println("Calculates Sum of first n numbers");
System.out.println("----------------------------------");
System.out.print("Enter limit number:");
limit = sc.nextInt();
for(int i=1;i<=limit;i++){
sum += i;
}
System.out.println("Sum of first '"+limit+"' numbers: " + sum);
}
}
```
Output:
```D:\Java_Programs>javac SumTest.java
D:\Java_Programs>java SumTest
Calculates Sum of first n numbers
----------------------------------
Enter limit number:10
Sum of first '10' numbers: 55
```

Java Program for Sum of First N Numbers using while loop

This java program is used to compute the sum of first n numbers using while loop.

```import java.util.Scanner;

class SumTest {
public static void main(String[] values) {
int sum = 0, limit;
Scanner sc = new Scanner(System.in);
System.out.println("Calculates Sum of first n numbers");
System.out.println("----------------------------------");
System.out.print("Enter limit number:");
limit = sc.nextInt();
int i=1;
while(i<=limit){
sum += i;
i++;
}
System.out.println("Sum of first '"+limit+"' numbers: " + sum);
}
}
```
Output:
```D:\Java_Programs>javac SumTest.java
D:\Java_Programs>java SumTest
Calculates Sum of first n numbers
----------------------------------
Enter limit number:9
Sum of first '9' numbers: 45
```

Java Program for Sum of First N Numbers using do while loop

This java program is used to compute the sum of first n numbers using do while loop.

```import java.util.Scanner;

class SumTest {
public static void main(String[] values) {
int sum = 0, limit;
Scanner sc = new Scanner(System.in);
System.out.println("Calculates Sum of first n numbers");
System.out.println("----------------------------------");
System.out.print("Enter limit number:");
limit = sc.nextInt();
int i=1;
do {
sum += i;
i++;
}while(i<=limit);
System.out.println("Sum of first '"+limit+"' numbers: " + sum);
}
}
```
```D:\Java_Programs>javac SumTest.java
D:\Java_Programs>java SumTest
Calculates Sum of first n numbers
----------------------------------
Enter limit number:8
Sum of first '8' numbers: 36
```

Java Tutorial