0% found this document useful (0 votes)
47 views

Conditions and Loops

The document discusses various conditional statements and loops in C++. It covers if-else statements, else-if statements, switch statements, while loops, do-while loops, for loops, and how to use break and continue within loops. Nested if statements and switch statements are also explained. In summary: 1) C++ supports logical conditions and conditional statements like if-else, else-if to perform different actions based on various conditions. 2) Loops like while, do-while and for loops allow repeating a block of code as long as or for a set number of iterations of a condition. 3) Break and continue statements can be used within loops to exit/skip the current iteration.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Conditions and Loops

The document discusses various conditional statements and loops in C++. It covers if-else statements, else-if statements, switch statements, while loops, do-while loops, for loops, and how to use break and continue within loops. Nested if statements and switch statements are also explained. In summary: 1) C++ supports logical conditions and conditional statements like if-else, else-if to perform different actions based on various conditions. 2) Loops like while, do-while and for loops allow repeating a block of code as long as or for a set number of iterations of a condition. 3) Break and continue statements can be used within loops to exit/skip the current iteration.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

C++ Conditions

and Loops
C++ Conditions
▪ C++ supports the usual logical conditions from mathematics:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

▪ You can use these conditions to perform different actions for different
decisions.
C++ Conditions…
C++ Conditions…

▪ C++ has the following conditional statements:


• Use if to specify a block of code to be executed, if a
specified condition is true
• Use else to specify a block of code to be executed, if the
same condition is false
• Use else if to specify a new condition to test, if the first
condition is false
• Use switch to specify many alternative blocks of code to
be executed
The if Statement
▪ Use the if statement to specify a block of C++ code to be executed if
a condition is true.
▪ Syntax
▪ if (condition) {
// block of code to be executed if the condition is true
}
▪ Note that if is in lowercase letters. Uppercase letters (If or IF) will
generate an error.
The if Statement…
▪ In the example below, we test two values to find out if 20 is greater
than 18. If the condition is true, print some text:
▪ if (20 > 18) {
cout << "20 is greater than 18";
}
▪ We can also test variables:
▪ int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
The else Statement
▪ Use the else statement to specify a block of code to be
executed if the condition is false.
▪ Syntax
▪ if (condition) {
// block of code to be executed if the condition is
true
} else {
// block of code to be executed if the condition is
false
}
The else Statement…
▪ Example
▪ int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
The else if Statement
▪ Use the else if statement to specify a new condition if the first
condition is false.
▪ Syntax
▪ if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is
false and condition2 is true
} else {
// block of code to be executed if the condition1 is
false and condition2 is false
}
The else if Statement…
▪ Example
▪ int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Short Hand If...Else (Ternary Operator)
▪ There is also a short-hand if else, which is known as
the ternary operator because it consists of three
operands. It can be used to replace multiple lines of code
with a single line. It is often used to replace simple if else
statements:
▪ Syntax
▪ variable = (condition) ? expressionTrue : expressionFalse;
Short Hand If...Else (Ternary Operator)…
▪ Instead of writing:
▪ int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

▪ You can simply write:


▪ int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
C++ Switch Statements
▪ Use the switch statement to select one of many code blocks to be
executed.
▪ Syntax
▪ switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
C++ Switch Statements…

▪ This is how it works:


• The switch expression is evaluated once
• The value of the expression is compared with the values
of each case
• If there is a match, the associated block of code is
executed
• The break and default keywords are optional, and will
be described later in this lesson.
C++ Switch Statements…
▪ The example below uses the weekday number to calculate the weekday name:

▪ int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
C++ Switch Statements…
▪ The break Keyword

▪ When C++ reaches a break keyword, it breaks out of the switch block.

▪ This will stop the execution of more code and case testing inside the
block.

▪ When a match is found, and the job is done, it's time for a break.
There is no need for more testing.

▪ A break can save a lot of execution time because it "ignores" the


execution of all the rest of the code in the switch block.
C++ Switch Statements…
▪ The default Keyword
▪ The default keyword specifies some code to run if there is no case match:
▪ int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend“
▪ Note: The default keyword must be used as the last statement in the
switch, and it does not need a break.
C++ nested if statements
▪ It is always legal to nest if-else statements, which means you
can use one if or else if statement inside another if or else if
statement(s).
▪ Syntax
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}
▪ You can nest else if...else in the similar way as you have
nested if statement.
C++ nested if statements…
#include <iostream>using namespace std;
int main () {
// local variable declaration:
int a = 100;
int b = 200;
// check the boolean condition
if( a == 100 ) {
// if condition is true then check the following
if( b == 200 ) {
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
C++ nested switch statements
▪ It is possible to have a switch as part of the statement sequence of an outer switch. Even if the
case constants of the inner and outer switch contain common values, no conflicts will arise.

▪ Syntax
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}
C++ nested switch statements…
#include <iostream>
using namespace std;

int main () {
// local variable declaration:
int a = 100;
int b = 200;

switch(a) {
case 100:
cout << "This is part of outer switch" << endl;
switch(b) {
case 200:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;

return 0;
}
C++ Loops
▪ Loops can execute a block of code as long as a specified
condition is reached.
▪ Loops are handy because they save time, reduce errors,
and they make code more readable.
▪ C++ has the following loops:
• Use while loop when you what to loop through a block of
code as long as a specified condition is true.
• Use the for loop when you know exactly how many
times you want to loop through a block of code.
C++ Loops…
C++ While Loop
▪ The while loop loops through a block of code as long as a
specified condition is true:
▪ Syntax
▪ while (condition) {
// code block to be executed
}
C++ While Loop…
▪ In the example below, the code in the loop will run, over
and over again, as long as a variable (i) is less than 5:
▪ int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
▪ Note: Do not forget to increase the variable used in the
condition, otherwise the loop will never end!
C++ While Loop - The Do/While Loop
▪ The do/while loop is a variant of the while loop. This loop
will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the
condition is true.
▪ Syntax
▪ do {
// code block to be executed
}
while (condition);
C++ While Loop - The Do/While Loop…
▪ The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
▪ int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

▪ Do not forget to increase the variable used in the condition, otherwise


the loop will never end!
C++ For Loop
▪ When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
▪ Syntax
▪ for (statement 1; statement 2; statement 3) {
// code block to be executed
}
▪ Statement 1 is executed (one time) before the execution of the code
block.
▪ Statement 2 defines the condition for executing the code block.
▪ Statement 3 is executed (every time) after the code block has been
executed.
C++ For Loop…
▪ The example below will print the numbers 0 to 4:
▪ for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
▪ This example will only print even values between 0 and 10:
▪ for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}
C++ Break in For Loop
▪ You have already seen the break statement used in an earlier
lesson. It was used to "jump out" of a switch statement.

▪ The break statement can also be used to jump out of a loop.

▪ This example jumps out of the loop when i is equal to 4:


▪ for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
C++ Continue in For Loop
▪ The continue statement breaks one iteration (in the loop),
if a specified condition occurs, and continues with the next
iteration in the loop.
▪ This example skips the value of 4:
▪ for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Break and Continue in While Loop
▪ You can also use break and continue in while loops:
▪ Break Example
▪ int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}
Break and Continue in While Loop…
▪ Continue Example
▪ int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
C++ nested loops
▪ A loop can be nested inside of another loop. C++ allows at
least 256 levels of nesting.
▪ The syntax for a nested for loop statement in C++ is as
follows:
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s); // you can put more statements.
}
C++ nested loops…
▪ The syntax for a nested while loop statement in C++ is
as follows:

while(condition) {
while(condition) {
statement(s);
}
statement(s); // you can put more statements.
}
C++ nested loops…
▪ The syntax for a nested do...while loop statement in
C++ is as follows:

do {
statement(s); // you can put more statements.
do {
statement(s);
} while( condition );

} while( condition );
C++ nested loops…
#include <iostream>
using namespace std;

int main () {
int i, j;

for(i = 2; i<100; i++) {


for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) cout << i << " is prime\n";
}

return 0;
}

You might also like