Sunday, March 6, 2016

Using loops in C++

Hello Internet,

It’s been a few weeks since I posted something about C++. Today we will be talking about loops. In C++ there are 3 primary loops. Just like Java, C++ has “for” loops and “while” loops. For loops loop through specific criteria until all instances are met. While loops continue doing code while the condition has not been met. There is another loop in C++ and that is a “do…while” loop. There is a body of code within the do statement and you will do that code until the condition in the while is met. The code in the “do…while” loop will always be executed at least once.

I wrote up a small program to test all of these loops. First the user must enter a number between 1 and 3. 1 means to execute the “for” loop. 2 means to execute the “while” loop. 3 means to execute the “do…while” loop. The “for” loop and the “while” loop do the exact same thing. They count the number of times the program loops through the loop. In other words, you start at 1 and loop through until you get to 10. However the “do…while” loop is a little different. Basically it is an integer counter. It first starts as 0 and as long as the user wishes to continue, it increments by 1 each time.

Note: If you are using C++ shell like me or if you are using a compiler found online, definitely copy and paste all your code into notepad or a word document while you go. I’m telling you this because 3 times during creating this program, the compiler decided to get rid of all my work and revert back to the original page. Luckily because I copied all my code to a word document, each time I lost no code.

Below is the code for the first loop.

 Below is the output of the first loop.


Below is the code for the second loop.


Below is the output for the second loop.


Below is the code for the third loop.


Below is the output for the third loop.


As you can tell until the user says “no” the integer will keep incrementing.

Well that’s the basics of using loops in C++. Hope you enjoyed my example program and I hope this helped you to understand how to use loops. Let me know if anything did not make sense. 

Thanks!

No comments:

Post a Comment