Wednesday, July 5, 2017

C++ While Loop Syntax and Examples

C++ While Loop Syntax and Examples

The while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop in C++ is used to repeatedly execute a block of code as long as a given condition is true.

Basic Syntax

The loop checks the condition before executing the block of code. If the condition is false initially, the code inside the loop will never run.

while (condition) {
    // Code to be executed while condition is true
    // Remember to update variables to eventually make the condition false
}
  • The condition must be a boolean expression
  • The loop continues until the condition becomes false

Example 1: C++ program to print 1 to 10 numbers using while loop.

#include<iostream>
using namespace std;
int main()
{
  int i=1;
  while(i<=10)
  {
    cout << i << " ";
    i++;
  }
  return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10


Example 2: Display first 5 even numbers

#include <iostream>
using namespace std;

int main() {
    int num = 2, count = 1;

    while (count <= 5) {
        cout << num << " ";
        num += 2;
        count++;
    }
    return 0;
}

Output:
2 4 6 8 10

Example 3: Sum of numbers until user enters 0

#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;

    cout << "Enter numbers (0 to stop): ";
    cin >> num;

    while (num != 0) {
        sum += num;
        cin >> num;
    }

    cout << "Sum = " << sum;
    return 0;
}


* * * * *

No comments:

Post a Comment