Nested loop to execute during loop

Hi, I read the recommendations on homework, and he clearly states that this is homework. This is homework, I spent the last 45 minutes trying again and again. I hit the wall and need help.

My purpose was to take this code that came from the Double For loop and convert it to a while loop nested in the for loop. I have successfully completed this. However, the 3rd part should take this code and make an external for loop in the do while loop. The output should increment "#" each line so if the input was "4"

#
##
###
####

Below is my code that I wrote that I need to do an external for loop in a do while loop:

int main()
{
    int side;

    cout << "Enter a number: ";
    cin >> side;

    for (int i = 0; i < side; i++)
    {
        int j = i;
        while(j >= 0)
        {
            cout << "#";
            j--;
        }
        cout << "\n";
    }
}

This is my attempt:

int main()
{
    int side;
    int i;

    cout << "Enter a number: ";
    cin >> side;
    int j=side;
    do
    {
        while(j >= 0)
        {
            cout << "#";
            j--;
        }
        cout << "\n";
        i++;
    }
    while(j >= side);
}

, , , , , . . .

+4
4

, , :

int i; //not initialized!
/*...*/
i++;

do-while.

So while(j >= side); > while (i >= side);

, . , , i , , . , while (i < side);

: int j=side;, j, reset, while-while, i, ....

, :

#include <iostream>
using namespace std;

int main()
{
    int side;
    int i = 0;

    cout << "Enter a number: ";
    cin >> side;
    do
    {
        int j = i;
        while (j >= 0)
        {
            cout << "#";
            j--;
        }
        cout << "\n";
        i++;
    } while (i < side);

    return 0;
}

:

Enter a number: 10
#
##
###
####
#####
######
#######
########
#########
##########
+1

int main()
{
    int side;
    int i = 0;
    cout << "Enter a number: ";
    cin >> side;

    do
    {
        int j = i;
        while(j >= 0)
        {
           cout << "#";
           j--;
        }
        cout << "\n";
        i++;
    }while(i < side)
}

(i=0), (i < side) (i++); i?

+1
  • while(j >= side); it should be while(i <= side);
  • jmust be initialized in each iteration of the outer loop ( j = i;)
  • int j=side; not required.

A friendly suggestion is to describe your variables and functions descriptively - rowand columnmuch better than iand j.

0
source

They answer above, solve your problem, but let me show you a shorter way to do something:

int main()
{
    int side;

    std::cout << "Enter a number: ";
    std::cin >> side;

    int row = 1;
    do
    {
        int col = 0;
        while (col++ != row)
        {
            std::cout << "#";
        }
        std::cout << "\n";
    } while (row++ != side); //This way, the condition is checked (row != side), and then row is incremented
}
0
source

Source: https://habr.com/ru/post/1657592/


All Articles