casanovasky
casanovasky

Reputation: 27

Can I use multiple whiles within a while loop?

while (...) 
{
    while (...)  
    {   ......
    }

    while (...) 
    {   ......
    }

    while (...) 
    {   ......
    }
}

Can I write my code this way?

Can I use multiple whiles within a while loop in C language?

(I don't have my laptop with me right now so I can't test it out myself.)

Upvotes: 1

Views: 1319

Answers (2)

BradzTech
BradzTech

Reputation: 2835

Yes. Loops in general are highly versatile; you can nest them however you want. However, without getting into multi-threading, only one loop can be executed at a time.

Your code will execute the first sub-loop until it's condition is satisfied, then it will do the second one, then the third one, then if the main loop is still true, it will go back to the first one etc. It will NOT do all three simultaneously.

Upvotes: 2

Atafar
Atafar

Reputation: 717

Yes, sure you can. Give it a go:-).

An example:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int i = 0, j = 0;

  while (i < 10) {
    while (j < i) {
      printf("%d\n", j);
      j++;
    }
    i++;
  }
  exit(0);
}

It is not a very useful program. Just to illustrate the principle.

Upvotes: 2

Related Questions