Pages

Saturday, September 23, 2017

Easy tutorial for C / C++ Operator - 2

Easy tutorial for C / C++ Operator - 2


Comparison / relational operators:

- Returns the result value as true (1) or false (0) with an operator that computes the case relationship, such as greater than or equal to. The types of operators are as follows.

a == b : a and b are equal
a! = b  : a and b are different.
a > b   : a is greater than b
a < b   : a is less than b
a >= b : a is greater than or equal to b
a <= b : a is less than or equal to b

Example Code

#include <iostream>
using namespace std;

int main() {

     int a, b, compare;
          a = 3 ;
          b = 5 ;
    
         compare = a > b ;
     cout << "result  = " << compare <<endl;

          compare = a < b ;
     cout << " result = " << compare <<endl;
   
          return 0;

}

results:

result  = 0
result  = 1

- Declare integer variables a, b, and compare, substitute 3 for a, and 5 for b.

- First, we assign the result of a > b to compare. Since b is greater than a, the expression a > b becomes false and returns zero.

- The returned 0 is assigned to compare and 0 is printed. The expression a < b is then true, so 1 is returned and 1 is printed as a result.

Logical Operators:

- As logical operators, !, && and || are exist.

- ! is a logical negation. The operator obtains a logical value that is true (false) for false (true).

- && is an operator that concludes that a logical AND operator is true when all conditions are satisfied.

- || is a logical OR operator that concludes that if any condition is satisfied, it is true.

Example Code

#include <iostream>
using namespace std;

int main() {

     int a, b;

          a = 1 ;
          b = 5 ;
    
          if(a > 2 && b > 2){
           cout << "Logical AND !!!" <<endl;
          }else{
           cout << "Hi !!!" <<endl;
          }

          if(a > 2 || b > 2){
           cout << "Logical OR !!!" <<endl;
          }else{
           cout << "Hi !!!" <<endl;
          }
   
          return 0;

}

results:

Hi !!!
Logical OR !!!

- Declare integer variables a and b, substitute 1 for a, and 5 for b.

- The condition of the first if statement is a > 2 && b > 2.

- If both a and b are greater than 2, "Logical AND !!!" is printed. Otherwise, " Hi !!!" will be printed.

- Because "1" is assigned to a, you can see that the sentence "Hi !!!" is printed.

- In the second if statement, the condition is a > 2 || b > 2.

- If a or b is greater than 2, "Logical OR !!!" is printed.

- Because 5 is assigned to b, the statement "Logical OR !!!" is printed.

No comments:

Post a Comment