03 - Conditionals and loop structures
03 - Conditionals and loop structures
🔨 🔥 Assignment 🔥 🔨
Create a new project in the way explained in the first instruction.
Logical conditions and operators
In C and C++ statements are considered to be false if their value is equal to 0, and to be true if their value is different from 0, so almost any type of variable can be used in a logical condition. Additionally, in C++ language fundamental bool type can be used to store true and false values:
bool flag = true;
false flag =
To create logical conditions, one can use operators:
Operator | Description | Example | Example result |
---|---|---|---|
= | Assign a value to a variable | a = 0.2 |
true |
== | Equal to | 0 == 0 |
true |
!= | Not equal to | 0 != 0 |
false |
< | Less than | 3 < 3 |
false |
> | Greater than | 5 > 1 |
true |
<= | Less than or equal to | 5 <= 6 |
true |
>= | Greater than or equal to | 5 >= 6 |
false |
! | Negation | !0 |
true |
&& | Logical and | (1 > 2) && (1 < 2) |
false |
|| | Logical or | (1 > 2) || (1 < 2) |
true |
With parentheses these operators can be used to create more complex logical conditions.
ATTENTION: C and C++ use short-circuit (minimal) evaluation, which means that a compiler only evaluates necessary parts of statements (e.g. when the first argument of or
clause i true
, the other one does not need evaluation).
Flow control : if-else
Except for storing and modifying information, program needs to make decisions. You can control which part of code will be executed using if - else expression. Its syntax is presented below:
if(condition1){
// Code to be executed if condition1 is met
}else if(condition2){
// Code to be executed if condition1 is not met and condition2 is met
}else{
// Code to be executed if condition1 is not met and condition2 is not met
}
Else statements are not necessary when not required. If there is no need to perform alternative actions when the condition in if
statement is not met, there is no reason to include else
blocks.
🔨 🔥 Assignment 🔥 🔨
- Create a program that will ask user for the float value, and inform him that he is flying too low if entered value is below 100, that he is on good altitude if the value is between 100 and 1000, and that he is too high if the value exceeds 1000.
- Create a program that will ask user for 2 integer values, and inform him if the second value is a divisor of the first. HINT: use modulo operator (%).
Flow control: switch-case
Another often used type of flow control is switch-case. It is similar to concatenating if-else statements, but it is limited to constant, integer expressions:
switch(expression) {
case 1:
std::cout << "expression is equal to 1";
break;
case 2:
std::cout << "expression is equal to 2";
break;
default:
std::cout << "value of expression is out of scope";
break;
}
Program evaluates the tested expression, and compares it to the labels that are constant expressions (labels are the expressions between each case
and :
). If the tested expression is equal to a label, code lines following that case are executed, until the break command or the switch closing bracket is encountered. The default
label is optional and is used when the tested expression does not match any label.
int dinner_choice;
std::cout << "How many courses? ";
std::cin >> dinner_choice;
switch(dinner_choice)
{case 3:
std::cout << "Soup" << std::endl;
case 2:
std::cout << "Main course" << std::endl;
case 1:
std::cout << "Dessert" << std::endl;
break;
default:
std::cout << "Beer" << std::endl;
break;
}
🔨 🔥 Assignment 🔥 🔨
- Test the above switch-case. Try entering different values, what is happening and why?
- Create a program with menu: 1 - prints “Hello”, 2 - display random number in the range from 900 to 9000, 3 - ask user for two numbers and display a sum. HINT: use switch-case. Example of menu:
1: Say hello
2: Random number
3: Sum calculatorSelect option:
Loops
Loops repeat a statement (or block of statements) as long as some condition is true, or for certain number of times. Simplest loop is:
while(tested_expression)
{//statements to repeat as long as tested_expression == true
}
Similar construct is a do while loop:
do
{//statements to repeat as long as tested_expression == true
while(tested_expression) }
Above does the same as standard while loop, but condition is tested after every iteration instead of before.
🔨 🔥 Assignment 🔥 🔨
Modify previous program, by adding option 0 that ends the program. Menu should be prompted until the user chooses that option.
HINT: Use while loop so program returns to menu and prompts user for input.
If loop should be repeat for a certain number of times, for loop can be used:
for(initialization; condition; post iteration)
{//statements to repeat;
}
Which is executed in the following steps:
- Initializations are the statements executed once at the beginning of the loop.
- The condition is checked. If it is true, the loop continues; otherwise, the loop ends.
- If the condition was true statements to repeat are executed once.
- Post iteration statements are executed, and loop returns to step 2.
For example:
for(int n = 10; n > 0; n--) {
std::cout << n << ", ";
}std::cout << "liftoff!" << std::endl;
Like in switch-case, also in loops, break
command can be used to terminate loop. Similar command is continue
, which terminates current iteration, without terminating whole loop:
for(int i = 1; i < 100; i++) //loop iterating up to 99
{if(i == 13)
{continue; //jinx floor
else if(i > 20)
}
{std::cout << "I\'m out of oxygen!" << std::endl;
break;
}std::cout << "We are on " << i << " floor" << std::endl;
}
ATTENTION: Most of the programs can be written without the break
and continue
statements used in loops. Do not overuse them!
🔨 🔥 Assignment 🔥 🔨
Add 4th option to the menu. In this case program asks user for an integer value ( X ). Then displays numbers for 0 up to X and than back to 0.
More information on conditions and loop statements: http://www.cplusplus.com/doc/tutorial/control/
Final assignments 🔥 🔨
ATTENTION: All below tasks have to be placed in a single program. The exercises should be placed in a while loop, so the user will be able to choose what he want to do or terminate the program by pressing x or X. Program have to be accompanied by a menu allowing user to navigate between options:
Choose an option:
1 – Exercise 1
2 – Exercise 2
3 – Exercise 3
x – Exit
Exercise 1
Calculate the value of pi, with the number of iterations and approximation method chosen by the user. Implement the Leibniz and Wallis methods:
Leibniz:
Wallis:
Exercise 2
Write the program, which will show all ASCII coded characters (1-255, show both code and character). After every 40 codes, each in separate line, the program should stop and wait for a user to press any key (use modulo operation: %
).
Exercise 3
Factorial of a n, is the product of all positive integers less than or equal to n: n!=1*2*...*(n-1)*n. The value of 0! is 1. Factorial is defined for non-negative integer.
- Write the program, which will calculate factorial of the number provided by a user,
- handle the situation when n<0 and n=0,
- determine maximal n for which program will provide correct result (
int
type will not overflow).
Homework đź’Ą đźŹ
- Print all prime numbers in an interval provided by a user (user provides the minimal and maximal number)
- Compute the factorial using different integer types. What is the maximal value of the factorial argument that the value of the function is computed properly for unsigned short
int
,unsigned int
,unsigned long
andunsigned long long
? - Write a program that computes the least common multiple for two positive numbers read from a user.
- John was asked to compute the values of , where z is the value provided by a user but he cannot use a constant e. He is supposed to use the . Write a program that will print the error of the above equation in comparison to the direct computation of provided z when only first 2, first 5 or first 10 elements of the series are used.
Authors: Rafał Kabaciński, Michał Fularz, Dominik Pieczyński, Tomasz Mańkowski, Jakub Tomczyński