Prior to this lesson,, learning basics of programming for beginners, we'll write a very simple and boring program, which somehow worked, We are doing something, but they were completely deprived of the ability to choose, as they grow. Such programs are called linear. They were, as trams: If the path is blocked – Stop. No right, neither left not turn.
Now, I want all the little good news – Our program today will be much more interesting. We will learn to use in our code operators logical choice if andelse and the program will become a kind of intrigue, can “think”, analyze and solve, what to do and what “road” go. That is now the program – This is not the tram, and your car ))) If the road was blocked, you can easily drive around an obstacle and decide, where to go next.
Before, you begin to study this topic, you need to have a good knowledge, whatlogic operations. So that, if someone is not sure, take the time to read an article about them.
Well – we proceed to the choice of our operators (they are also conditionals, they are also branching statements). We will look at some simple examples, to help you get acquainted with these operators and to use them in the future in a more complex programs.
Example: The user enters two numbers and the program determines which of these two numbers is greater.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); int variable1 = 0; int variable2 = 0; cout << "Введите первое число: "; cin >> variable1; cout << "Введите второе число: "; cin >> variable2; // сравниваем полученные значения // если первое число больше второго - выводим сообщение // если это будет не так, код в фигурных скобках не выполнится // и программа перейдет к проверке второго условия if if (variable1 > variable2) { cout << "\nРезультат сравнения: Первое число больше чем второе\n"; } // если и это условие не выполняется - переход к следующему if if (variable1 < variable2) { cout << "\nРезультат сравнения: Второе число больше чем первое\n"; } // проверяем значения на равенство. Не забывайте об операторе == // если написать variable1 = variable2, то значение // variable2 запишется в переменную variable1 if (variable1 == variable2) { cout << "\nРезультат сравнения: Числа равны\n"; } return 0; } |
Up to 14-th row all clear – the user enters two numbers, they have signed the corresponding variables. How to compare them now and show the result of the comparison? To do this, we apply the operator if (translated-IF). Writing if, next to the parentheses () record condition – Compare the values of variables(variable1 > variable2).
And if variable1 really more variable2 – this condition will return true (truth). Then the program will go to the code, which is placed inside the braces {} – strings 21 – 23. That is, we will see on the screen a message, that the first number is greater than the second.
If the condition in parentheses() not performed (returns false (lie)), the code in curly braces {} It will be ignored and the program continues with the next line of code under the block if – with the string 26. There we again check the relationship between a variable.
All similarly – If the condition is true – Run the code of this unit if, if false – move below. In string 33 check the last possible option – for equality. Be sure to use the operator == (equal to), but not = (assigned). Otherwise, this unit code if It will work with the error. For examplevariable1 = 3, and variable2 = 4 , that if we mistakenly written in the subject if(variable1 = variable2) , value 4 written in variable1.
Getif(4) . And any value other than 0, as you remember, the compiler sees as true . As a result, this block is executed, and we will see a message that, that the values are equal, although it was initially not so. be careful.
This code can be considerably reduced. At first, You can add operator else (see below). Secondly – if the blocks if or else it contains only one line of code in curly brackets {} , these braces, you can not write. We will see, how to change our code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); int variable1 = 0; int variable2 = 0; cout << "Введите первое число: "; cin >> variable1; cout << "Введите второе число: "; cin >> variable2; if (variable1 > variable2) // как и в первом примере cout << "\nРезультат сравнения: Первое число больше чем второе\n"; else if (variable1 < variable2) // иначе если variable1 < variable2 cout << "\nРезультат сравнения: Второе число больше чем первое\n"; else // иначе cout << "\nРезультат сравнения: Числа равны\n"; return 0; } |
You see, that the braces in this example we do not use. Another plus – if the first condition if performed, the remaining blocks if else and else, not checked (i.e.. time for execution of the program is reduced). Well, if the first condition is false, the program goes to the next block else if (else if), and verifies its condition – (variable1 < variable2) – string 18. If there lie, then execute the last block else, in which the condition can no longer check, as we previously went over all possible relations between the two values, and there is only the equality.
The result of these programs is the same. But in the second case, and more compact code, and the compiler less.
Main, it is important to remember:
- syntax if:
- syntax if else:
or if you want more conditions:
- block designif else – inseparable. If it is found in the code, it is impossible to separate the extraneous code. For example :
- Work-selection principle if – if the condition is true in parentheses (true), the code block is executed. If false (false) – is ignored and the program starts with a line of code, under the following block if.
- statement selection condition in parentheses may be a conventional: if(variable > 0) or combined: if(variable > 0 && variable < 100). Combined condition returnstrue, If both conditions are true.
- the condition of the statement selection can be an arithmetic expression: if(variable1 – variable2). block code if executed, if the calculation result is not equal to 0. For example: if (5 – 7), if (2 + 5). But if the if (2 -2) – code block will be ignored.
- if the blocks if , else if or else It contains only one string of code, braces can not be used. But for beginners, while you learn, I recommend always use braces.
And perhaps all of the conditional statementsif andelse. There is a programming practice on this topic.
Possibly, Watch this video. It covers conditional statementsif andelse
asdfg
#include
using namespace std;
int main()
{
setlocale(LC_ALL,”rus”);
cout <> a;
int b = 0;
cin >> b;
cout <<endl;
cout << a <<"*" <<b <<"=?"<> d;
if (d == c)
{
cout << "Верно!"<<endl;
}
if (d != c)
{
cout << "Вы ошиблись!"<< endl;
cout << "Верный ответ: "<< c;
}
return 0;
}
ss7h8e
if
else if
else
if
” eliminates the need { } as they serve as a function separator “
it seems to me that I became if and my name is Sergey I read the text and hear the voice . With thanks from the mind and heart