# Java Program to Print sum of first N odd natural numbers

In this post, we will write a two Java program to print the sum of the first N odd natural number using For Loop and While Loop. The program will find the odd number using the “2*i-1” formula and add the odd number.

To understand these programs you should have knowledge of following concepts of Core Java Programming.

• For Loop
• While Loop

### How the sum of first odd numbers program will work?

• First of all, we will accept the number from the user.
• Now we run a loop till number.
• Then add odd numbers using the “2*i-1” formula.

### Example:

1. Input:
2. Number of terms is : 6
3. Output:
4. The odd numbers are:
5. 1
6. 3
7. 5
8. 7
9. 9
10. 11
11. Sum of first 5 odd number is 36.

## Example 1: Program to Calculate sum of odd Number using for Loop

This program allows the user to enter the the maximum limit value. Next, this java program calculates the sum of odd numbers from 1 to maximum limit value using For Loop.

```import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Number of terms is : ");
int num = sc.nextInt();
int sum = 0;

for (int i=1;i<=num;i++){
System.out.println(2*i-1);
sum = sum + (2*i-1);
}
System.out.println("The Sum of first 5 odd number is "+sum);
}
}
```

### Output:

```Number of terms is : 5
1
3
5
7
9
The Sum of first 5 odd number is 25```

## Example 2: Program to Calculate the sum of odd Number using while loop

This Java program to find the sum of odd is the same as the above program take input from the user and then calculate the sum of odd number from 1 to maximum limit value using a While Loop.

```import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Number of terms is : ");
int num = sc.nextInt();
int sum = 0;
int i=1;

while (i<=num){
System.out.println(2*i-1);
sum = sum + (2*i-1);
i++;
}
System.out.println("The Sum of first 5 odd number is "+sum);
}
}```

### Output:

```Number of terms is : 7
1
3
5
7
9
11
13
The Sum of first 5 odd number is 49```