in blue j part 1: Write a program that reads a sequence of integers into an arra
ID: 3768416 • Letter: I
Question
in blue j
part 1: Write a program that reads a sequence of integers into an array and that computes the alternating sum of all elements in the array.
For example, if the program is executed with the input data: 2 1 4 9 16 9 7 4 9 11 Then it computes 2 - 1 + 4 - 9 + 16 - 9 + 7 - 4 + 9 – 11 = 4
Use a scanner object to gather the inputs from the user. Remember that you will not know how many numbers the user will input each time the program is run. Check out our book’s info on partially filled arrays, or my part of the class java program on the Declaration of Independence.
Part II – Write a method that will produce random permutations of the numbers 1 to 10. To generate a random permutation, you need to fill an array with the numbers 1 to 10 so that no two entries of the array have the same contents. You could do it by brute force, by calling Math.random() until it produces a value that is not yet in the array. That may take some time, and wouldn’t be efficient. Instead you should implement a smart process; Make a second array and fill it with the numbers 1 to 10, then pick one of those at random, remove it from the second array and append it to the permutation array. Repeat this 10 times.
Create a main method that will test this method along with a printArray(int [] arr) method to print it out. Print out 5 or 6 arrays in your main method created by your randomizing method to ensure it is working appropriately.
Explanation / Answer
Part-I
import java.util.Scanner;
public class TestArray {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] array = new int[Integer.parseInt(args[0])];//instance variable
for(int i = 0; i < array.length; i++){//user fills in array
System.out.println("Please enter value " + (i +1) + " :");
array[i] = keyboard.nextInt();
}
int sum = 0;
for(int i=0; i< array.length; i++){//alternates adding and subtracting integers
if(i%2==0){
sum+= array[i];
}
else{
sum-= array[i];
}
}
//results
System.out.println("The alternating sum of all elements is: " + sum);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.