- C++ Course Basics
- C++ Tutorial
- C++ Basic Syntax
- C++ Identifiers
- C++ Character Set
- C++ Input/Output Operator
- C++ Variables
- C++ Data Types
- C++ Formatting Output
- C++ Operators
- C++ Assignment Operator
- C++ Type Conversion
- C++ Program Control
- C++ if and if-else
- C++ switch
- C++ loops
- C++ break and continue
- C++ Functions
- C++ Functions
- C++ Prototype and Definition
- C++ Function Call
- C++ Function Types
- C++ Friend Function
- C++ Function Overloading
- C++ Arrays and Strings
- C++ Arrays
- C++ One-Dimensional Arrays
- C++ Strings
- C++ String Functions
- C++ Structures
- C++ Structures
- C++ Nested Structure
- C++ Structure Array
- C++ Pass Structure to Function
- C++ Pointers
- C++ Pointers
- C++ Memory Map
- C++ Declare Initialize Pointers
- C++ Pointers and Structures
- C++ Object-Oriented
- C++ Object-Oriented
- C++ Classes and Objects
- C++ Constructors and Destructors
- C++ Objects as Function Arguments
- C++ Pointers and Objects
- C++ Data Structure
- C++ Linked List
- C++ Stack
- C++ Queues
- C++ File Handling
- C++ File Handling
- C++ Opening and Closing Files
- C++ Steps to Process Files
- C++ Sequential I/O Operations
- C++ Detecting EOF
- C++ File Pointers Random Access
- C++ Binary Files Operations
- C++ Error Handling
- C++ Misc
- C++ typedef
- C++ #define
- C++ Date and Time
- C++ Examples
- C++ Examples
C++ loops: for, while, and do-while loops with example programs
This post was written and published on this website to explain one of the most important C++ topics: "iteration statements." So, without further ado, let's get started.
The iteration statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements.
Types of Loops in C++
C++ provides the following three kinds of loops:
C++ loop constructs repeat a set of statements until the given condition evaluates to false. A true condition in all three loop statements is any value that is not zero, and a false condition is any value that is zero.
Before we start describing these three types of C++ loops one by one, I think it will be great if we discuss the parts of the loop.
Each and every loop has components that control and direct how it is carried out. In most cases, a loop will consist of four components, each of which serves a distinct function. These are the parts that make it up:
- Initialization Expression(s): A loop's control variable(s) must be initialized before it can be entered. The control variable(s) are initialized using the initialization expression (s). The initialization expression(s) assign the first value to the loop variables. The initialization expression(s) are only executed once, at the start of the loop.
- Test Expression: The test expression is an expression whose truth value determines whether or not the loop-body is executed. The loop body is executed if the test expression evaluates to true, or 1. If the test expression returns false or zero, the loop is terminated. Before exiting an entry-controlled loop, the test-expression is evaluated. The for and while loops in C++ are entry-controlled loops, while the do-while loop is an exit-controlled loop. Not to worry; it is explained immediately following this section in this post.
- Update Expression(s): The update expression modifies the value(s) of the loop variable(s). Following the execution of the loop-body, the update expression(s) are executed.
- Loop's Body: The body of the loop is made up of one or more statements that will be executed until the test expression evaluates to true. Even if the test expression evaluates to false in the case of a "do-while" loop, the body of the loop will be executed once on the first run and then will terminate.
We use "expression(s)" instead of "expression" because the loop in C++ can have multiple initialization and update expressions. The same can be said for loop variables.
C++ for loop
The for loop is the easiest to understand of the C++ loops. All of its loop-control elements are gathered in one location, which is at the top of the loop, whereas in C++'s other loop construction, the loop-control elements are dispersed throughout the program.
The general form of the "for" loop in C++ is as follows:
for(initialization expression(s); test-expression; update expression(s)) { // body of the loop }
For example,
for(int i=0; i<10; i++) { cout<<"fresherearth.com"; }
indicates that the "for" loop continues the execution of its body, which is the statement,
cout<<"fresherearth.com";
until the value of "i" becomes equal to 10. In other words, if the value of "i" becomes equal to 10, then the condition "i<10" evaluates to false, which makes the loop terminate its execution. Therefore, the above "for" loop code snippet prints the text "fresherearth.com" on the output console 10 times.
C++ for example program
The C++ program can be considered an example program for the "for" loop in C++.
#include<iostream> using namespace std; int main() { int val, x; cout<<"Enter a number: "; cin>>val; for(int i=1; i<=10; i++) { x = val*i; cout<<val<<" * "<<i<<" = "<<x; cout<<endl; } cout<<endl; return 0; }
The following snapshot shows the initial output produced by the above C++ example program:
Now type any number, say "3," and hit the ENTER key to produce the following output:
Now let me explain the above "for" loop section of the above example program:
- Initially, "val = 3" entered by the user.
- Now the execution of the "for" loop begins.
- Since I already told you that the initialization expression executed first and only once, the value 1 was initialized to "i."
- I also told you that before entering the body of the loop, the test expression must be evaluated to true, therefore the given test expression, "i<=10," will be evaluated.
- Since the test expression, which is "i<=10" or "1<=10," evaluates to true, program flow enters the body of the "for" loop and executes all three written statements, which are "val*i" or "3*1" or "3," which will be initialized to "x," and using the "cout," "val * i = x" or "3 * 1 = 3" (by putting the values of all three variables) will be printed on the output console.
- Now, after the execution of the loop's body, the update expression evaluates, and therefore the value of "i" is incremented using "i++." So "i = 2" now.
- Again, before entering the body of the loop, the test expression must be evaluated as true.
- Because this time too, the test expression "i<=10" or "2<=10" evaluates to true, the program flow again enters the body of the loop and again executes all three statements written in it with the updated value of "i."
- So, the loop keeps running until the test expression is evaluated as false.
C++ while loop
When we need to execute a block of code or a set of statements multiple times, we use the "while" loop. However, the "while" loop only accepts "test-expression" as a parameter. The other two are that the "initialization expression(s)" must be done before starting the "while" loop, and the "update expression(s)" must be written in the loop's body.
Following is the general form of the "while" loop in C++.
while(test-expression) { // body of the loop }
For example,
int i=0; while(i<10) { cout<<"fresherearth.com"; i++; }
prints the text "fresherearth.com" 10 times on the output console. Except for the placement of the "initialization expression(s)" and the "update expression(s)," everything remains the same as in the "for" loop.
C++ while loop example program
The following program can be considered an example program for the "while" loop in C++.
#include<iostream> using namespace std; int main() { int val, i=1, x; cout<<"Enter a number: "; cin>>val; while(i<=10) { x = val*i; cout<<val<<" * "<<i<<" = "<<x<<endl; i++; } cout<<endl; return 0; }
This program does the same job as the program given in the "for" loop section.
C++ do-while loop
The do-while loop, unlike the for and while loops, is a "exit-controlled" loop; that is, it evaluates its "test-expression" after executing its loop-body statements, which means that if the test-expression evaluates to false at first, the loop-body will be executed once before the loop is terminated.
Following is the general form of the "do-while" loop in C++.
do { // body of the loop }while(test-expression);
For example,
int i=0; do { cout<<"fresherearth.com"; i++; }while(i<10);
again prints the text "fresherearth.com" 10 times on the output console.
C++ do-while loop example program
The following program can be considered an example program for the "do-while" loop in C++.
#include<iostream> using namespace std; int main() { int val, i=1, x; cout<<"Enter a number: "; cin>>val; do { x = val*i; cout<<val<<" * "<<i<<" = "<<x<<endl; i++; }while(i<=10); cout<<endl; return 0; }
This program does the same job as in the previous two sections' programs.
Main difference between for, while, and do-while loops in C++
In all three loops, the test expression must be evaluated to true before entering the body of the loop. However, just in case of "for" and "while" loops, the test-expression is evaluated first and then entered into the body, whereas in the case of the "do-while" loop, The test expression is evaluated after executing the loop's body. In the case of a "do-while" loop, however, before entering the loop's body a second time, the test expression must be evaluated as true. Let me give you an example to help you understand.
#include<iostream> using namespace std; int main() { cout<<"----for loop example----\n"; for(int a=100; a<0; a++) { cout<<"Greetings."; } cout<<"\n\n"; cout<<"----while loop example----\n"; int b=100; while(b<0) { cout<<"Greetings."; b++; } cout<<"\n\n"; cout<<"----do-while loop example----\n"; int c=100; do { cout<<"Greetings."; c++; }while(c<0); cout<<endl; return 0; }
This program will produce the following output:
----for loop example---- ----while loop example---- ----do-while loop example---- Greetings.
The output shows that the conditions in all three loops are false on the first execution. As a result, the text "Greetings" was omitted. However, because the test-expression for a "do-while" loop is available at the bottom of the loop, it evaluates after executing the loop body, and thus the text "Greetings." was printed in the case of a "do-while" loop. Furthermore, because the condition of the "do-while" loop evaluates to false, the "do-while" loop terminates after evaluating the condition.
Note: When the loop-body contains a single statement, the curly braces are not required.
Important: If you leave out the text-expression, the loop will run indefinitely. Another case when the loop goes for infinite execution is when the test expression always evaluates to true.
Note: One loop can be nested in another.
More Examples
Here are some C++ programs that you might enjoy:
- Decimal to Binary Conversion
- Pattern Programs
- Print Diamond Pattern
- Print Floyd Triangle
- Print Pascal Triangle
- Print Smiling Face
« Previous Tutorial Next Tutorial »