For Loop in C++ with Syntax & Program EXAMPLES (2024)

By : Barbara Thompson

Updated

What is a For Loop?

This is a repetition control structure that helps us iterate over a section of C++ code for a fixed number of times. A for loop runs provided the test expression is true. The loop terminates execution immediately the test expression becomes false. This means before the execution of the loop body in each iteration, the condition has to be evaluated. If the evaluation returns a true, the loop body is executed. If the evaluation returns a false, execution of the loop body is terminated.

How for loop works?

The for loop works as follows:

Flow Chart Explanation:

  1. The C++ language compiler begins by evaluating the initialization. This is only done once as execution begins.
  2. The test expression is evaluated/executed.
  3. If the test expression is true, the loop body is executed and the test expression is updated. If expression becomes false, the for loop terminates.
  4. After the execution of test expression, the increment is executed to increase the value of the loop control variable.
  5. The test expression is evaluated again, and the process continues until the expression becomes false.
  6. If the expression is false, the loop body statements are skipped.

Note: The test expression is updated after every iteration. This means different values of the loop control variable are executed in each iteration.

When to use a for loop?

The for loop should be used when:

  • You have a fixed number of iterations.
  • You know the exact number of iterations.

Syntax of for loop

Here is the syntax for the for loop:

for ( initialization;condition;increment ) { statement(s);}

Here is an explanation of the above parameters:

  • Initialization: This part is executed first and only once. Here, you declare and initialize loop control variables. The loop control variables can be more than one, and their values will change after every iteration. However, their values must be evaluated before an iteration runs.
  • Condition: This part is executed next. For the loop body to be executed, this condition must be true. If the condition is false, execution will jump to statements immediately after the loop body. If the condition is false on the first evaluation, the loop body will never be executed.
  • Increment: Once the loop body has been executed, control jumps to the increment. You can leave out this part and use a semicolon instead.
  • Again, the condition is evaluated. If it’s true, the loop body is executed, and this continues. The loop terminates immediately the condition becomes false.

For Loop in C++ Example 1

#include <iostream>using namespace std;int main() {for (int x=0; x<5; x=x+1) {cout << "X is: " << x << endl;}return 0;}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Creating a for loop. The initialization creates an integer variable x and assigns it a value of 0. The condition states that the value of x must be less than 5. The increment increases the value of x by 1 after every iteration. The { marks the beginning of the body of the for loop.
  5. To print the value of variable x alongside other text on the console. The endl is a C++ keyword meaning end line. The cursor will print in the next line in the next iteration.
  6. End of the loop body.
  7. The main() function should return an value if the program runs fine.
  8. End of the body of the main() function.

For Loop in C++ Example 2

#include <iostream>using namespace std;int main(){int x, num, factorial = 1;cout << "Type positive number: ";cin >> num;for (x = 1; x <= num; ++x) {factorial *= x; // factorial = factorial * x;}cout << "Factorial of " << num << " = " << factorial;return 0;}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added.
  4. The { marks start of body of the main() function.
  5. Declaring integer variables, x, num, and factorial. The variable factorial has been assigned a value of 1.
  6. Printing some text on the console.
  7. Prompting user to enter a value for variable num.
  8. Creating a for loop. The initialization creates an integer variable x and assigns it a value of 1. The condition states that the value of x must be less than or equal to value of variable num. The increment increases the value of x by 1 after every iteration. The { marks the beginning of the body of the for loop.
  9. Calculating the value of factorial using the formula factorial = factorial * x.
  10. End of the loop body.
  11. To print the value of variables num and factorial alongside other text on the console.
  12. The main() function should return an value if the program runs fine.
  13. End of the body of the main() function.

Summary

  • The for loop iterates a section of C++ code for a fixed number of times.
  • The for loop runs as long as the test condition is true.
  • The initialization part of for loop is for declaring and initializing any loop control variables.
  • The condition part of for loop must be true for loop body to be executed.
  • The increment part of the for loop can be replaced with a semicolon.

You Might Like:

  • std::list in C++ with Example
  • How to Download and Install C++ IDE on Windows
  • Hello World Program in C++ with Code Explanation
  • C++ Tutorial for Beginners: Learn Programming Basics in 7 Days
  • Difference between Structure and Class in C++
  • C++ Tutorial PDF for Beginners (Download Now)
  • Static Member Function in C++ (Examples)
For Loop in C++ with Syntax & Program EXAMPLES (2024)
Top Articles
Baby Skin Care -- Simple Tips to Keep Your Baby's Skin Healthy
4 Ways to Have a Baby Soft Face - wikiHow
Ffxiv Act Plugin
Durr Burger Inflatable
Genesis Parsippany
Libiyi Sawsharpener
The UPS Store | Ship & Print Here > 400 West Broadway
Pangphip Application
How to know if a financial advisor is good?
Rubfinder
Which aspects are important in sales |#1 Prospection
Garrick Joker'' Hastings Sentenced
Iron Drop Cafe
Ladyva Is She Married
What Is Njvpdi
Johnston v. State, 2023 MT 20
Chicken Coop Havelock Nc
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
Binghamton Ny Cars Craigslist
Price Of Gas At Sam's
National Weather Service Denver Co Forecast
Dr Adj Redist Cadv Prin Amex Charge
iZurvive DayZ & ARMA Map
Unterwegs im autonomen Freightliner Cascadia: Finger weg, jetzt fahre ich!
Farmer's Almanac 2 Month Free Forecast
Beryl forecast to become an 'extremely dangerous' Category 4 hurricane
Cbssports Rankings
Craigslist Lewes Delaware
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
Saxies Lake Worth
Account Now Login In
Vht Shortener
Ff14 Sage Stat Priority
Franklin Villafuerte Osorio
Abga Gestation Calculator
Autopsy, Grave Rating, and Corpse Guide in Graveyard Keeper
Staar English 1 April 2022 Answer Key
Skip The Games Ventura
#1 | Rottweiler Puppies For Sale In New York | Uptown
Imperialism Flocabulary Quiz Answers
SF bay area cars & trucks "chevrolet 50" - craigslist
Devotion Showtimes Near The Grand 16 - Pier Park
Walgreens Agrees to Pay $106.8M to Resolve Allegations It Billed the Government for Prescriptions Never Dispensed
Nina Flowers
Inducement Small Bribe
Dragon Ball Super Super Hero 123Movies
Gamestop Store Manager Pay
White County
The Cutest Photos of Enrique Iglesias and Anna Kournikova with Their Three Kids
The Blackening Showtimes Near Ncg Cinema - Grand Blanc Trillium
Glowforge Forum
Kindlerso
Latest Posts
Article information

Author: Kelle Weber

Last Updated:

Views: 5516

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.