Advertisement
mmayoub

arrays-exercise 04, slide 28

Jul 1st, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class arrays04 {
  6.  
  7.     public static void main(String[] args) {
  8.         /*
  9.          * Exercise 4, slide 28
  10.          * input : 10 numbers to an array
  11.          * output: add 1 to values in even keys, then print all numbers
  12.          */
  13.        
  14.         // create a scanner
  15.         Scanner s = new Scanner(System.in);
  16.  
  17.         // define an integer array, size=10
  18.         int[] numbers = new int[10];
  19.  
  20.         System.out.printf("Enter %d integer numbers:\n", numbers.length);
  21.         // get data from user and save it in the array
  22.         for (int i = 0; i < numbers.length; i += 1) {
  23.             numbers[i] = s.nextInt();
  24.         }
  25.         s.close();
  26.  
  27.         // print numbers before adding and add to even places
  28.         System.out.print("Numbers before adding: ");
  29.         for (int i = 0; i < numbers.length; i += 1) {
  30.             System.out.printf("%d ", numbers[i]);
  31.             // if even key add one to the value
  32.             numbers[i] += i % 2 == 0 ? 1 : 0;
  33.         }
  34.         System.out.println();
  35.  
  36.         // print numbers after adding
  37.         System.out.print("Numbers after adding: ");
  38.         for (int i = 0; i < numbers.length; i += 1) {
  39.             System.out.printf("%d ", numbers[i]);
  40.  
  41.         }
  42.         System.out.println();
  43.     }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement