Shorten my code, i want to compare my work to yours.
Mar 5, 2019 at 1:09am Mar 5, 2019 at 1:09am UTC
any idea on how to shorten this 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 num1, num2, num3;
cout << "Enter three numbers: \n " ;
cin >> num1;
cin >> num2;
cin >> num3;
cout << num1 << "\n" ;
cout << num2 << "\n" ;
cout << num3 << "\n" ;
return 0;
}
Mar 5, 2019 at 4:33am Mar 5, 2019 at 4:33am UTC
You can use a for loop and arrays.
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main() {
const size_t foo = 3;
int bar[foo];
std::cout << "Enter " << foo << " numbers: " ;
for (size_t i = 0; i < foo; i++)
std::cin >> bar[i];
for (auto i : bar)
std::cout << i << std::endl;
return 0;
}
$ g++ main.cpp
$ ./a.out
Enter 3 numbers: 30 60 90
30
60
90
$
Mar 5, 2019 at 12:34pm Mar 5, 2019 at 12:34pm UTC
This would be shorter, but I tend to think the best code, in any project, is the most readable and the most maintainable; that is, I prefer clarity over brevity if there's a choice.
Still, being as you asked:
1 2 3 4 5 6 7 8 9
#include <iostream>
int main(){
int n[3];
std::cout << "Enter three numbers:\n" ;
std::cin >> n[0] >> n[1] >> n[2];
std::cout << "\n" << n[0] << "\n" << n[1] << "\n" << n[2] << "\n" ;
return 0;
}
Enter three numbers:
10
4
56
10
4
56
or maybe ...
1 2 3 4 5 6 7 8 9
#include <iostream>
int main(){
int n[3];
std::cout << "Enter three numbers:\n" ;
std::cin >> n[0] >> n[1] >> n[2];
for (auto i:n) std::cout <<n[i] << "\n" ;
return 0;
}
Last edited on Mar 5, 2019 at 1:05pm Mar 5, 2019 at 1:05pm UTC
Mar 5, 2019 at 2:52pm Mar 5, 2019 at 2:52pm UTC
It's usually helpful to look carefully at the problem and solve exactly what's for and no more. So while my solution is pedantic, I hope it illustrates the idea.
- Since you don't do anything with the numbers, there's no need for an array.
- Unless you really need the output to go the screen then there's no need to delay printing it:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
int main(){
int n;
std::cout << "Enter three numbers:\n" ;
for (int i=0; i<3; ++i) {
std::cin >> n;
std::cout << n << '\n' ;
}
}
To go even further, you could just print "Enter three numbers:\n" and then copy cin to cout.
Mar 5, 2019 at 3:35pm Mar 5, 2019 at 3:35pm UTC
@
jesi
So far, yours is the cleanest code here that doesn’t change program behavior.
Focus on writing clean, easy-to-read code over being tricky. The only variation I might consider is chaining the operators:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
using namespace std;
int main()
{
int num1, num2, num3;
cout << "Enter three numbers: \n " ;
cin >> num1
>> num2
>> num3;
cout << num1 << "\n"
<< num2 << "\n"
<< num3 << "\n" ;
}
If you are inclined to scrunch stuff on one line then you could do that too... but scrunching makes things less readable, IMHO.
Hope this helps.
Topic archived. No new replies allowed.