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

## All 2 Replies

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