Rewrite a WHILE loop to FOR loop

Page 1 of 1

3 Replies - 3787 Views - Last Post: 30 June 2008 - 07:23 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=56231&amp;s=375f162e53b7739bbd3a70f3526c6fdd&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 idle_09

Reputation: 0
• Posts: 48
• Joined: 02-March 08

Rewrite a WHILE loop to FOR loop

Posted 29 June 2008 - 11:18 PM

I need to write a for loop but i am confused. The while loop follows:

```int factorial (int n)
{
int product = 1;
while (n > 0)
{
product = n * product;
n--;
}

return product;
}
```

I am thinking
```for (int n = 0; n > 0; n--)
{
product = n * product;
cout << product << endl;
}
```

Is This A Good Question/Topic? 0

Replies To: Rewrite a WHILE loop to FOR loop

#2 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

Re: Rewrite a WHILE loop to FOR loop

Posted 29 June 2008 - 11:24 PM

idle_09, on 30 Jun, 2008 - 11:48 AM, said:

I need to write a for loop but i am confused. The while loop follows:

int factorial (int n)
{
int product = 1;
while (n > 0)
{
product = n * product;
n--;
}

return product;
}

I am thinking

for (int n = 0; n > 0; n--)
{
product = n * product;
cout << product << endl;
}

```int factorial (int n)
{
int product = 1;
for(;n>0;n--)
{
product = n * product;
}

```

#3 idle_09

Reputation: 0
• Posts: 48
• Joined: 02-March 08

Re: Rewrite a WHILE loop to FOR loop

Posted 30 June 2008 - 12:21 PM

Thanks a lot. It helped

#4 Delta_Echo

Reputation: 5
• Posts: 722
• Joined: 24-October 07

Re: Rewrite a WHILE loop to FOR loop

Posted 30 June 2008 - 07:23 PM

'n' was already declared. You cannot re-declare. Just thought i would throw that in