The basics of programming in c++ for beginners

Select if and else statements in C++

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.

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:

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.

операторы логического выбора if  elseMain, it is important to remember:

  • syntax if:

операторы логического выбора if else

  •  syntax if else:

операторы логического выбора if else

or if you want more conditions:

операторы логического выбора if else

  • block designif else  – inseparable. If it is found in the code, it is impossible to separate the extraneous code. For example :

операторы логического выбора if else

    • 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

21 thoughts on “Select if and else statements in C++

  1. Is it possible to do so?
    if(*condition*)
    {
    *Code *
    }
    if(*another condition *)
    {
    *Code *
    }

    1. Could be so, Once this is one if statement, and followed by a second independent statement if … Only then it is necessary to divide them ;
      But you should understand what you are doing:

      if( ( x = 5 ) > 2 ) { /*операторы №1*/ };
      if( x > 4 ) { /*операторы №2*/ };

      It executed two groups of statements: №1 and №2.
      And if you want to exclusive branches, you need if … else if … , as described above, or case statement.

    1. If ivan – is another variable and). the same integer, and b). announced earlier in). she was awarded for a numerical value … then yes, this is permissible.

      But I guess, that this is not the, What did you mean… And in order, name_student to contain it name students, you need to declare the type name_student character string. Like this:
      char name_student[] = "ivan";
      Or so:
      string name_student( "ivan" );

  2. Welcome here such problem.

    #include
    #include
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, “rus”);
    int number1 = 0;
    int number2 = 0;

    cout <> number1;
    cout <> number2;

    if (number1 < number2)
    cout << "\a\a\a\a\a\a\a\a";
    cout < number2)
    cout << "\a\a\a\a\a\a";
    cout << "\t\t\tПервое число больше второго \n";
    else
    cout << "\a\a\a\a\a\a";
    cout <—— The assembly began: project: Project2, Configuration: Debug Win32 ——
    1>Source.cpp
    1>c:\usersgoodjarsourcereposproject2project2source.cpp(19): error C2181: Invalid else without the pair if
    1>c:\usersgoodjarsourcereposproject2project2source.cpp(22): error C2181: Invalid else without the pair if
    1>project Build “Project2.vcxproj” complete with error.
    ========== Build: successfully: 0, with errors: 1, without changes: 0, missing: 0 ==========

    What's wrong with him?

    1. if (number1 < number2)
      {
      cout << "\a\a\a\a\a\a\a\a";
      cout < number2)
      cout << "\a\a\a\a\a\a";
      cout << "\t\t\tПервое число больше второго \n";
      }
      else
      cout << "\a\a\a\a\a\a";

      1. oops… still I found

        #include
        using namespace std;

        int main()
        {
        setlocale(LC_ALL, “rus”);
        int number1 = 0;
        int number2 = 0;

        cout << number1;
        cout << number2;

        if (number1 < number2)
        {
        cout << "текст";
        cout << number2;
        cout << "текст";
        }
        else
        cout << "текст";
        }

Leave a Reply

Your email address will not be published. Required fields are marked *