In: Computer Science
Assignment Purpose
The purpose of this lab is to write a well commented java program that demonstrates the use of one dimensional arrays and methods.
Instructions
1 2 3 4 5 6 7 and the value of n = 3
Sample output
-----------------------Output Begins-------------------------
The randomly generated integers in array are: 1 2 3 4 5 6 7
Sum of numbers at even indexes = 16
Average of numbers at odd indexes = 4
Enter rotation count: 3
Calling rotateArray with rotation count as 3………
After 1st rotation the array contents are 2 3 4 5 6 7 1
After 2nd rotation the array contents are 3 4 5 6 7 1 2
After 3rd rotation the array contents are 4 5 6 7 1 2 3
-----------------------End of Output----------------------------
So after rotating by 3, the elements in the new array will appear in this sequence:
4 5 6 7 1 2 3
import java.util.*;
public class Main{
//Method to rotate array by one
static void RotatebyOne(int arr[], int n)
{
int i, temp;
// storing the first element in a temporary variable
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
public static void rotateArray(int x[],int n) {
//Rotating array one by one
for(int i=0;i<n;++i) {
System.out.print("After " + (i+1) + " rotation the array contents are ");
RotatebyOne(x,x.length);
//printing the array
for(int j=0;j<x.length;++j) {
System.out.print(x[j] + " ");
}
System.out.println();
}
System.out.print("So after rotating by " + n + ", the elements in the new array will appear in this sequence: ");
//printing the array
for(int i=0;i<x.length;++i) {
System.out.print(x[i] + " ");
}
System.out.println();
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int even=0,odd=0,c=0;
int x[] = new int[7];
for(int i=0;i<x.length;++i) {
//assigning random values to the array between 1 to 100
x[i] = (int) (Math.random() * (100 -1 + 1) + 1) ;
// calculating sum of elements at even and odd places
if(i%2==0)
even += x[i];
else {
odd += x[i];
c++;
}
}
System.out.print("The randomly generated integers in array are: ");
for(int i=0;i<x.length;++i) {
System.out.print(x[i] + " ");
}
System.out.println("\nSum of numbers at even indexes = " + even);
System.out.println("Average of numbers at odd indexes = " + (double)odd/c);
System.out.print("Enter rotation count: ");
//Reading input for n
int n = input.nextInt();
System.out.println("Calling rotateArray with rotation count as " + n + ".....");
//Calling rotateArray method to rotate the array n times
rotateArray(x,n);
}
}
OUTPUT: