for loop vs while loop

Posted by Atul on Stack Overflow See other posts from Stack Overflow or by Atul
Published on 2011-01-09T17:36:03Z Indexed on 2011/01/09 17:54 UTC
Read the original article Hit count: 189

Filed under:
|

We can use for loop and while loop for same purpose. in what means they effect our code if I use for instead of while? same question arises between if-else and switch-case? how to decide what to use? for example which one you would prefer?

This code:

int main()
{
   int n;
    cin>>n;
   for(int i=0;i<n;i++)
    {
        do_something();
    }
    return 0;
}

Or this code:

int main()
{
    int n,i=0;
    cin>>n;
    while(i<n)
    {
          do_something();
          i++;
    }
    return 0;
}

if using for or while loop does not effect the code by any means then may I know What was the need to make 2 solution for same problem?

© Stack Overflow or respective owner

Related posts about c++

Related posts about c