Search code examples
c++for-loopnested-loops

Nested loops to display rows of 25 characters c++


Hello I'm having some trouble with my nested loops to output rows of 25 characters that a user selects. There are supposed to be 25 characters per line and the user inputs the amount of lines to be printed.

Also each line needs to be one tab more than the previous line.

Currently I am only able to get the program to output one line of characters, or it will display 25 lines of one character that is selected.

Please help. Any input is appreciated.

int lines=0, count=0, amount=0, symbol, i=0, j=0;

do {
    cout << "\nEnter number of lines to print: ";
    cin >> lines;
    if (lines < 5 ) {
        cout << "Please enter an integer greater than 5." << endl;
        system("pause");            
    }
    else if (lines >= 5) {
        cout << "\nEnter the number corresponding to the character you would like to display: ";
        cout << "\n 1. * \n 2. $ \n 3. # \n 4. ! \n 5. & \n ";
        cin >> symbol;

        for (i = 1; i <= 25; i++) {
            cout << symbol << " " ;
            count++;
            for (j = 1; j <= lines; j++) {
                cout << "" << endl;
            }
        }  
    }
} while (1);

Solution

  • You've got the nested loops the wrong way round.

    Try:

    // Iterate parent loop line by line
    for(j=1; j<=lines; j++){
        // Add tabs according to the line number
        for(int k=1; k<j; k++){
            cout << "\t";
        }
    
        // Print symbol 25 times each line
        for(i=1; i<=25; i++){
            cout << symbol << " ";
        }
        cout << endl;
    }