If else and variables practice

I am new to programming and after reading the tutorial for "if else" commands I wrote this small program that checks for the largest number that was put in from the user. It is working, but are there a better way to code this using only variables and if else commands?


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
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

int main()
{
    int firstNumber;
    cout << " Enter the first number:";
    cin >> firstNumber;
    
    int secondNumber;
    cout << " Enter the second number:";
    cin >> secondNumber;
    
    int thirdNumber;
    cout << " Enter the third number:";
    cin >> thirdNumber;
    
if (firstNumber > secondNumber && firstNumber > thirdNumber)
{
                cout << " The largest number was the first number: " << firstNumber <<endl;
                }
                else if (secondNumber > firstNumber && secondNumber > thirdNumber)
                {
                        cout << "The largest number was the second number: " << secondNumber << endl;
                        }
                        else if (thirdNumber > firstNumber && thirdNumber > secondNumber)
                        {
                             cout << "The largest number was the third number: " << thirdNumber << endl;
                             }
                             
                             
                             
    
    system("PAUSE");
    
    return 0;
}
using only variables and if else commands

What do you mean by that? Does that exclude loops?

The problem with your code is that it gets increasingly more complicated to extend your program to handle four, five or more numbers.

The following code works with any amount of numbers with no changes to the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{	int howmany;
	int highest = 0;
	int	number; 

	cout << "How many numbers: ";
	cin >> howmany;
	for (int i=0;i<howmany; i++)
	{	cout << "Enter number " << i+1 << ": ";
		cin >> number;
		if (number > highest) 
			highest = number;
	}
	cout << "The largest number was: " << highest << endl;  
    system("PAUSE");    
    return 0;
}

Last edited on
Yes, excluding the loops. It was a practice challenge I read on some other site. I though it would be a good practice to understand how if else can be used.

Thanks for the loop program. I will try to make one on my own later on.
Topic archived. No new replies allowed.