Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that examines a series of a integers entered by the user and tha

ID: 3690037 • Letter: W

Question

Write a program that examines a series of a integers entered by the user and that then determines whether adjacent values in the series differ by at most 2.

The program should ask the user to enter the number , n, of numbers in the sequence, followed by the numbers themselves (i.e. one per line). The assumption is that n>1.

Hint: The function abs(-5) will return 5.

Sample Input/Output:

Enter the length of the sequence:

3

Enter the number 1:

50

Enter the number 2:

51

Within bounds

Sample Input/Output:

Enter the length of the sequence:

3

Enter the number 1:

50

Enter the number 2:

51

Enter the number 3:

57

Not within bounds

Explanation / Answer

NumberSeries.java


import java.util.Scanner;

public class NumberSeries {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       Scanner scan = new Scanner(System.in);
       boolean status = false;
       System.out.println("Enter the length of the sequence:");
       int n = scan.nextInt();
       int a[] = new int[n];
       for(int i=0; i<n; i++){
           System.out.println("Enter the number "+(i+1)+":");
           a[i] = scan.nextInt();
       }
       for(int i=0; i<n-1; i++){
           if(Math.abs(a[i] - a[i+1]) <= 2){
               status = true;
           }
           else{
               status = false;
               break;
           }
       }
       if(status)
           System.out.println("Within bounds");
       else
           System.out.println("Not within bounds");
   }

}

Output:

Enter the length of the sequence:
3
Enter the number 1:
51
Enter the number 2:
52
Enter the number 3:
53
Within bounds

Enter the length of the sequence:
3
Enter the number 1:
51
Enter the number 2:
52
Enter the number 3:
57
Not within bounds

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote