Advertisement
mmayoub

arrays-exercise 10, slide 29

Jul 1st, 2017
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class arrays10 {
  6.  
  7.     public static void main(String[] args) {
  8.         /*
  9.          * Exercise 10, slide 29
  10.          * input : 5 numbers to an array
  11.          * output: are the values in the array sorted in ascending order ?
  12.          */
  13.        
  14.         // size of array
  15.         final int SIZE = 5;
  16.  
  17.         // create a scanner
  18.         Scanner s = new Scanner(System.in);
  19.  
  20.         // define an integer array
  21.         int[] numbers = new int[SIZE];
  22.  
  23.         System.out.printf("Enter %d integer numbers:\n", numbers.length);
  24.         // get data from user and save it in the array
  25.         for (int i = 0; i < numbers.length; i += 1) {
  26.             numbers[i] = s.nextInt();
  27.         }
  28.  
  29.         s.close();
  30.  
  31.         // check numbers at the same position, if equal then print the position
  32.         int i;
  33.  
  34.         // using for with if
  35.         for (i = 1; i < numbers.length; i += 1) {
  36.             if (numbers[i] <= numbers[i - 1]) {
  37.                 break;
  38.             }
  39.  
  40.         }
  41.  
  42.         // you can also use for without if
  43.         // for (i = 1; i < numbers.length && numbers[i] > numbers[i - 1]; i +=
  44.         // 1) { }
  45.  
  46.         System.out.printf("array is %ssorted in ascending order.\n",
  47.                 i == numbers.length ? "" : "not ");
  48.     }
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement