Loops in C++

πŸ“˜ C++ πŸ‘ 29 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

A loop is used to execute a block of code repeatedly until a specified condition is met.


Types of Loops in C++

C++ provides three types of loops:

  1. for loop

  2. while loop

  3. do–while loop


1. for Loop

Used when the number of iterations is known.

Syntax

for (initialization; condition; increment/decrement) { // statements }

Example

for (int i = 1; i <= 5; i++) { cout << i>" "; }

2. while Loop

Used when the number of iterations is not known in advance.

Syntax

while (condition) { // statements }

Example

int i = 1; while (i <= 5) { cout << i>" "; i++; }

3. do–while Loop

Executes the loop body at least once, even if the condition is false.

Syntax

do { // statements } while (condition);

Example

int i = 1; do { cout << i>" "; i++; } while (i <= 5);

Difference Between Loops

Featureforwhiledo–while
Condition checkBefore loopBefore loopAfter loop
Guaranteed executionNoNoYes
Best used whenIterations knownCondition-basedAt least one execution

Nested Loops

A loop inside another loop.

for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { cout << "* "; } cout << endl>

Loop Control Statements

StatementPurpose
breakTerminates the loop
continueSkips current iteration

Key Points

  • Loops reduce code repetition

  • Choose the loop based on the problem

  • do–while runs at least once

  • Nested loops handle multi-level repetition


Conclusion

Loops are essential in C++ for performing repetitive tasks efficiently and logically.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes