While and Do-While Loops

Condition-based iteration

Interview Relevant: Loop control

While and Do-While Loops

While loops repeat while a condition is true.

Difference

  • while: Checks condition before each iteration
  • do-while: Executes at least once, checks after

Code Examples

While and do-while loops for condition-based iteration.

cpp
1// while loop
2int count = 0;
3while (count < 5) {
4    cout << count << " ";  // 0 1 2 3 4
5    count++;
6}
7
8// do-while loop (executes at least once)
9int num;
10do {
11    cout << "Enter a positive number: ";
12    cin >> num;
13} while (num <= 0);
14
15// Infinite loop with break
16while (true) {
17    string input;
18    getline(cin, input);
19    if (input == "quit") break;
20    cout << "You entered: " << input << endl;
21}
22
23// Reading until EOF
24while (cin >> num) {
25    cout << "Read: " << num << endl;
26}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In