Understanding the basic of Loops

Khanittha Krajangjaem
2 min readSep 27, 2020

--

Photo by Nareeta Martin on Unsplash

Loops are basic and important structures that exist in almost all programming languages. Loops allow your program to execute lines of code repeatedly until a specific condition is met. Without loops, we’d have to do a lot of copy and pasting the same line of code over and over.

I must say I have worked with all kinds of loops in all three of the programming languages that I have learned including C, Ruby, and JavaScript. Even though I feel like I get the theory and how they operate I still find myself hesitating over which loop to use in which situation sometimes.

Today, I am going to talk about loops in C which is pretty similar to loops in JavaScript.

There are three major types of loops in C, and as in all languages, they exist for different purposes

While Loop — or Infinite Loop
HOW IT WORKS: While the condition evaluates to true, the lines of code between the two curly braces will execute from top to bottom forever otherwise the condition evaluates to false or break out of it.
WHEN TO USE: When you want the loop to run repeatedly for an unknown number of times or never run at all.

while loop syntax

Do While Loop
HOW IT WORKS:
Is similar to While Loop except for it makes sure the code between the two curly braces run at least once (regardless of the condition). Then continue to check the condition, if the condition expression evaluates to true then the above while loop will execute.
WHEN TO USE: When you have the same purpose of using While Loop but want to make sure your code executes at least once.

do-while loop syntax

For Loop
HOW IT WORKS:
Is pretty straightforward. It repeats the lines of code between the two curly braces for a specific number of times. Given a counter and a condition, while the condition expression evaluates to true the code will execute.
WHEN TO USE: When you want the loop to run for a specific number of times (e.g. 10 times or x times) and for sure has an endpoint.

for loop syntax

Something To Keep In Mind — In most cases, you can interchange all three of the above loops, but best to use each loop in the right context. And you can also combine them which make nested loops.

--

--

Khanittha Krajangjaem

Software Engineer | Full-Stack Developer with background in Graphic Design based in San Francisco, CA