I have the following assignment:
A program that takes four (4) inputs then using a conditional statement does the following:
- Display the values that are below or equal to 25.
- Multiply the values that are below 20 with each other.
- Add the values that are above 25 with each other.
I've successfully solved all of them as they're pretty easy, however I want to ask a couple of things along with getting feedback from you.
I know that using less variables is always a better choice if you can do it, it might not matter on such small scale projects but I believe it's useful to get in the habit head-on. So in this specific example code, can I use a single var instead of 4 different ones? I know I can for the second and third tasks, however what about the third? Can I still list the inputs that are less than or equal to 25?
What tips do you have to make the code readable and even more easy to understand?
Also keep in mind that using loops, arrays, functions ... is not allowed so I would be glad if we keep our discussion limited to conditionals only.
#include "stdafx.h"
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
float val1, val2, val3, val4;
float sum = 0, multiply = 1;
cout << "Enter the first number: ";
cin >> val1;
if(val1 < 20) {
multiply *= val1;
} else if(val1 > 25) {
sum += val1;
}
cout << "Enter the second number: ";
cin >> val2;
if(val2 < 20) {
multiply *= val2;
} else if(val2 > 25) {
sum += val2;
}
cout << "Enter the third number: ";
cin >> val3;
if(val3 < 20) {
multiply *= val3;
} else if(val1 > 25) {
sum += val3;
}
cout << "Enter the fourth number: ";
cin >> val4;
if(val4 < 20) {
multiply *= val4;
} else if(val4 > 25) {
sum += val4;
}
if(val1 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val1 << endl;
if(val2 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val2 << endl;
if(val3 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val3 << endl;
if(val4 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val4 << endl;
cout << "When we multiply the numbers below 20 we get: " << multiply << endl;
cout << "When we add the numbers above 25 we get: " << sum << endl;
return 0;
}