0

I find the solution to marios pyramid using the for loop.I am wondering if is is possible to solve it with the while loops ?

2
  • Anything that can be done by iteration, can be performed by any loop: for, while, do-while, or even recursion.
    – sinister
    Commented Dec 8, 2014 at 6:37
  • If found any answer useful, please mark them (if any) as "accepted", so other students with similar issues can benefit from your already answered question.
    – abelinux
    Commented Dec 27, 2014 at 16:26

1 Answer 1

0

Indeed, @pavlos romios.

Both for and while loops are different cases of what's known as iteration. Generally speaking, anything you can solve with a while loop you can solve with a for loop. The only difference is that:

  • Case "WHILE": in the while loop the sequence is more evidently repeated an uncertain number of times. I.e.: it would repeat indefinitely until a certain condition is met:

    while(random != 2)
    {
        random = rand();
    }
    

    That also means that if the condition is never met, you get caught in an infinite loop.

  • Case "FOR": On the contrary, in a for loop, you tend to state clearly the number of repeats you want your sequence to run through, because generally you know it beforehand:

    for (int i = 0; i < 10; i++)
    {
        printf("Step number: %d", i + 1);
    }
    

That is the "normal" way of using such loops.

Then, of course, you can twitch'em up a little bit and use them exactly the other way around:

  • Case "WHILE":

    int i = 0;
    
    while(i < 10)
    {
        printf("Step number: %d", i + 1);
        i++;
    }
    

    I.e.: you just executed a while loop a finite and determined number of times

  • Case "FOR:

    for (; random != 2; )
    {
        random = rand();
    }
    

    I.e.: you just executed a for loop an indefinite, and potentially, infinite number of times.

Even when all of these are legal expressions in 'C', you should, for the sake of readability of your code, stick to what's the more obvious way of using them:

  • while for uncertain number of repeats
  • for for a definite number of repeats

There're times though, when you'll see some of these techniques in use, so it's good you learn they exist.

HTH!

Not the answer you're looking for? Browse other questions tagged .