JAVA LANGUAGE In this assignment you will use the Java array class to help you.
ID: 3576981 • Letter: J
Question
JAVA LANGUAGE
In this assignment you will use the Java array class to help you. First, create an array of N random integers in the range of 1 to 100 (you can use the Java random class for this). Get the value of N from the user. Next ask the user to input a number in this range (1 to 100) and then search the array to locate all occurrences of the search number. For each occurrence, print out the number and the position at which it was found.
Then sort the array and search again, displaying all occurrences of the search number. If the search number is not found, then display a message to that effect.
Finally, print the sum of all of the numbers in the array.
Explanation / Answer
// Test.java
import java.util.*;
import java.util.Scanner;
public class Test
{
public static void sort(int[] array, int n)
{
for (int i = 0; i < n; i++ )
{
for (int j = 0; j < n; j++ )
{
if(array[i] > array[j])
{
int t = array[i];
array[i] = array[j];
array[j] = t;
}
}
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Random randomno = new Random();
System.out.print("Enter n: ");
int n=sc.nextInt();
int[] array = new int[n];
int sum = 0;
System.out.println("Random array: ");
for (int i = 0; i < n ;i++ )
{
array[i] = randomno.nextInt(100) + 1;
System.out.print(array[i] + " ");
sum = sum + array[i];
}
System.out.print(" Enter the number to search: ");
int search=sc.nextInt();
int flag = 0;
for (int i = 0; i < n; i++ )
{
if(array[i] == search)
{
System.out.println(search + " found at index " + i);
flag = 1;
}
}
if(flag == 0)
System.out.println("Given number is not present in array");
System.out.print(" ");
System.out.println("Sorting array ");
sort(array,n);
flag = 0;
for (int i = 0; i < n; i++ )
{
if(array[i] == search)
{
System.out.println(search + " found at index " + i);
flag = 1;
}
}
if(flag == 0)
System.out.println("Given number is not present in array");
System.out.print(" ");
System.out.println("Sum of all numbers in array: " + sum );
}
}
/*
output:
Enter n: 20
Random array:
25 38 71 23 54 64 76 60 93 34 76 50 33 41 91 16 15 68 33 17
Enter the number to search: 60
60 found at index 7
Sorting array
60 found at index 7
Sum of all numbers in array: 978
Enter n: 20
Random array:
53 25 25 84 29 29 72 95 91 12 79 46 15 31 60 30 21 60 7 61
Enter the number to search: 45
Given number is not present in array
Sorting array
Given number is not present in array
Sum of all numbers in array: 925
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.