Share your repls and programming experiences

← Back to all posts
Loops Tutorial - C++
AlfonsoTorres (7)

Loops Tutorial - C++

Level: Beginners

By: Alfonso Torres

About Me

My name is Alfonso Torres and I am a 5th year college student at California State University Monterey Bay. I am currently pursuing a degree in Computer Science.
The reason I am doing this tutorial is because when I started coding, I had a tough time with loops. I was fortunate enough to have a helpful TA to help me out.
Now I would like to pay it forward and create
a tutorial for people dealing with the same
issue I was dealing with before.

Background Information

Are you not familiar with the basic C++ syntax?
Would you like a quick crash course?
Checkout the link to my power point. It will help you with the basics, then you can move on to the loops portion. All the information presented here is also presented in the power point.

My Power Point!

What are for-loops?

For-loop - is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

  • Simple Explanation: A for-loop can be used to repeat a piece of code a specific number of times.

For-loop Syntax

for ( init; condition; increment) {
   //statement(s) or code;
}
  • init - start
  • condition - it acts as a rule to see whether or not the loop continues
  • increment - add or subtract to keep the loop going

For-loop Example

Loop begins with creating a variable named “i” to equal zero. Then it checks the condition “i < 5”. If yes it moves onto the code inside the loop. Then it goes to the increment section to add onto the “i” variable. It goes to check the condition again. It goes from the condition to the increment section of the loop until the condition is not met. This is where the loop is made. Once the condition is not met, once the “i” is not less than 5 for our case, then it breaks out of the loop.

for ( int i = 0 ; i < 5; i = i + 1) {
  cout << i  << “ ”; //printing out the variable “i”
}

Output:

0 1 2 3 4

While Loops

While Loop - is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

  • To define it in simple terms, a while loop is a way to repeat code that you written.

While Loop Syntax

while(condition) {
   //code goes here
}
  • While loop starts at the top. If the condition is true then it will go inside the loop to begin the code.
  • After it goes through your code. Your program will go to the beginning of your while loop to see if the condition is still true.

Time to Code!

Go ahead to try to code your very own for-loop!