CJCoding With Joseph
15free / daySign inCreate account

Mastering C Textbook

Mastering Loops

Here are three main types of loops in programming: while, do-while, and for. Each type of loop serves a different purpose, and mastering when and how to use each is key to writing efficient code.


While Loops

while(condition) {logic}

Use While loops when you do not need the logic in the loop to run at least once. The complier will check the condition inside of the while loop brackets, and then only run if it is a true statement.

int sum = 2;

while (sum < 100) {
    sum += sum * sum;
}

printf("%d", sum);

OUTPUT:

1806

 

Do While Loops

do { logic } while(condition);

Use Do While Loops when you do need logic to run at least once. The complier will run the code inside of the loop, then check the condition statement on the bottom. It will run again only if that statement is true.

In this example, the condition is false, but it will still run one time, then break out of the loop.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 11 more lessons in Mastering C Textbook.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.