element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ Tutorial - For Loops
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: oneleggedredcow
  • Date Created: 23 Jan 2013 5:19 AM Date Created
  • Views 775 views
  • Likes 1 like
  • Comments 0 comments
  • Code Exchange
  • learn++
  • raspberry_pi
  • code
  • rpi
  • c++
Related
Recommended

C++ Tutorial - For Loops

oneleggedredcow
oneleggedredcow
23 Jan 2013

Introduction

In the previous tutorial, we learned how to make decisions based on the data that the user typed in and we wrote a guess my number game.  The code for the game was very repetitive and could greatly be reduced and generalized by using loops.  In this tutorial, we will rewrite the game using for loops to make the code much more concise.

Code

A for loop takes three pieces of information: the value that you wish to start at, a comparison to decide how long to keep going, and a statement to execute between each loop. So, let’s start out with an example, here’s how to print all of the numbers between 1 and 10:

 

for (int num = 1; num <= 10; num++)

{

cout << num << endl;

}

 

The first part of the for loop (int num = 1) declares a new variable and sets its value to 1, which is the first number that we want to print.  At this point, the computer checks the value of num against the comparison to decide whether or not to continue (num <= 10).  Since num is one, which is less than ten, the statement within the loop executes, so the value is printed to the screen.  When all of the statements in the curly braces have executed, then the last part of the for loop is executed (num++).  This adds one to the value of num.  This produces the same result as num = num + 1, but since this operation is so common there is a short hand version of it.  After this, then we are back to seeing whether or not to continue running the loop (num <= 10).  Since num is two, which is less than ten, we continue executing the statements in the loop.  Then we add one to num again, perform the check again, and then execute the statements in the loop, until the check fails and then we are done with the for loop.

 

At this point, you might be thinking, why do I need a for loop, I could print out the numbers between 1 and 10 doing something like this:

 

cout << 1 << endl;

cout << 2 << endl;

cout << 3 << endl;

cout << 4 << endl;

cout << 5 << endl;

cout << 6 << endl;

cout << 7 << endl;

cout << 8 << endl;

cout << 9 << endl;

cout << 10 << endl;

 

While this would work, it isn’t very flexible.  What if you wanted to prompt the user for a value and then count from 1 up to the given value?  The previous example would have to look something like this:

 

int max = 0;

cin >> max;

if (1 <= max) { cout << 1 << endl; }

if (2 <= max) { cout << 2 << endl; }

if (3 <= max) { cout << 3 << endl; }

if (4 <= max) { cout << 4 << endl; }

…

 

This would continue on for a long time, since the user could type in a large number like 1,234,567.  However, with a for loop, the following code could handle numbers as large as an integer can store:

 

int max = 0;

cin >> max;

for (int num = 1; num <= max; num++)

{

cout << num << endl;

}

 

So, you could either write a million plus lines of repetitive code to handle the user input or you could use a for loop and only write a handful.

So, let’s rewrite the guess my number game using a for loop.  Here’s the code:

 

#include <cstdlib>

#include <ctime>

#include <iostream>

using namespace std;

 

int main()

{

// Randomly generate a secret number

srand((unsigned int) time(NULL));

int num = (rand() % 10) + 1;

int num_guesses = 3;

 

// Print out number first (used for debugging purposes, no cheating!)

//cout << num << endl;

 

// Game intro

cout << "I'm thinking of a secret number, can you guess it?" << endl;

 

int guess = 0;

for (int i = 0; i < num_guesses; i++)

{

// Read in guess

cout << "Guess? ";

cin >> guess;

 

// Guess logic

if (guess == num)

{

// Tell the user that they guessed correctly

// and then exit the program

cout << "Correct, my secret number was " << num << endl;

return 0;

}

else

{

if (num < guess)

{

cout << "My secret number is less than " << guess << endl;

}

else

{

cout << "The secret number is greater than " << guess << endl;

}

}

}

 

// If the loop ends, that means that the user is out of guesses

// and never guessed the correct number

cout << "Sorry, the correct number was " << num << endl;

 

return 0;

}

 

See how the use of the for loop replaces the repetitive logic from the previous tutorial?  Before we had to do 3 different checks to see if the guess matched the secret number.  Here, we only write the code once and loop over it multiple times.

 

Loops are very, very powerful tools and I encourage you to play around with them because their effective usage is critical to writing good code.  Trust me, I can’t over emphasize their importance.  An exercise that really helped me learn looping was to try to prompt the user for a number and create a triangle of asterisks based on it that looked like this, if the user typed in 3:

 

  *

  **

  ***


A slightly more advanced exercise is to create a pyramid that looks something like this, if the user typed in 3:

 

    *

   ***

  *****


Give those a try and see what you come up with.  One possible solution is attached below.

Summary

In this tutorial, we learned how to make our code more concise and general through the use of for loops.  We rewrote our guess my number game from the previous tutorial using for loops to remove the repetitive code.

 

Did you ever try typing in a number larger than 10 or less than 1?  How about typing in fractional number or even a letter?  In the next tutorial, we will improve the game to make it more robust in handling user input by introducing while loops.

 

If you have any questions or comments about what was covered here, post them to the comments.  I watch them closely and will respond and try to help you out.

Tutorial Index

01 - Hello Raspberry Pi

02 - Reading User Input

03 - If Statement

04 - For Loops

05 - While Loops

06 - Functions

07 - Data Types

08 - Arrays

09 - Structures

10 - Classes

11 - Pointers

12 - Dynamic Arrays

13 - Linked List

14 - Linked List Operations

15 - STL List/Vector

16 - Templates

17 - Inheritance

18 - File I/O

19 - Strings

20 - Constants

21 - Hash Tables

Attachments:
04_CodeSamples.zip
  • Sign in to reply
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube