Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Scanner;
- public class arrays10 {
- public static void main(String[] args) {
- /*
- * Exercise 10, slide 29
- * input : 5 numbers to an array
- * output: are the values in the array sorted in ascending order ?
- */
- // size of array
- final int SIZE = 5;
- // create a scanner
- Scanner s = new Scanner(System.in);
- // define an integer array
- int[] numbers = new int[SIZE];
- System.out.printf("Enter %d integer numbers:\n", numbers.length);
- // get data from user and save it in the array
- for (int i = 0; i < numbers.length; i += 1) {
- numbers[i] = s.nextInt();
- }
- s.close();
- // check numbers at the same position, if equal then print the position
- int i;
- // using for with if
- for (i = 1; i < numbers.length; i += 1) {
- if (numbers[i] <= numbers[i - 1]) {
- break;
- }
- }
- // you can also use for without if
- // for (i = 1; i < numbers.length && numbers[i] > numbers[i - 1]; i +=
- // 1) { }
- System.out.printf("array is %ssorted in ascending order.\n",
- i == numbers.length ? "" : "not ");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement