Hello, all! I just submitted an assignment for school, and I have a feeling that I took a rather bush-league approach to coding it. After messing with
<iomanip>
a bit more, I took what may or may not be considered a shortcut on the second for-loop. Here's what I did:
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
|
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
int n;
char ch = '@';
cout << "Choose an odd number between 5 and 21: ";
cin >> n;
cout << endl;
for (int i = n; i < 5 || i > 21 || i % 2 == 0; ) {
exit(0);
}
for (int i = n; i >= 1 ; i = i - 2) {
cout << string(i, ch);
cout << endl;
}
cout << endl;
for (int i = n; i >= 1 ; i = i - 1) {
cout << setw(n) << right << string(i, ch);
cout << endl;
}
cout << endl;
system("PAUSE");
return 0;
}
|
As you can see, the user will enter a number between 5 and 21 that's odd, and the rest goes from there. I looked around and found the
string(n, ch)
code as a suggestion for printing symbols like that, but I have a feeling that there might be a more efficient/straightforward way of doing the same thing. I spent quite a while trying to think of a way to do it, but multiplying '@' by "n" in my cout statement caused the program to show the symbol's binary value. I tried assigning "ch" to "i" in the loop, but it obviously didn't work because of the type conflict.
The second for-loop was supposed to replace the given symbol with spaces to get the effect you see here, and the right-justification probably wasn't what was wanted.
The other kicker was that we could only use
return
once. I originally put
return 0;
in the first loop, but that would (obviously) have kept me from using it at the end. I doubt that borrowing
exit()
is really a good idea, but I couldn't get
break;
to do what I needed.
If you run the program, the results appear exactly as requested, but one of the reasons I want to learn this language is because I want to get ideas of how to do the same thing many different ways. While this program is extremely simple, I would really like to see what ideas you all have regarding the loops. I'd also like your exit-strategies that don't resort to plain C. Any feedback is much appreciated!