Nested loops exercise

So I can't seem to find the reason why when i input one into this program, it prints the "-" repeated until the compiler quits. I've spot checked all my loops to ensure that the only one that should be executing is the first print "+".
Let me know if you see anything I missed!

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
41
42
43
44
45
46
47
48
49
  #include <iostream>

using namespace std;

int main(int,char**) {
	int z=0;
	double sum;
	while(z!=5){
	    int x;
	    cout << "Enter length between 0 and 64 (-1 to exit): ";
	    cin >> x;
	    sum+=x;
	    if (x>-1&&x<64){
	       if (x>0){
	        cout << "+";
	       }
	       int n=0;
	       for (x>=3;x-2!=n;++n){
	            cout << "-";
	        }
	        if (x>=2){
	        cout << "+" << endl;
	        }
        int o=0;
        for (x>=3;x-2!=o;++o) {
            cout << "|";
            int m=0;
            do {
                cout << " ";
                ++m;
            }while (x-2!=m);
            cout << "|" << endl;
        }
        ++z;
        int u=0;
        if (x>1){
	        cout << "+";
	    for (x>=3;x-2!=u;++u){
	            cout << "-";
	        }
	        cout << "+" << endl;
	    }
	    }
	    else {
	        cout << "Length must be between 0 and 64 inclusive, or enter -1 to exit." << endl;
	    }
} 
cout << "5 squares printed.  Average length: " << sum/5 << endl;
}





Thanks!
Let me know if you see anything I missed!

Line 7 double sum; sum is not initialised. It contains garbage.

Line 10:
 
    cout << "Enter length between 0 and 64 (-1 to exit): ";

User input of -1 should terminate the program, but there is no logic to check and carry out that.

Line 12, sum+=x; x is added to sum even if x invalid (out of range).

Lines 18, 25 and 38.
1
2
3
    for (x>=3;x-2!=n;++n){
    for (x>=3;x-2!=o;++o) {
    for (x>=3;x-2!=u;++u){

Unusual for-loop construction. This is a logic error, it seems the intention of this
1
2
3
4
    int n=0;
    for (x>=3;x-2!=n;++n){
        cout << "-";
    }
is to only execute the loop if x >= 3.

You could re-structure it like this:
1
2
3
4
5
    if (x >= 3)
        for (int n = 0; x-2 != n; ++n)
        {
            cout << "-";
        }

Similarly with the other loops.

Line 48:
 
    cout << "5 squares printed.  Average length: " << sum/5 << endl;

Number of squares printed is stored in the variable z. It need not be 5. Likewise the average is sum/z, but only if z is non-zero.
Last edited on
Topic archived. No new replies allowed.