Professional Documents
Culture Documents
B. While
- its functionality is simply to repeat statementwhile the condition set in
expression is true.
-Example:
// custom countdown using while
#include <iostream>
using namespacestd;
intmain ()
{
intn;
cout << "Enter the starting number > ";
cin >> n;
while(n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return0;
}
-Example:
// continue loop example
#include <iostream>
using namespacestd;
intmain ()
{
for(intn=10; n>0; n--) {
if(n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return0;
}
D. While True
-This is commonly called "infinite loop". Yet it is not technically infinite - it
will stop once control flows through break.
-Example:
hile( true ) {
doSomething();
if( condition() ) {
break;
}
doSomethingElse();
}
E. Do/While
-Its functionality is exactly the same as the while loop, except that
conditionin the do-while loop is evaluated after the execution of statement
instead of before, granting at least one execution of statementeven if
conditionis never fulfilled.
-Example:
// number echoer
#include <iostream>
using namespacestd;
intmain ()
{
unsigned longn;
do{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: "<< n << "\n";
} while(n != 0);
return0;
}
F. Jump/Loop
-A C++ jump statement performs an immediate local transfer of control.
-Example:
break;
continue;
return [expression];
goto identifier;
G. if/else
-The if keyword is used to execute a statement or block only if a condition
is fulfilled. Its form is: if (condition) statement
-We can additionally specify what we want to happen if the condition is not
fulfilled by using the keyword else. Its form used in conjunction with if is: if
(condition) statement1 else statement2
-Example:
if(x == 100)
cout << "x is 100";
else
cout << "x is not 100";