Ok so I am trying to write a basic program that will take a set of numbers, and determine the 2 largest numbers in the set. The stipulation is that I can use a while loop and some if statements. Oh and all the numbers have to be different (cannot have 2 equal numbers).
I came up with the following code:
Code:
int counter, num=0, largest=0, ndlargest=0, pnum=0;
while (counter != 10)
counter++;
printf("Please enter a number (cannot be equal to any other number):");
scanf("%d", &num);
if (num>largest){ \*this takes care of the largest number*\
largest = num;
else
if (num>ndlargest) \*this takes care of the 2nd largest number but only if descending*\
ndlargest = num;}
if (largest>pnum) \*should test the values for all cases other than the previous if*\
ndlargest=pnum;
pnum = largest;
Am I doing something wrong? Because when I consider the logic I think I have all the possibilities covered. However, when I compile and use 1,2,3 (counter != 3, for faster testing) I get 3 for largest value and 1 for 2nd largest. When I run the program with 3,2,1 as the input, I get the correct results. When I use 3,1,2, I get 3 as largest and 1 as 2nd largest.
Any help would be appreciated
Oh and I forgot to mention I use DMC as my compiler in DOS on a WindowsXP platform.