Can't understand the infinity loop

I passed the infinity while loop exercise without errors but I still did’nt understand how the while loop works like when I want the user to go on and on until the user types a command that is corect. But I still did not understand how does the while loop work.

Could you share your code? There are many different ways to have a while loop behave this way, so to help you it be best to see what you’re doing.

For example, this code will continue pulling single characters from stdin until the user enters the character 'd':

#include <stdio.h>

int main(void) {
  
  char a = 0;
  while ((a = getchar()) != 'd');
  return 0;

}

Since the loop runs while it’s condition is true, than as long as a is not assigned the character 'd' it will loop again.

Ok, heres my worked well without a promlem.

#include <iostream>

int main() {
  
  int i = 0;
  int square = 0;
  
  // Write a while loop here:
  while (i < 10) {

    square = i * i;

    std::cout << i << " " << square << "\n";

    i++;

  }
  
  
  
  
  
  
  
  
}

please explan as I did under stand not The while loops

do I have to know what is

void function?

Have you learned about conditionals yet? I’m fairly certain they should’ve been covered by this point.

Essentially the while loop has a conditional in it, that has to be true for it to keep looping. As long as this condition is true it will keep running the code inside it.

In your above code, the condition is i < 10 so as long as i is less than 10, it will keep looping. Notice inside the loop i is incremented, meaning every time it loops i increases in size, until eventually it is not longer less than 10, and the loop stops.

void is a keyword meaning nothing exists there, at this point you don’t need to have a full understanding of it. It is often used in functions to indicate there are no parameters, though it is not necessary.

Thanks very much my 2 week problem has been solved

1 Like