Link to home
Start Free TrialLog in
Avatar of shahedny
shahedny

asked on

while loop

I am trying to solve this problem :

*****
*****
*****
*****
*****

and another one should look like this :
*****
*    *
*    *
*    *
*****

This is what i am trying but getting only this result :
*****
*
*
*
*

Please help me out with this:
#include<iostream>
using namespace std;

int main()
{

int i=0;
while (i<4)
{
cout<<'*';
i++;
}
int j=0;
while (j<5)
{
cout<<'*';
j++;
cout<<endl;
i++;
}
return 0;
}
Avatar of sunnycoder
sunnycoder
Flag of India image

I would have expected you to get

****
*****

You are basically setting up two loos - 0 to 3 and 0 to 4 and printing * in each iteration

For
*****
*****
*****
*****
*****
You need two nested loops each from 0 to 4. Outer loop would be responsible for printing a line and inner loop will print the *

nested loops means loop within loop ... something like

while (...)
{
     while(...)
     {
        ....
     }
}
Nest your i loop (while) inside the j loop, not sequentially.
I would  type it out, but then, is it ethical for us to do your homework for you?
Avatar of shahedny
shahedny

ASKER

ofcourse it is not.Let me try what you have just said and see if i can do this.
i had to figure this one out...i even still have the solution because it was a homework assignment for me...lol...but my solution was in java...but since i know c++, the looping in java and c++ are the same...what part are you having trouble with?  we can't give direct solutions for homework...
i am having problem with the nested loop. i am only getting till this part
*****
*
*
*
*
i have wrote this-
#include<iostream>
using namespace std;
         
int main()
         
{
        int i=0;
        int j=0;  
        while (i<4)
        {
        cout<<'*';
        i++;
        }
        while (j<5)
        {
        cout<<'*';
        j++;
        cout<<endl;
        i++;
        }
return 0;
}

---Where is my mistake?please tell me as i am not getting this-
*****
*****
*****
*****
*****
You did not nest the loops ... Nesting means one loop within another


while (...)
{
     while(...) // This while begins before the previous while has ended
     {
        ....
     }
}

Open in new window

i tried nesting the loop the way you said it-
#include<iostream>
using namespace std;
       
int main()
       
{
        int i=0;  
        int j=0;
        while (i<4)
        {
        cout<<'*';
        i++;
        while (j<5)
        {
        cout<<'*';
        j++;
        cout<<endl;
        i++;
        }
}
return 0;
}
__it is giving me only one line
*
*
*
*
*

PLs set the indentation right ... it makes the code readable

int main()
{
        int i=0;  
        int j=0;
        while (i<4)
        {
            cout<<'*'; //you want to print * in the inner loop - Inner loop is supposed to print *, outer loop is supposed to print newlines. Basically outer loop moves you to different lines.
            i++;  //remove this. Generally loop counters are incremented towards end of the loop.
            while (j<5)
            {
                cout<<'*';
                j++;
                cout<<endl; // this needs to be part of outer loop - near end of it
                i++; //why are you incrementing i here? Increment it at the end of outer loop
            }
        }
        return 0;
}

Open in new window

my code looks like this now-
#include<iostream>
using namespace std;
int main()
{
        int i=0;
        int j=0;
        while (i<4)
        {
            cout<<endl;

            while (j<5)
            {
                cout<<'*';
                j++;

            }
        cout<<endl;
        i++;
        }
return 0;
}
--- this code generates this result
****
##What am i doing wrong?
             
ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think 3 years ago I coded this and maybe can help you
works as you want and  it is dynamic ;)
<code removed by sunnycoder>

Open in new window

I know agreement and help pages, I wasn't aware it's homework.... Just that... Not needed to go so far
Not needed, it's ok
excellent bro.i got the first part which is
*****
*****
*****
*****
*****
but now i need to do it like this
*****
*    *
*    *
*    *
*****
this is the code i have put in-

#include<iostream>
using namespace std;
int main()
{
        int i=0;
       while (i<5)

        {
        int j=0;
                while (j<5)
                {
                cout<<'*';
                j++;
                }
                cout<<endl;
                i++;
                }

        while (j<5)
    {
        if (j==1)||(j==5);
        cout<<'*';
        else
        cout<<" ";
        j++;
        }
        return 0;
}
__but this is giving me this error-
123.cpp: In function `int main()':
123.cpp:18: error: `j' was not declared in this scope
123.cpp:21: error: expected primary-expression before '||' token
123.cpp:23: error: expected primary-expression before "else"
123.cpp:23: error: expected `;' before "else"
Pls get the indentation right. When you declare a variable, its scope/visibility is limited to the pair of braces that enclose it ... Here you declared j inside a while loop - so it is limited in scope to this loop. You cannot use it the second while loop.
If you need to use a variable in both the loops, declare it before first loop.

Code for second output would similar to first one except that instead of printing all * in all lines, you need to print only the first and last * in all but first and last lines :-)
now i tried this-
#include<iostream>
using namespace std;
int main()
{
        int i=0;
       while (i<5)
        {
        int j=0;
                while (j<5)
                {
                cout<<'*';
                j++;
                }
                cout<<endl;
                i++;

        //int j=0;
        j=0;
        while (j<5)
    {
        if
        ((j==0)||(j==5))
        cout<<'*';
        else
        cout<<" ";
        j++;
        }  
        }
    return 0;
}
     this is giving me this picture-
*****
*    *****
*    *****
*    *****
*    *****



your current code organization is
while()
{
    while()
    {
    }
     while()
     {
     }
}

What you need is
while()
{
    while()
    {
    }
}
while()
{
    while()
    {
    }
}

Get your code indentation right. It is a strain to read unindented code.
As sunnycoder asked repeatedly, PLEASE DO SOMETHING WITH YOUR INDENTATION. You may think that it is not important. However, you will not make the things clear in your head if they do not cry to you from the source code.  This is important especially for beginners. After that, you will see your errors. Put some short comments to the end of important lines.

Use 4 spaces for each indentation level or use some decent editor which supports automatic indentation for C++.
Well, sunnycoder asked again :)) Do listen to him. The indentation is one of the things that makes or readable or obscure code.
i thought there is only 3 while loop :(
where am i going to get the 4th one
This is what i have now -

#include<iostream>
using namespace std;
int main()  
{
       
         int i=0;
         while (i<5)
         {
         int j=0;
         while (j<5)
         {
         cout<<'*';
         j++;
         }
         cout<<endl;
         i++;

                while (j<5)
                {
                if
                ((j==0)||(j==5))
                cout<<'*';
                else
                cout<<" ";
                j++;}
                }

        return 0;
}

But no change in result --
*****
*****
*****
*****
*****
stays the same
solution to 2nd problem is structured exactly like the first one.
So you have the outer loop that handles lines and inner loop that handles printing *
In this code, third loop never gets executed - by the time control reaches third loop, value of j is 5.

Use the exactly same loop setup that you used for first problem. Only printing of * is different and you already have that "nearly" right ;-) ... nearly because your loop condition is j<5 and inside loop you have a check for j == 5.
so on second loop instead of J<5 i should put ((j==0)||j==5)) ??
loop condition is correct .. it is the if check that needs to be modified. Value of j can never b 5 inside the loop. It is controlled by the loop and will range from 0 to 4.
It will be good practice if you start dry running your code .. i.e. sit with a pen and paper and trace the execution of the program by hand. This will give you clarity about role and impact of each statement.
where exactly is the problem?because i am tired of trying hundreds of ways
    while (j<5)  //here??
                {
                if
                ((j==0)||(j==5))    //or here??
                cout<<'*';
                else
                cout<<" ";
                j++;}
                }
>> because i am tired of trying hundreds of ways

May I offer a small bit of advice ? Instead of trying/guessing, try to understand what is going on in the code. Follow what the code does step by step (for every iteration of every loop), draw the output on a piece of paper. And you'll find it a lot easier to modify the code to do what you want.

Remember that a large part of writing code is thinking about what you will write (how you'll solve the problem, and how that solution can be expressed in code). Actually writing the code should come last (once you've figured it all out).
hmm other people are also telling me that but i get even more confused that way :(
>> but i get even more confused that way :(

Just take your time for it. Take things one step at a time - rushing things causes confusion.
It often help with solving such a  problem to approach it "as if you were doing it on paper with pencil in your hand". In other words, you will not solve it programmatically if you cannot find regularities in the process when doing it by hand.

Say you want to do draw

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

You probably do it line by line by writing the numerals one by one, right? Now, the regularity is "start at the first line, write the 1, move to the next position, write 2, etc.; now next line, write 1, ...; write so much lines that you need.

In the terms of programming: writing the line which length is prescribed by some value means "loop i times and write the numeral and move to the next position; write the end of line". And writing the j lines means "loop j times and write the line (using the above loop).

In your case, you or replace all the numerals by the stars (the filled rectangle) or you write stars for all 1's and 5's  and for all positions on the first line and the last line.

Now, as Infinity08 said ... one simple step at a time.

1) A program that displays one star (simple, you know it).
2) Add the loop to the 1) that writes n stars plus the end of line.
3) Modify the previous step so that you write the star only at the first and last positions by adding some test and writing star and space alternatively.
4) Modify the 3) so that you enhance the test by adding condition on j (to add stars for all positions for the first and last line). Just assign the j in front of the single loop you wrote so far -- test if you know how to write one line.

Now you know how to write whatever line. The last simple step is...

5) Write the outer loop through j. (Now you do not fill the j by assigning explicitly in front of your i-loop. It will be filled by the outer loop.

You have done all of the steps. However, you did not combine them well. Having this in your mind, try to find what the steps in your older solution are bad, strange, misplaced...