Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Scanner;
- public class arrays04 {
- public static void main(String[] args) {
- /*
- * Exercise 4, slide 28
- * input : 10 numbers to an array
- * output: add 1 to values in even keys, then print all numbers
- */
- // create a scanner
- Scanner s = new Scanner(System.in);
- // define an integer array, size=10
- int[] numbers = new int[10];
- 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();
- // print numbers before adding and add to even places
- System.out.print("Numbers before adding: ");
- for (int i = 0; i < numbers.length; i += 1) {
- System.out.printf("%d ", numbers[i]);
- // if even key add one to the value
- numbers[i] += i % 2 == 0 ? 1 : 0;
- }
- System.out.println();
- // print numbers after adding
- System.out.print("Numbers after adding: ");
- for (int i = 0; i < numbers.length; i += 1) {
- System.out.printf("%d ", numbers[i]);
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement