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:**

**Input:**- Number of terms is : 6
**Output:**- The odd numbers are:
- 1
- 3
- 5
- 7
- 9
- 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

**Recommended:**

- Java Program to find the greatest of three Numbers
- Java Program to Display the weekday between 1 and 7
- Java Program to Find the number of days in a Months.
- Java Program to Print character is vowel or Consonant
- Java Program to Check a year is a leap year or not
- Java Program to display the sum of first N natural numbers
- Java Program to find sum and average of N numbers
- Java Program to find a cube of an N given numbers.

MellissaIt’s nearly impossible to find well-informed people in this particular

subject, however, you sound like you know what you’re talking about!

Thanks