Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

While loop 2

Status
Not open for further replies.

malola123

Technical User
Feb 16, 2007
17
CA
Hi,

Im normally pretty good with loops, but for some reason, im not able to understand this loop.

using System;

class Ques
{
public static void Main()
{
int i = 17;
while(i != 1)
{
Console.WriteLine("{0}", i);
i = 3*i + 1;
while(i%2 == 0)
i/=2;
}
}
}

The answer for this loop is: 17, 13, 5.

Can someone explain the process in each iteration? Thanks!

 
Yep..

At the begginning, i=17.

The while(i != 1) will loop as long as i is not equal to 1.

Print the 'i' (17).

Do calculations.. i = 3*17 + 1 = 51+1 = 52

The following:
while(i%2 == 0)
i/=2;

will loop (and do the i = i/2) as long as the module of i by 2 is equal to 0. So, in other words, it will loop as long as the 'i' is even number!

So...
'i' becomes 52/2 = 26 (even)
'i' becomes 26/2 = 13 (odd.. so stop) and go to the outer loop because 13 is not equal to 1.

Print the 'i' (13).

i = 3*13 + 1 = 39 + 1 = 40 (even ! so go in the other loop)

'i' becomes 40/2 = 20 (even)
'i' becomes 20/2 = 10 (even)
'i' becomes 10/2 = 5 (odd, stop now and go to the outer loop) because 13 is not equal to 1.

i = 3*5 + 1 = 15+1 = 16

'i' becomes 16/2 = 8 (even)
'i' becomes 8/2 = 4 (even)
'i' becomes 4/2 = 2 (even)
'i' becomes 2/2 = 1 (odd, stop now and do NOT go to the outer loop) because 13 is equal to 1).

So nothing is printed now, because the Console.WriteLine("{0}", i); is in the loop that we did not entered.


:) Phewww!
 
Wow, that was a great explanation!!..Thanks!!! :)
 
Thanks.

Forgot something...

Above:
i = 3*5 + 1 = 15+1 = 16
Put:
Print the 'i' (5).

 
Is this for homework?

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
lol...no no..im just trying to learn c# for myself...im a newbie to programming!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top