1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M3 While
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
15Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M3 While

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
15Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

While & Do-While Loops

Overview

If you need to execute a block of code repeatedly, you use a loop. A while loop checks a condition BEFORE it executes the code. If the condition is true, it runs the block, then checks the condition again. It is perfectly designed for scenarios where you do not know how many times the loop needs to run (e.g., 'Keep reading network packets until the user disconnects').

A do...while loop flips the architecture. It executes the code block first, and checks the condition at the end. This mathematically guarantees that the code inside a do...while loop will ALWAYS execute at least once, regardless of the condition.

Syntax

cpp
// --- 1. THE WHILE LOOP ---
int count = 0;
// Checks condition FIRST
while (count < 3) {
    std::cout << "Looping: " << count << "\n";
    count++; // CRITICAL: Ensure the condition eventually becomes false!
}

// --- 2. THE DO-WHILE LOOP ---
int input;
// Executes code FIRST, checks condition LAST
do {
    std::cout << "Enter a positive number: ";
    std::cin >> input;
} while (input <= 0); // Notice the semicolon here!

Common Pitfalls

  • The Infinite Loop. If you forget to modify the variable that the condition relies on (e.g., forgetting count++), the condition will remain true forever. The loop will run infinitely, instantly maxing out 100% of a CPU core and completely freezing your application.
  • Forgetting the semicolon at the end of a do...while loop. While standard if and while loops don't use semicolons after their conditions, the syntax of do { } while (condition); strictly requires a semicolon at the very end.

Interview Questions

What is the fundamental architectural difference between a while loop and a do...while loop?

A while loop is a 'pre-test' loop; if the initial condition is false, the internal code is executed zero times. A do...while loop is a 'post-test' loop; the internal code is blindly executed exactly once before the condition is ever evaluated.

Real-World Example

Using a classic 'Infinite While Loop' (while(true)) combined with a custom breakout condition to drive the main event loop of a video game or server.

example
cpp
bool isGameRunning = true;

// The classic 'Game Loop'
while (isGameRunning) {
    // 1. Process player input
    char key = getInput();
    
    // 2. Break out of the loop dynamically
    if (key == 'Q') {
        isGameRunning = false; 
    }
    
    // 3. Render graphics
    // renderEngine();
}

Check Your Knowledge

Test your understanding of While & Do-While Loops with these quick questions.

Question 1

If you write `int x = 10; do { x++; } while (x < 5);`, what is the final value of x?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

While & Do-While Loops

Overview

If you need to execute a block of code repeatedly, you use a loop. A while loop checks a condition BEFORE it executes the code. If the condition is true, it runs the block, then checks the condition again. It is perfectly designed for scenarios where you do not know how many times the loop needs to run (e.g., 'Keep reading network packets until the user disconnects').

A do...while loop flips the architecture. It executes the code block first, and checks the condition at the end. This mathematically guarantees that the code inside a do...while loop will ALWAYS execute at least once, regardless of the condition.

Syntax

cpp
// --- 1. THE WHILE LOOP ---
int count = 0;
// Checks condition FIRST
while (count < 3) {
    std::cout << "Looping: " << count << "\n";
    count++; // CRITICAL: Ensure the condition eventually becomes false!
}

// --- 2. THE DO-WHILE LOOP ---
int input;
// Executes code FIRST, checks condition LAST
do {
    std::cout << "Enter a positive number: ";
    std::cin >> input;
} while (input <= 0); // Notice the semicolon here!

Common Pitfalls

  • The Infinite Loop. If you forget to modify the variable that the condition relies on (e.g., forgetting count++), the condition will remain true forever. The loop will run infinitely, instantly maxing out 100% of a CPU core and completely freezing your application.
  • Forgetting the semicolon at the end of a do...while loop. While standard if and while loops don't use semicolons after their conditions, the syntax of do { } while (condition); strictly requires a semicolon at the very end.

Interview Questions

What is the fundamental architectural difference between a while loop and a do...while loop?

A while loop is a 'pre-test' loop; if the initial condition is false, the internal code is executed zero times. A do...while loop is a 'post-test' loop; the internal code is blindly executed exactly once before the condition is ever evaluated.

Real-World Example

Using a classic 'Infinite While Loop' (while(true)) combined with a custom breakout condition to drive the main event loop of a video game or server.

example
cpp
bool isGameRunning = true;

// The classic 'Game Loop'
while (isGameRunning) {
    // 1. Process player input
    char key = getInput();
    
    // 2. Break out of the loop dynamically
    if (key == 'Q') {
        isGameRunning = false; 
    }
    
    // 3. Render graphics
    // renderEngine();
}

Check Your Knowledge

Test your understanding of While & Do-While Loops with these quick questions.

Question 1

If you write `int x = 10; do { x++; } while (x < 5);`, what is the final value of x?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A