I have been doing some exercises out of the Head First C# book and have just done this exercise where you write a complete sentence using a while loop. The book dosent explain how the while loop puts together the string. I am looking if someone could please explain the logic to me and the process the method uses to create this string. I understand that 'x' has been set to 0 and that the 'while' condition is that while x < 4 run the loop. It confuses me with the logic of this one.

Here is the method:

private void button1_Click(object sender, EventArgs e)
        {
            int x = 0;
            String poem = "";

            while(x < 4)
            {
                poem = poem + "a";//1.

                if(x < 1)//2.
                {
                    poem = poem + " ";
                }

                poem = poem + "n";//3.

                if(x > 1)
                {
                    poem = poem + " oyster";
                    x = x + 2;
                }

                if(x == 1)
                {
                    poem = poem + "noys ";
                }

                if(x < 1)
                {
                    poem = poem + "oise ";
                }
                x = x + 1;
            }
            MessageBox.Show(poem);
        }
    }

Thankyou

It should be fairly understandable if you buld the string yourself, keeping track of x at the same time but I'll try to give a coherent explanation.

On the first loop x == 0
an A is always added so "a" becomes the first letter.
X < 1 so a space is added : "a "
An 'n' is always added: "a n"
Only the x < 1 if statement is called as x == 0 so oise is added: 'a noise '

Second loop, x = 1
an 'a' is always added: 'a noise a'
an 'n' is always added: 'a noise an'
the only if statement to fire is x == 1 so noys is added: 'a noise annoys '

Third loop x == 2
add an a
add an n : 'a noise annoys an'
x > 1 if statement adds 'oyster' : 'a noise annoys an oyster'
x increments to 4 so loop exits

Does that help?

That helps! thankyou!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.