Принятие решений в C / C ++ (if, if..else, Nested if, if-else-if)

Опубликовано: 7 Января, 2022

В реальной жизни бывают ситуации, когда нам нужно принять какие-то решения, и на основе этих решений мы решаем, что нам делать дальше. Подобные ситуации возникают и в программировании, когда нам нужно принять некоторые решения, и на основе этих решений мы выполним следующий блок кода. Например, в C, если встречается x, выполните y, иначе выполните z. Также может быть несколько условий, как в C, если возникает x, затем выполнить p, иначе, если возникает условие y, выполнить q, иначе выполнить r. Это условие C else-if является одним из многих способов импорта нескольких условий.

Операторы принятия решений в языках программирования определяют направление потока выполнения программы. Операторы принятия решений, доступные на C или C ++:

  1. если заявление
  2. if..else заявления
  3. вложенные операторы if
  4. если-иначе-если лестница
  5. операторы переключения
  6. Заявления о прыжках:
    1. перерыв
    2. Продолжить
    3. перейти к
    4. возвращение

оператор if в C / C ++

Оператор if - это самый простой оператор принятия решения. Он используется, чтобы решить, будет ли выполняться определенный оператор или блок операторов, то есть, если определенное условие истинно, то блок операторов выполняется, в противном случае - нет.
Синтаксис :

 если (условие) 
{
   // Операторы для выполнения, если
   // условие верно
}

Здесь условие после оценки будет либо истинным, либо ложным. Оператор C if принимает логические значения - если значение истинно, то он выполнит блок операторов под ним, в противном случае - нет. Если мы не поставим фигурные скобки '{' и '}' после if (условие), то по умолчанию оператор if будет считать, что первый оператор, расположенный непосредственно под ним, находится внутри своего блока.
Пример :

 если (условие)
   оператор1;
   оператор2;

// Здесь если условие истинно, если блок 
// будет считать, что внутри находится только оператор1 
// его блок.

Схема

 

C

// C program to illustrate If statement
#include <stdio.h>
 
int main() {
    int i = 10;
 
    if (i > 15)
    {
       printf("10 is less than 15");
    }   
    
    printf("I am Not in if");
}

C++

// C++ program to illustrate If statement
#include<iostream>
using namespace std;
 
    int main()
    {
        int i = 10;
  
        if (i > 15)
        {
           cout<<"10 is less than 15";
        }   
        
        cout<<"I am Not in if";
    }
Output: 
I am Not in if

 

Поскольку условие, присутствующее в операторе if, является ложным. Итак, блок под оператором if не выполняется.

if-else в C / C ++

Один только оператор if сообщает нам, что если условие истинно, он выполнит блок операторов, а если условие ложно, то не выполнит. Но что, если мы хотим сделать что-то еще, если условие ложно. А вот и инструкция C else. Мы можем использовать оператор else с оператором if для выполнения блока кода, когда условие ложно.
Синтаксис :

 если (условие)
{
    // Выполняет этот блок, если
    // условие верно
}
еще
{
    // Выполняет этот блок, если
    // условие ложно
}

Схема :

Example:
 

C

// C program to illustrate If statement
#include <stdio.h>
 
int main() {
    int i = 20;
 
    if (i < 15)
        printf("i is smaller than 15");
    else
        printf("i is greater than 15");
             
    return 0;   
}

C++

// C++ program to illustrate if-else statement
#include<iostream>
using namespace std;
 
int main()
 {
        int i = 20;
  
        if (i < 15)
            cout<<"i is smaller than 15";
        else
            cout<<"i is greater than 15";
             
    return 0;   
 }
Output: 
i is greater than 15

 

Блок кода, следующий за оператором else, выполняется, поскольку условие, присутствующее в операторе if, является ложным.

вложенный-если в C / C ++

Вложенный if в C является оператором if, который является целью другого оператора if. Вложенные операторы if означают оператор if внутри другого оператора if. Да, и C, и C ++ позволяют нам вложить операторы if в операторы if, т. Е. Мы можем разместить оператор if внутри другого оператора if.
Синтаксис:

 если (условие1) 
{
   // Выполняется, когда условие 1 истинно
   если (условие2) 
   {
      // Выполняется, когда условие 2 истинно
   }
}

Схема

Example: 
 

C

// C program to illustrate nested-if statement
#include <stdio.h>
 
int main() {
    int i = 10;
 
    if (i == 10)
    {
        // First if statement
        if (i < 15)
           printf("i is smaller than 15 ");
 
        // Nested - if statement
        // Will only be executed if statement above
        // is true
        if (i < 12)
            printf("i is smaller than 12 too ");
        else
            printf("i is greater than 15");
    }
 
    return 0;
}

C++

// C++ program to illustrate nested-if statement
#include <iostream>
using namespace std;
 
int main()
{
    int i = 10;
 
    if (i == 10)
    {
        // First if statement
        if (i < 15)
           cout<<"i is smaller than 15 ";
 
        // Nested - if statement
        // Will only be executed if statement above
        // is true
        if (i < 12)
            cout<<"i is smaller than 12 too ";
        else
            cout<<"i is greater than 15";
    }
 
    return 0;
}
Output: 
i is smaller than 15
i is smaller than 12 too

 

Лестница if-else-if в C / C ++

Здесь пользователь может выбрать один из нескольких вариантов. Операторы C if выполняются сверху вниз. Как только одно из условий, управляющих if, становится истинным, выполняется оператор, связанный с этим if, а остальная часть лестницы C else-if пропускается. Если ни одно из условий не выполняется, будет выполнена последняя инструкция else.
Синтаксис:

 если (условие)
    утверждение;
иначе если (условие)
    утверждение;
.
.
еще
    утверждение;

Example: 
 

C

// C program to illustrate nested-if statement
#include <stdio.h>
 
int main() {
    int i = 20;
  
    if (i == 10)
        printf("i is 10");
    else if (i == 15)
        printf("i is 15");
    else if (i == 20)
        printf("i is 20");
    else
        printf("i is not present");
}

C++

// C++ program to illustrate if-else-if ladder
#include<iostream>
using namespace std;
 
int main()
{
    int i = 20;
  
    if (i == 10)
        cout<<"i is 10";
    else if (i == 15)
        cout<<"i is 15";
    else if (i == 20)
        cout<<"i is 20";
    else
        cout<<"i is not present";
}
Output: 
i is 20

 

Операторы перехода в C / C ++

Эти операторы используются в C или C ++ для безусловного потока управления через функции в программе. Они поддерживают четыре типа операторов перехода:

  1. C break: этот оператор управления циклом используется для завершения цикла. Как только оператор break встречается внутри цикла, итерации цикла останавливаются, и управление сразу же возвращается из цикла к первому оператору после цикла.
    Синтаксис:
 перерыв;
  1. В основном операторы break используются в ситуациях, когда мы не уверены в фактическом количестве итераций для цикла или хотим завершить цикл на основе некоторого условия.

  1. Example: 
     

C

// C program to illustrate
// Linear Search
 
#include <stdio.h>
 
void findElement(int arr[], int size, int key)
{
    // loop to traverse array and search for key
    for (int i = 0; i < size; i++) {
        if (arr[i] == key) {
            printf("Element found at position: %d", (i + 1));
            break;
        }
    }
}
 
int main() {
    int arr[] = { 1, 2, 3, 4, 5, 6 };
     
    // no of elements
    int n = 6; 
     
    // key to be searched
    int key = 3;
 
    // Calling function to find the key
    findElement(arr, n, key);
 
    return 0;
}

C++

// CPP program to illustrate
// Linear Search
#include <iostream>
using namespace std;
 
void findElement(int arr[], int size, int key)
{
    // loop to traverse array and search for key
    for (int i = 0; i < size; i++) {
        if (arr[i] == key) {
            cout << "Element found at position: " << (i + 1);
            break;
        }
    }
}
 
// Driver program to test above function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = 6; // no of elements
    int key = 3; // key to be searched
 
    // Calling function to find the key
    findElement(arr, n, key);
 
    return 0;
}
  1.  
Output: 
Element found at position: 3

 

  1.  
  2. C continue: This loop control statement is just like the break statement. The continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. 
    As the name suggest the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and next iteration of the loop will begin. 
    Syntax: 
     
continue;
  1.  

  1. Example: 
     

C

// C program to explain the use
// of continue statement
#include <stdio.h>
 
int main() {
    // loop from 1 to 10
    for (int i = 1; i <= 10; i++) {
 
        // If i is equals to 6,
        // continue to next iteration
        // without printing
        if (i == 6)
            continue;
 
        else
            // otherwise print the value of i
            printf("%d ", i);
    }
 
    return 0;
}

C++

// C++ program to explain the use
// of continue statement
 
#include <iostream>
using namespace std;
 
int main()
{
    // loop from 1 to 10
    for (int i = 1; i <= 10; i++) {
 
        // If i is equals to 6,
        // continue to next iteration
        // without printing
        if (i == 6)
            continue;
 
        else
            // otherwise print the value of i
            cout << i << " ";
    }
 
    return 0;
}
  1.  
Output: 
1 2 3 4 5 7 8 9 10

 

  1.  

If you create variable in if else in C/C++, it will be local to that if/else block only. You can use global variables inside if/else block. If name of variable you created in if/else is  as same as any global variable then priority will be given to `local variable`. 

C++

#include<iostream>
using namespace std;
 
int main(){
    int gfg=0; // local variable for main
    cout<<"Before if-else block "<<gfg<<endl;
    if(1){
        int gfg = 100; // new local variable of if block
        cout<<"if block "<<gfg<<endl;
    }
    cout<<"After if block "<<gfg<<endl;
    return 0;
}
/*
    Before if-else block 0
    if block 100
    After if block 0
*/

C

#include <stdio.h>
 
int main() {
 
      int gfg=0; // local variable for main
    printf("Before if-else block %d ",gfg);
    if(1){
        int gfg = 100; // new local variable of if block
        printf("if block %d ",gfg);
    }
    printf("After if block %d",gfg);
  return 0;
}
  1. C goto: The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from one point to another within a function. 
    Syntax
     
Syntax1      |   Syntax2
----------------------------
goto label;  |    label:  
.            |    .
.            |    .
.            |    .
label:       |    goto label;
  1. In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier which indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax. 
     

  1. Below are some examples on how to use goto statement:
    Examples: 
     

C

// C program to print numbers
// from 1 to 10 using goto statement
#include <stdio.h>
 
// function to print numbers from 1 to 10
void printNumbers()
{
    int n = 1;
label:
    printf("%d ",n);
    n++;
    if (n <= 10)
        goto label;
}
 
// Driver program to test above function
int main() {
    printNumbers();
    return 0;
}

C++

// C++ program to print numbers
// from 1 to 10 using goto statement
#include <iostream>
using namespace std;
 
// function to print numbers from 1 to 10
void printNumbers()
{
    int n = 1;
label:
    cout << n << " ";
    n++;
    if (n <= 10)
        goto label;
}
 
// Driver program to test above function
int main()
{
    printNumbers();
    return 0;
}
  1.  
Output: 
1 2 3 4 5 6 7 8 9 10

 

  1.  
  2. C return: The return in C or C++ returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and return the control from where it was called. The return statement may or may not return anything for a void function, but for a non-void function, a return value is must be returned. 
    Syntax: 
     
return[expression];
  1. Example: 
     

C

// C code to illustrate return
// statement
#include <stdio.h>
 
// non-void return type
// function to calculate sum
int SUM(int a, int b)
{
    int s1 = a + b;
    return s1;
}
 
// returns void
// function to print
void Print(int s2)
{
    printf("The sum is %d", s2);
    return;
}
 
int main()
{
    int num1 = 10;
    int num2 = 10;
    int sum_of = SUM(num1, num2);