I'm trying to find the highest score from 6 scores taken from a text file. The code I have works, but it looks so inefficient. There should be a way to do it with a for loop,

for (int i = 0; i < count; i++)
    if (max > score)
        max = score;

something like that. But something about this doesnt seem like it would work to me.

here is main and the big chunk of code to find the highest.


string name;
int score1;
int score2;
int score3;
int score4;
int score5;
int score6;
int max;

while(infile.peek() !=EOF)
    infile >> name;
    infile >> score1;
    infile >> score2;
    infile >> score3;
    infile >> score4;
    infile >> score5;
    infile >> score6;

     if(score1>=score2 && score1>=score3 && score1>=score4 && score1>=score5 && score1>=score6) 
                max =score1; 
        else if(score2>=score3 && score2>=score4 && score2>=score5 && score2>=score6) 
        else if(score3>=score4 && score3>=score5 && score3>=score6) 
        else if(score4>=score5 && score4>=score6) 
        else if(score5>=score6) 

Recommended Answers

All 4 Replies

You can use a loop but you need to store your scores in an array

Yea, I know how to do that, and would make life easier, but we haven't "learned" that yet so I can't use that.

Well you can kinda unwind the loop and make it look like this

max = score1;
if(score2 > max)
    max = score2;
if(score3 > max)
    max = score2;
if(score4 > max)
    max = score4;
if(score5 > max)
    max = score5;
if(score6 > max)
    max = score6;

I'm not sure if it any more efficient than what you have but it seems to need fewer comparisons

This ^ I like!

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.