Loops Tutorial - C++
Loops Tutorial - C++
By: Alfonso Torres
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.
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.
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.
- 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
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.
0 1 2 3 4
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 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!