C++ Tutorial #9 – Range Based For Loops

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Today I want to cover one more thing before we move on to other tutorials. I’m going to show you really quick how to use Range-Based For Loops. It’s basically a For Loop with another syntax. Instead of initializing a variable, adding a condition and increase; we just place a declaration and range. Confused? Don’t be. Pay attention to those two words and I’ll show you what it is in a second.

 

Here’s the syntax:

 

for (declaration : range)
{
statement;
}

 

Range-Based For Loops cycles through all the elements in range. Ranges are groups of elements, such as strings and arrays. We are going to be using both today. In the declaration spot you can declare a variable. example: int x or char c. Believe it or not. that’s all there is to Range Based For Loops. Just remember to separate the declaration and range with a colon. Lets get started on writing a program.

 

In this program, we are going to write two Range-Based For Loops. One using arrays, and another using strings. You can copy, or write this code:

 

 

Your program should look something like this:

 

(H)(e)(l)(l)(o)(!)
Ranged-Based For Loop using string

(3)(1)(4)(1)(5)(9)(2)(6)(5)(3)(5)
Ranged-Based For Loop using an arrays

 

As you can see, we created two variables to use as our range (string and array of integers). Then we set values to each of the variables.

 

 

Then we created our first Range Based For Loop, using char x as the declaration, and str as the range. We used cout to print each series of elements in our range (str).

 

 

We also added another line after the for loop to print out that we just made a for loop using string

 

 

Then we made our second loop, using int x as declaration and numbers as range. We also used cout to print each series of elements in numbers.

 

 

I’m sure you understand by now, but I’ll say it anyways. At the end of our program, after the loop, we added another line of code to print out that we made a loop using arrays.

 

 

That’s pretty much it! I hope you’ve enjoyed this tutorial, and that it was very easy to understand. There are many tutorials I have planned on writing, and I hope to get them done as soon as I can. Have a nice day! 😀

 

Facebooktwittergoogle_plusredditpinterestlinkedinmail

About Justin

Computer programmer and owner of kauergames.com.
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.