While C++
While C++
while Loops
• Examples
int i = 3;
i += 4; // i = i + 4
cout << i << endl; // i is now 7
double a = 3.2;
a *= 2.0; // a = a * 2.0
cout << a << endl; // a is now 6.4
• Syntax
while (condition)
action
• How it works:
• if condition is true then execute false
action condition
• repeat this process until condition
evaluates to false
true
• action is either a single
statement or a group of
statements within braces. action
The while Loop
Example:
5! = 1 x 2 x 3 x 4 x 5 = 120
How to compute 5! ?
1! = 1 ( store the temporary result in T, T is 1! )
2! = 1! x 2 = T x 2 = 2 ( store the temporary result in T, T is 2! )
3! = 2! X 3 = T x 3 = 6 ( store the temporary result in T, T is 3! )
4! = 3! X 4 = T x 4 = 24 ( store the temporary result in T, T is 4! )
5! = 4! X 5 = T x 5 = 120 ( final result )
N!
Example:
20 = 1
22 = 2 x 2 = 4
24 = 2 x 2 x 2 x 2 = 16
How to compute 24 ?
20 = 1 ( store the temporary result in T, T is 20 )
21 = 20 x 2 = T x 2 = 2 ( store the temporary result in T , T is 21 )
22 = 21 X 2 = T x 2 = 4 ( store the temporary result in T , T is 22 )
23 = 22 X 2 = T x 2 = 8 ( store the temporary result in T , T is 23 )
24 = 23 X 2 = T x 2 = 16 ( final result )
2N
int number, result, counter;
cout << "Enter a positive integer:";
cin >> number;
result = 1;
counter = 1;
while(counter <= number){
result *= 2; // result = result * 2
counter += 1;
}
cout << "Two raised to the " << number
<< " power is " << result << endl;
Find Maximum Value
int value=0; // input value
int max=0; // maximum value
while(value!=-1){
cout << "Enter a positive integer”
<< " (-1 to stop):";
cin >> value;
if(value > max)
max = value;
}
cout << "The maximum value found is "
<< max << endl;
//find the average of a list of integers
#include <iostream>
using namespace std;
int main() {
int listSize = 0;
int value;
double sum = 0;
double average;
cout << "Provide a list of numbers (-1 to stop) "
<< endl;
cin >> value;
while (value != -1) {
sum += value;
listSize += 1;
cin >> value;
}
if(listSize > 0){
average = sum / listSize;
cout << "Average: " << average << endl;
}
else
cout << "No list to average" << endl;
return 0;
}