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
Following is the answer:
import java.util.Random;
import java.util.Scanner;
public class RotateArray {
void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++) {
leftRotatebyOne(arr, n);
printArray(arr, n);
System.out.println("\n");
}
}
void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
void sumOfEven(int arr[], int n){
int sum = 0;
double avg = 0;
int sum2 = 0;
int count = 0;
for(int i = 0 ; i < n ; i++){
if(i%2 == 0){
sum+= arr[i];
}else {
sum2+= arr[i];
count++;
}
}
System.out.println("\nSum of numbers at even indexes = " +
sum);
System.out.println("Average of numbers at odd indexes = " +
(sum2/count));
}
// Driver program to test above functions
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n, count;
RotateArray rotate = new RotateArray();
System.out.println("Enter array size:");
n = sc.nextInt();
int arr[] = new int[n];
Random rand = new Random();
for (int i = 0; i < n; i++) {
arr[i] = rand.nextInt(100-1) + 1;
}
System.out.println("The randomly generated integers in array are:
");
rotate.printArray(arr, n);
rotate.sumOfEven(arr, 7);
System.out.println("Enter rotation count: ");
count = sc.nextInt();
rotate.leftRotate(arr, count, n);
}
}
Output: