1 Replies - 194 Views - Last Post: 12 May 2013 - 10:42 AM Rate Topic: -----

#1 MichealSlattery248  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-May 13

Differences in loops

Posted 12 May 2013 - 10:37 AM

Would anyone like to give me the key differences between a for loop, a do while and a while loop? i already know that a do while loop executes at least once whereas a while loop wont execute unless the statement is true. I know that a for loop must have an index equal to something, must be less than or equal to something and have an increment or a decrement...anything else?
Is This A Good Question/Topic? 0
  • +

Replies To: Differences in loops

#2 Zereo  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 44
  • View blog
  • Posts: 108
  • Joined: 08-November 12

Re: Differences in loops

Posted 12 May 2013 - 10:42 AM

Quote

must be less than or equal to something and have an increment or a decrement...anything else?


That statement isn't true. Consider this loop for example

for (int i = 99; i >= 1; --i)
{
    // Do something
}


For loops run until the condition is met. The are basically the same as while loops but with different syntax. Which is what you meant I think since you included decrement.

Though it doesn't have to have a increment of decrement only. You could have something like this, which generates a random number every time and the loop only stops when that random number equals 5.

int main()
{
    srand(time(0));

    for (int i = rand() % 100; i != 5; i = rand() % 100)
    {
        cout << "Running" << endl;
    }
}


Other that there isn't that much different between the loops. The one major difference in the do while loop. Like you said it always executes atleast once. This is because the do while loop checks the condition after it has run its block of code (IE the stuff between the braces).

This post has been edited by Zereo: 12 May 2013 - 10:52 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1