How do I find the maximum number in an array in Java - java

I am given the array measurements[]. I am supposed to write a for loop that goes through all the numbers and each time a number maximum is reached, the variable maximum is replaced. In the code I have so far, the output is saying that it cannot find the symbol i, but I thought that was the symbol I am supposed to use within a for-loop. Here is my code:
double maximum = measurements[0];
for (i = 0; i < measurements.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);

You can also do this using Java stream api :
double maximum = Arrays.stream(measurements).max();
System.out.println(maximum);
Or a more concise code:
double maximum = Double.MIN_VALUE;
for(double measurement : measurements) {
maximum = Math.max(maximum, measurement);
}
System.out.println(maximum);
Or, sort the array and return the last one
Arrays.sort(measurements);
System.out.println(measurements[measurements.length-1]);

you can try this -
class MaxNumber
{
public static void main(String args[])
{
int[] a = new int[] { 10, 3, 50, 14, 7, 90};
int max = a[0];
for(int i = 1; i < a.length;i++)
{
if(a[i] > max)
{
max = a[i];
}
}
System.out.println("Given Array is:");
for(int i = 0; i < a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("Max Number is:" + max);
}
}

You have not declared i inside the for loop or before the for loop.
double maximum = measurements[0];
for (int i = 0; i < measurements.length; i++) { //You can declare i here.
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also declare i before the for loop also

Related

How to delete minimum and maximum from array?

I'm a newbie in java. I'm trying to find minimum maximum element in array and then delete the minimum and maximum. This is the code I wrote, it's only working for maximum not for minimum.
public class delminmax {
public static void main(String[] args) {
int [] nums = {10,50,20,90,22};
int max = 0;
int min = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i]> max)
max = nums[i];
}
System.out.println("The max number is "+ max);
for (int i=0;i<nums.length;i++)
if (max==nums[i]) {
for (int j=i; j<nums.length-1;j++)
nums[j]= nums[j+1];
}
for (int i=0;i<nums.length-1;i++)
System.out.print(nums[i]+ " " + "\n");
for (int i=0; i<nums.length; i++) {
if (nums[i]< min)
min = nums[i];
}
System.out.println("The min number is "+ min);
for (int i=0;i<nums.length;i++)
if (min==nums[i]) {
for (int j=i; j<nums.length-1;j++)
nums[j]= nums[j+1];
}
for (int i=0;i<nums.length-1;i++)
System.out.println(nums[i] + " ");
}
}
You can't delete elements from an array, an array has a fixed length determined at creation time. You can instead create a new array with two fewer elements. You only need one loop to determine the min and max, but instead of doing so directly it's cleaner in my opinion to track the indices of the min and max elements. Then you can use a second loop to skip those elements when you copy nums to the new array. Like,
int[] nums = { 10, 50, 20, 90, 22 };
int mini = 0, maxi = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[mini]) {
mini = i;
}
if (nums[i] > nums[maxi]) {
maxi = i;
}
}
System.out.printf("The min = %d, the max = %d%n", nums[mini], nums[maxi]);
int[] newNums = new int[nums.length - 2]; // A new array, with two fewer elements
int p = 0;
for (int i = 0; i < nums.length; i++) {
if (i != mini && i != maxi) {
newNums[p++] = nums[i];
}
}
System.out.println(Arrays.toString(newNums));
Which outputs
The min = 10, the max = 90
[50, 20, 22]
Using Java 8
You can try by using streams with the approach below:
Approach Here:
I have converted the given array of Integers in the sorted list and then find the minimum and maximum integer from that list using any of the below method and then filtered the nums Array with these min and max integers and converted the filtered list back to Array of Integers.
To find the minimum and maximum integer in an array
1) By using IntSummaryStatistics from stream
IntSummaryStatistics statistics = Arrays.stream(nums).summaryStatistics();
int minNum = statistics.getMin();
int maxNum = statistics.getMax();
2) By Sorting the array
List<Integer> mainList = Arrays.stream(nums).boxed().sorted()
.collect(Collectors.toList());
int minNum = mainList.get(0);
int maxNum = mainList.get(mainList.size()-1);
Note: It will remove all the occurrences of minimum and maximum integer from the given array.
public class Test {
public static void main(String[] args) {
int [] nums = {10,50,90,20,5,90,22,5};
IntSummaryStatistics statistics = Arrays.stream(nums).summaryStatistics();
int minNum = statistics.getMin();
int maxNum = statistics.getMax();
int[] num = Arrays.stream(nums)
.filter(x -> x != minNum && x != maxNum).toArray();
for(int i:num){
System.out.print(i + " ");
}
}
}
Testcases:
Input: {10,50,90,20,5,90,22,5}
Output: 10 50 20 22
Input: {10, 50, 20, 90, 22}
Output: 50 20 22
Arrays are something whose length/size can't be changed. They are created with a fixed size which can't be modified. If you want to use the functionality you mentioned, it's better to go for a list, preferably ArrayList
List<Integer> list= new ArrayList<Integer>();
You can always return an ArrayList as an array if need be. You can search for functions like
list.toArray()

Sorting an array by number of digits in each element from largest to smallest using loops java

I'm trying to sort an array by the number of digits in each element from largest to smallest. This technically works but it seems to sort the array by value as well. For example, instead of printing out 1234 700 234 80 52, it should print 1234 234 700 52 80 as 234 is before 700 in the original array.
public class Sort {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {52, 234, 80, 700, 1234};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
//Math function is used to find length of each element
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(Math.log10(arr[i]) + 1 < Math.log10(arr[j]) + 1) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
The easiest way to find the length of the number is to convert it into a String and then call the method length on it.
int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3
But you also could do it by division. The following method takes a number and divides by multiples of 10.
divide by 1 (we have at least a length of 1)
division by 10 > 0 (we have at least a length of 2)
division by 100 > 0 (we have at least a length of 3)
...
the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.
As soon as number / i equals zero we return the counter value.
public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}
There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).
Use nested for-loop
public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}
if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}
I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).
Using Arrays.sort()
If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.
public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}
Using a recursive method
public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);
if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
// here you do a recursive call
sortArray(array);
}
}
}

Using a while-loop to find the maximum integer in an array

My assignment is to edit the following code to use a while-loop instead of a for loop to find the maximum in an array.
public static void main(String[] args) {
int[] numbers = {23, 101, 8, 25, 77, 5};
int max = 0;
for(int i=0; i<numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println(max);
}
So far, this is what I've been trying to do and have not come up with the solution.
public static void main(String[] args) {
int[] numbers = {23,101,8,25,77,5};
int i = 0;
int max = numbers[0];
while(i<=numbers.length) {
i=i+1;;
if (numbers[i] > max) {
max = numbers[i];
}
}
If anyone could provide me with some insight as to what I'm doing wrong I would appreciate it. I have little experience with while-loops.
Change the while condition slightly and move the i increment to after the actual loop body:
while(i < numbers.length) {
if (numbers[i] > max) {
max = numbers[i];
}
i = i + 1; // or simply i++;
}
Remove the <= in your while loop condition and move incrementing i to end of the loop.
while (i < numbers.length) {
if (numbers[i] > max) {
max = numbers[i];
}
i = i + 1;
}
The while loop is correct. Remove the double semicolon as that is a syntax error and use (sizeof(numbers.length)/sizeof(int)); line to obtain list length.

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}

How I can print largest sum in this Program?

package Message;
public class Example_R {
public static void main (String args[])
int n=1;
int input[]={1, 2, 1, 3, 4};
for (int j=0; j<=4; j++) {
int Add = 0;
for (int i=0; i<=4; i++) {
if (input[j] !=input[i]) {
Add+=input[i];
}
}
System.out.println(Add);
}
}
}
Output of This program is: 9 9 9 8 7 sum of all the other elements in the array that are not equal to the element.
Now I want to extend the program so I can print the Largest sum of any of it's element, (In this case 9 is the largest sum.) Do you have any suggestions? For this assignment I am restricted from using additional array, hashmap etc. not allowed. Arrays.sort(..)
Hint: use a variable that is holding "the largest sum reached so far". You will update it very time you compute a new sum.
You will need to find "how and when do I initialize this variable ?" and "how do I update it ?"
You probably want to create a separate method that you pass your "input[]" array to (left as an exercise). However when considering problems like this, first just consider how you would do it in english (or whatever your native language is). Write down that strategy (an "algorithm") and then implement that in Java.
public class Example_R {
public static void main(String args[]) {
int input[] = { 1, 2, 1, 3, 4 };
int largestSum = 0;
int currentSum;
for (int j = 0; j < input.length; j++) {
currentSum = 0;
for (int i = 0; i < input.length; i++) {
if (input[j] != input[i]) {
currentSum += input[i];
}
}
System.out.println("Sum of all values not equal to " + input[j]
+ " is: " + currentSum);
if (j == 0) {
largestSum = currentSum;
} else {
if (largestSum < currentSum) {
largestSum = currentSum;
}
}
}
System.out.println("The largest overall sum was " + largestSum);
}
}
You'll need a temporary variable to save the current highest number.
int temp = intArray[0]
for(int i : intArray)
{
if(i > temp)
temp = i;
}
Try this:
int n = 1,sum=0;
int[] input = { 1, 2, 1, 3, 4 };
for (int j = 0; j <= 4; j++){
int Add = 0;
for (int i = 0; i <= 4; i++){
if (input[j] != input[i])
Add += input[i];
}
if (sum < Add)
sum = Add;
}
After completing the second loop every time,the "sum" was updated if it is less than the current "add" value.
You can use variables of type Comparable and use the compareTo() method.
one.compareTo(two) will return > 0 if one > two
one.compareTo(two) will return < 0 if one < two
one.compareTo(two) will return 0 if one and two are equal
Go through the array, compare the current index with the previous index, and update a variable that holds the currentLargest value.

Categories

Resources