Ad Code

Calculating the Sum of Odd Numbers in Java

 Sum of odd numbers up to n terms



In this tutorial, we will discuss how to calculate the sum of odd numbers series e.g.
1+3+5+..... up to n terms.

Example:

Number of terms  n = 5 

Then, The odd number is 1+3+5+7+9

The Sum of Odd numbers up to n terms is  25

There are two types of methods to calculate the sum of odd numbers up to n terms.

First Method:

 import java.util.*;
 public class MyClass {
    public static void main(String args[]) {
      System.out.println("the number of terms: ");
      Scanner S=new Scanner (System.in);
      int term=S.nextInt();
      int sum=0;
      int i;
      for(i=1;i<=term;i++){
          sum=sum+(2*i-1);
      }
      System.out.println("Sum of Odd Numbers = " + sum);
    }
 }

Output:

The number of terms: 5

Sum of Odd Numbers = 25


Second Method:

 import java.util.*;
 public class MyClass {
    public static void main(String args[]) {
      System.out.println("The number of terms: ");
      Scanner S=new Scanner (System.in);
      int term=S.nextInt();
      int sum=0;
      int i=1;
      int c;
      for(c=1;c<=term;c++){
          sum=sum+i;
          i=i+2;
      }
      System.out.println("Sum of Odd Numbers = " + sum);
    }
 }


Output:

The number of terms: 6

Sum of Odd Numbers = 36

Both methods give the same result, but using the formula is faster and more efficient when dealing with large values of n.

Post a Comment

0 Comments

Ad Code