Rewrite a WHILE loop to FOR loop

I have to rewrite a while loop to for loop but i am confused

Page 1 of 1

3 Replies - 2389 Views - Last Post: 30 June 2008 - 07:23 PM Rate Topic: -----

#1 idle_09  Icon User is offline

  • New D.I.C Head

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

Rewrite a WHILE loop to FOR loop

Post icon  Posted 29 June 2008 - 11:18 PM

Hi! Can someone please help me.
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  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,559
  • Joined: 25-January 07

Re: Rewrite a WHILE loop to FOR loop

Posted 29 June 2008 - 11:24 PM

View Postidle_09, on 30 Jun, 2008 - 11:48 AM, said:

Hi! Can someone please help me.
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;
}



that's it. I hope this will help you. :)
Was This Post Helpful? 0
  • +
  • -

#3 idle_09  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

#4 Delta_Echo  Icon User is offline

  • D.I.C Addict

Reputation: 5
  • View blog
  • 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 :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1