Bungling hollow square loop

Hey. So I'm supposed to build a program that will allow me to create a hollow square up to 20 characters long and wide depending on how many you enter. My instructor also wanted us to create a sentinel that would end the program if you entered a number below 1 or above 20. Here is the code.

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
50
51
52
53
54
55
56
57
58
59
 // Lab 2a, Typewriter Graphics
// Programmer: Jesse Burns
// Editor(s) used: JNotePad
// Compiler(s) used: VC++ 2010 Express

// The necessary C++ file library
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ios;

#include <string>
using std::string;

#include <cstdlib>

int main()
{
    // Jesse Burns, Lab 2a.
    cout << "Lab 2a, Typewriter Graphics\n";
    cout << "Programmer: Jesse Burns\n";
    cout << "Editor(s) used: JNotePad\n";
    cout << "Compiler(s) used: VC++ 2010 Express\n";
    cout << "File: " << __FILE__ << endl;
    cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl << endl;

    //Necessary input and counter for program to run
    int num;
    int i = 1;
    int j = 1;
    string buf;

    //Enter the size of the square you would like
    cout << "Enter a side of square between 1-20: "<<endl;
    cin >> buf; num = atof(buf.c_str());
    cin.ignore(1000, 10);

    //This code block creates the loop/counter loop that
    //will run for that size until you enter a sentinel
    //number that will end the program if you enter that
    //number that is not between 1-20
    while (true)
    {
    if (num < 1 || num > 20)break;
    {
    if ( i <= num && j <= num )
    {
    if ( i == 1 || i == num || j == 1 || j == num )
    cout << "*"<<endl;	// if any one out of 4 argument is true then it will print * otherwise ' '
    else
    cout << " "<<endl;	// prints if i=2 and j = 2
    i++;
    j++;
    }
    }
    }
    }


It builds the first and last character, but doesn't loop it all the way around. Plus, it's not returning so you can exit the program via enter key. Which is strange, because it first started doing that when I entered the while(true) loop with the if()break.

Any suggestions or pointers? Thanks.
remove <<endl from your print statements inside the while loop.

You also need to be using a nested loop to print the square properly. For each increment of i, you should be incrementing j from 1 to num.
Last edited on
Thank you.
Topic archived. No new replies allowed.