Printing the maximum numbers after user's input using Array? guys I'm struggling with this program.

here's what I wrote but it's not working..

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    int maxArray[10];
    int maxValue=0;
    for(int j=0; j<4; j++)
    {
        cout<<"Enter a number: ";
        cin>>maxArray[j];

         if(maxArray[j]>maxValue)
        {
            maxValue=maxArray[j];
          cout << "The highest value is: " << maxValue;
        }   

    }  

    getch();
    return 0;

}

Recommended Answers

All 2 Replies

You have an array of 10, but the loop counter only counts to 4. Any reason for that?

here's what I wrote but it's not working..

what's not working? It should print something on the screen every time you enter a number that is greater than any previous number entered.

If all you want the program to do is tell you only one time what the highest number is, you will need another loop. First loop like you have it but delete line 10. After that loop finished write another loop that scans all the array looking for the largest number. When that loop is finished then print the largest value like you did on line 10.

so you program should do this:

  • Loop to enter data into the array
  • Loop to find largest value in the array
  • Print the largest value

Try this:

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    int maxArray[10];
    int maxValue=0;
    for(int j=0; j<4; j++)
    {
        cout<<"Enter a number: ";
        cin>>maxArray[j];
    }
    for (int j = 0; j < 4; j++)
    {
        if(maxArray[j]>maxValue)
        {
            maxValue=maxArray[j];
        }   
    }
    cout << "The highest value is: " << maxValue << endl;
    getch();
    return 0;
}

Yes, you could evaluate the maxvalue in the first loop, but I like to keep my input, evaluation, and output loops separate. Just personal preference, and it helps me to keep "domains of responsibility" distinct.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.