w3resource

Java: Display the n terms of odd natural number and their sum


Sum of Odd Natural Numbers

Write a Java program that displays the sum of n odd natural numbers.

Test Data
Input number of terms is: 5

Pictorial Presentation:

Java conditional statement Exercises: Display the n terms of odd natural number and their sum


Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise15 {

   public static void main(String[] args)

{
   int i,n,sum=0;

   System.out.print("Input number of terms is: ");
{
   Scanner in = new Scanner(System.in);
		    n = in.nextInt();
  System.out.println ("\nThe odd numbers are :");
   for(i=1;i<=n;i++)

   {
     System.out.println (2*i-1);
     sum+=2*i-1;
   }
   System.out.println ("The Sum of odd Natural Number upto " +n+" terms is: " +sum);

}
}
}

Sample Output:

Input number of terms is: 5                                                                                   
The odd numbers are :                                                                                         
1                                                                                                       
3                                                                                                       
5                                                                                                       
7                                                                                                       
9                                                                                                       
The Sum of odd Natural Number upto 5 terms is: 25

Flowchart:

Flowchart: Java Conditional Statement Exercises - Display the n terms of odd natural number and their sum



For more Practice: Solve these Related Problems:

  • Write a Java program to compute the sum of the first n odd natural numbers using a mathematical formula.
  • Write a Java program to display the first n odd numbers and then compute their cumulative sum using recursion.
  • Write a Java program to calculate the sum of odd numbers in an array of natural numbers using streams.
  • Write a Java program to prompt the user for n and then display the odd numbers and their sum using a while loop.

Go to:


PREV : Multiplication Table of a Number.
NEXT : Right-Angle Triangle Number Pattern.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.