Confused About Sentinal Controlled Loop Problem

I'm currently working on a program for my computer science class. We need to
read several lines containing integers from a file and output to another file.
Each line ends with a negative number (the sentinel). For testing purposes, I'm
able to write the code that reads the input data and then sends that data to the
output file. However, the assignment asks us to find the minimum and maximum
number from each line and then print only those numbers to the file.

For whatever reason, I'm having trouble figuring-out how to find the minimum and
maximum numbers. The number of input integers may vary. It seems there should
be a way to compare the integers as they're read. For instance, something like:

1. Read the first number
2. Read the second number
3. compare 1st and 2nd number
4. Read the third number
5. etc., etc.
6. When a negative number is read, terminate the loop

Could anyone give me some guidance as to what I'm missing?


Say my input is: 11 55 44 88 12 90 89 55 100 -5.
The loop I've written so far prints:

The Maximum number is: 100
The Minimum number is: -5


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while (inData)
{
  int minimum = 0, maximum = 0, num = 0;
		
  while (num >= 0)
  {	
	inData >> num;

        if (num < minimum)
        minimum = num;
								
	if (num > maximum)
	maximum = num;
  }
			
  cout << "The Maximum Number is: " << maximum << endl;
  cout << "The Minimum Number is: " << minimum << endl;
	
}

So do you mean, when it reads a negative number, it'll terminate the program? I think you need this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
while (inData)
{
  int minimum = 0, maximum = 0, num = 0;
		
  while (num >= 0)
  {	
	inData >> num;

        if (num < minimum)
        minimum = num;

        if (minimum < 0)
        {
                  return(0);
        }
							
	if (num > maximum)
	maximum = num;
  }
			
  cout << "The Maximum Number is: " << maximum << endl;
  cout << "The Minimum Number is: " << minimum << endl;
	
}


Not sure if that's what you want though.
The minimum is initialized to zero. If the user was to input 1 2 3 4 5 6 7 8 9 10, the minimum would incorrectly be determined as 0. You should set it to a really large number, like (~0)>>1, which is universally and for all integral types the largest positive number.

The above code should have a break in line 14, not a return.
And I don't see the point of an outer while.
Last edited on
What you do, is initialise the minimum and maximum to the first integer of the 'line.'
Thanks for the help. I was finally able to make it work with the code below.
Sorry for the late reply... been busy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
maximum = 0;
minimum = 100;
count = 0;
		
while (num > 0)
{
count++;
	
   if (num > maximum)
   maximum = num;
			
   if (num < minimum)
   minimum = num;
}
Last edited on
Topic archived. No new replies allowed.