Examples of Operators in c++ Programming

0

Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction. 

All Contributions

example of operators priorities:

priorities are like the following:

  1. power ^
  2. braces ()
  3. multiply and division * /
  4. addition and subtraction + -
  5. assignment =
int n1=5;
int n2=4;
int n3=7;
int n4=12;
int result=n1+n2+n3+n4;
cout<<"n1+n2+n3+n4 = "<<result;  //prints 28
result=n1+n2*n3-n4;
cout<<"n1+n2*n3-n4 = "<<result;  //prints 21
result=(n1+n2)*(n3-n4);
cout<<"(n1+n2)*(n3-n4) = "<<result;  //prints 171

example of operators priorities:

#include <iostream>

using namespace std;
int main()
{
  int x=4+(3-2)*2;
  cout<<x<<endl; //prints 6
  int y=3+4-2/(2+4)*3;
  cout<<y; //prints 7 
return 0;
}

Output:

6

7

Logical Operators :

#include <iostream>
using namespace std;
int main() 
{
    bool result;
    result = (3 != 5) && (3 < 5);     // true
    cout << "(3 != 5) && (3 < 5) is " << result << endl;
    result = (3 == 5) && (3 < 5);    // false
    cout << "(3 == 5) && (3 < 5) is " << result << endl;
    result = (3 == 5) && (3 > 5);    // false
    cout << "(3 == 5) && (3 > 5) is " << result << endl;
    result = (3 != 5) || (3 < 5);    // true
    cout << "(3 != 5) || (3 < 5) is " << result << endl;
    result = (3 != 5) || (3 > 5);    // true
    cout << "(3 != 5) || (3 > 5) is " << result << endl;
    result = (3 == 5) || (3 > 5);    // false
    cout << "(3 == 5) || (3 > 5) is " << result << endl;
    result = !(5 == 2);    // true
    cout << "!(5 == 2) is " << result << endl;
    result = !(5 == 5);    // false
    cout << "!(5 == 5) is " << result << endl;
    return 0;
}

Relational Operators :

#include <iostream>
using namespace std;
int main()
{
    int a, b;
    a = 3;
    b = 5;
    bool result;
    result = (a == b);   // false
    cout << "3 == 5 is " << result << endl;
    result = (a != b);  // true
    cout << "3 != 5 is " << result << endl;
    result = a > b;   // false
    cout << "3 > 5 is " << result << endl;
    result = a < b;   // true
    cout << "3 < 5 is " << result << endl;
    result = a >= b;  // false
    cout << "3 >= 5 is " << result << endl;
    result = a <= b;  // true
    cout << "3 <= 5 is " << result << endl;
    return 0;
}

Assignment Operators :

#include <iostream>
using namespace std;
int main() 
{
    int a, b;
    // 2 is assigned to a
    a = 2;
    // 7 is assigned to b
    b = 7;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "\nAfter a += b;" << endl;
    // assigning the sum of a and b to a
    a += b;  // a = a +b
    cout << "a = " << a << endl;
    return 0;
}

total contributions (7)

New to examplegeek.com?

Join us