Home > Software engineering >  comparing one array element with the next element to find what is the biggest element
comparing one array element with the next element to find what is the biggest element

Time:10-30

I'm trying to find a way to iterating while comparing the element with the next element to find what is the biggest element in the array. But, the output i want keep repeating as much as the loop run.

int main(){
    int array[4];

    for ( int i = 0; i < 4; i  ){
        cin >> array[i];
    }
    for (int i:array){
        for (int j = 1; j < 4; j  ){
            if (i < array[j]){
               break;
            }
            if (i > array[j] ){
                cout << i;
            }
        }
    }
}

CodePudding user response:

You can use the following program to find the biggest element in the array. Note that there is no need to use two for loops as you did in your code snippet.

#include <iostream>

int main()
{
    int array[4] = {1,10, 13, 2};
    
    int arraySize = sizeof(array)/sizeof(int);//note that you can also use std::size() with C  17 
    
    int startingValue = array[0];
    
    for(int i = 1; i < arraySize;   i)//start from 1 instead of 0 since we already have array[0]
    {
        if(array[i] > startingValue)
        {
            startingValue = array[i];
        }
    }


    //print out the biggest value 
    std::cout<<"the biggest element in the array is: "<<startingValue<<std::endl;
    return 0;
}

Your program is reapeating output because you have the cout inside the if which is satisfied multiple times(depending upon how big the array is and what elements it contains). For example, if you try your example on the array int array[] = {23,2,13,6,52,9,3,78}; then the output of your program will be 2323231313652525293787878 . So the output is reapeating more than 2 times. You can instead use the version i gave that uses only 1 for loop and prints the correct biggest element only once.

Note that you can also use std::size with C 17 while sizeof(array)/sizeof(int) works with all C versions.

  •  Tags:  
  • c
  • Related