Max of Numbers

So I have a simple problem that I've been working on and I'm having some scope issues. My program is supposed to have the user input how many numbers he/she wants to enter and then let the user enter an initial number so that I can hold the max value. Then the for loop starts and attempts to store the maximum number throughout the loop. The problem I have is that at the end of the loop when I want to pull the max number out, I can't because of the variables within the loop are gone once the loop ends. How do I pull the "max" out of the loop and output it for a final answer? Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

int main()
{
	cout << "This program finds the maximum number." << endl << endl;

	int amount;
	cout << "How many numbers? ";
	cin >> amount;

	float number, max;
	cout << "Number: ";
	cin >> number;

	max = number;

	for( float i = 0; i < (amount - 1); i++ )
	{
		float number;
		cout << "Number: ";
		cin >> number;

		if(max > number)
			max = number;
		else
			number = max;
	}
	cout << "The largest number is " << max;
}


If you run the code you can see that when I first set a value to "max" it stays that value that is outside of the loop. The max inside the loop simply does nothing. What do I do to get "max" to change in the loop and then call that "max" outside of the loop to use it as output?
Line 24 is wrong. You are checking if max is less than the number you enter. Correct code:
1
2
3
		if(max < number) // read: if max is less than number,then max =number
			max = number;
// 'else' statement is not needed. it doesn't do anything useful 
Last edited on
Ok so you can pull a variable out of the scope of the loop I just had the wrong condition. Thank you.
Topic archived. No new replies allowed.