Computer Science, asked by vaanyamittal2006, 16 days ago

Write a program in java to print 2 + 4 + 7 + 11 + 16 + -----------------------------N terms.​

Answers

Answered by anindyaadhikari13
3

Correct Question:

  • Write a program in java to print 2 4 7 11 16 . . . N terms.

Solution:

The given problem is solved in Java.

import java.util.Scanner;

public class Main{

   public static void main(String args[]){

       Scanner sc = new Scanner(System.in);

       int i, n, term = 1;

       System.out.print("Enter limit: ");

       n = sc.nextInt();

       for(i = 1;i <= n;i++){

           term += i;

           System.out.print(term + " ");

       }

   }

}

Explanation:

  • At first, we ask the user to enter the limit.
  • Then a loop is created to display the series. Variable i is the looping variable. Its default value is 1. The loop iterates until i is less than the limit (n).
  • Now, in the series, we can see that the difference between each term increases by 1. At first it was 2 (4 - 2 = 2), then it becomes 3, 4, 5 . . . and so on.
  • So, we assume term = 1. When the loop starts iterating, the value os the variable term is increased by the value of the control variable.
  • For the first time, it is increased by 1. So, 2 is printed. For the second time, it is incremented by 2, 4 is printed and in this way, remaining terms are printed.
  • Hence our problem is solved.!!

Refer to the attachment for output.

Attachments:
Similar questions