Code About Us Tutorial


  Statements & Expression
    The while Statement
    The do ... while Statement
    The for Statement
    The break Statement
    The continue Statement
    The goto Statement
    The switch Statement
    Keywords
    Scope Resolution (::)
    Arithmatic Operators


   
 

Home > Statements & Expression > Arithmatic Operators

December 1, 2009 7:24 am

   

Arithmatic Operators

In this section we will be learning about how to use arithmetic operators in C++. An operator is just a symbol that operates on one or more expressions, creating a value that can be assigned to a variable.

Here are some of the operators we will be going over: (+)add, (-) subtract,(*) Multiply, (/) Divide, (%) Modulus. I’ll create a simple application to using the switch statement you were shown above to show the usage of all the operators.

 

 
#include <iostream.h>

int main() { int num1,num2; int result; char Oper; cout<<"Enter two numbers: "; cin >> num1 >> num2; cout <<"Now enter a math operator: "; cin >> Oper; switch(Oper) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; case '%': result = num1 % num2; break; default: cout << "Syntax error, used wrong operators or didn't follow directions! :Pn"; break; } cout << num1 << Oper << num2 << "= " << result << endl; return 0; }

This application prompts the user to enter two numbers, then any of the 5 operators we learned. After it decides what operator was entered it finds the case and then breaks and returns the value. If you didn’t enter a valid operator it will call the default and return an error message.

For reference, here is a table of the operators and their uses:

Fig. 2b:
fig. 2b (figs/fig2b.htm)

Operators

  1. The Assignment Operator - assigns a value to a variable.
    • x = y;: The basic assignment opperator, takes the left hand operand and sets it to the value of the right hand operand.

  2. The Relational Operators - for logically comparing relationships.
    • == - Equality
    • != - Inequality
    • > - Greater than
    • < - Less than
    • >= - Greater or equal than
    • <= - Less or equal than

  3. Bitwise Operators - for binary conventions.
  4. Bitwise Operators allow you to turn on and off specific bits. These are used for bit manupilations. In order to fully understand bitwise operators, you must understand the different modes of numbers and the convention between them.

    A Binary number is a number with a numerical radix of 2. Either 0 or 1, on or off. So in binary form, the number 0 is 0, 1 is 1, 2 is 10, 3 is 11, 4 is 110 ... and so on.

    An Octal number is a number with a numerical radix of 8. Octal numbers go from 0 to 7 (a total of 8 number combinations). Normally, to distinguish between decimal notation and octal notation, octal numbers always begin with a 0 followed by the actual value.

    A Decimal number is a number with a numerical radix of 10. This is the type of number that you learned in pre-school, it goes from 0-9 (total of 10).

    A Hexidecimal number is a number with a numerical radix of 16. This is strange to many people since we are so used to having 10 and less is understandable because it falls in the range. But hex numbers range from 0-9 and the letters a,b,c,d,e, and f (a total of 16 combinations). Normally hex numbers are prefixed with 0x followed by the hex digits.

    Decimal to Octal to Hex to Binary

    HEX DEC OCT BIN
    Input a number in either hex, bin, dec, or oct and press convert to see the conversion.

      For the bitwise operator to be true...
    • x & y - And - ...both x and y have to be true.
    • x | y - Or - ...either x or y have to be true true.
    • x ^ y - Xor - ...either x or y have to be true but not both at the same time.
    • ~ x - Not - ...the opposite of x has to be true. if x is false, ~x is true and if x is true ~x is false.

  5. The Shift Bitwise operators - a faster way of multiplying by 2 and dividing by 2 several times in a row.
    • x << y - Shift left - Shift the bits of x, y steps to the left (each step means "multiply by two")
    • x >> y - Shift right - Shift the bits of x, y steps to the right (each step means "divide by two")

  6. Incrementing Decrementing - adding and subtracting by 1's.
    • x++ - post-increment - adds one to the value of x after it has been executed
    • ++x - pre-increment - adds one to the value of x before it has been executed
    • x-- - post-decrement - subtracts one from the value of x after it has been executed
    • --x - pre-decrement - subtracts one from the value of x after it has been executed

    Note: All of the bitwise operators can be used in conjunction with the assignment opperator to make the bitwise compund assignment opperator. Take a look below.
    width=1
    width=1

  7. Compound Assignment Opperators - These are all made up of any one of the above operators plus an assignment opperator to make a compund assignment opperator.
    • x += y;: A combination of assignment opperator and addition, takes the left hand operand and sets it to the value of the right hand operand plus the left hand. Short for x = x + y;
    • x -= y;: Short for x = x - y;
    • x *= y;: Short for x = x * y;
    • x /= y;: Short for x = x / y;
    • x %= y;: Short for x = x % y;
    • x >>= y;: Short for x = x >> y;
    • x <<= y;: Short for x = x << y;
    • x &= y;: Short for x = x & y;
    • x |= y;: Short for x = x | y;
    • x ^= y;: Short for x = x ^ y;

  8. Turnery Operator My Favorite!
  9. The turnery operator is the only oprator in C++ that takes 3 parameters. It is a very useful operator and I happen to use it more often that I can emagine.

     

     
     (boolean expression) ? (true part) : (false part); 

    This operator can be used just like an if/else statement set, since it lets you supply if true and else arguments.

     

     
      // Example
      // Turnery operator in action!!
      int res = -10;
      res = abs( res );
      
      // somewhere else in the program...
      int abs( int val )
      {
      	return (val > 0) ? val : -val;
      }
    

    The function abs() checks to see whether the value (val) that has been passed to it is greater than 0 and returns either the true or the false part of the code depending on whether or not the value is greater than 0. The true part just returns the value without any change. The false part (if the value is negative) returns negative of that value, this just makes it a positive value if it has previously a negative one.

  10. Order of Opperations - priority levels
  11. Priority Operator Description Associativity
    1 :: scope Left
    2 () [ ] -> . sizeof   Left
    3 ++ -- increment/decrement Right
    ~ Complement to one (bitwise)
    ! unary NOT
    & * Reference and Dereference (pointers)
    (type) Type casting
    + - Unary less sign
    4 * / % arithmetical operations Left
    5 + - arithmetical operations Left
    6 << >> bit shifting (bitwise) Left
    7 < <= > >= Relational operators Left
    8 == != Relational operators Left
    9 & ^ | Bitwise operators Left
    10 && || Logic operators Left
    11 ?: Conditional Right
    12 = += -= *= /= %=
    >>= <<= &= ^= |=
    Assignation Right
    13 , Comma, Separator Left
    Associativity defines -in the case that there are several operators of the same priority level- which one must be evaluated before, the rightmost one or the leftmost one.

Well that raps up yet another exciting section of the possibilities of C++.Please Rate this Code:


    Comments for: Arithmatic Operators
MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
Make note of the bitwise operators, they are among the most helpfull and fastest in terms of speed and efficiency.

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
Make note of the bitwise operators, they are among the most helpfull and fastest in terms of speed and efficiency. says:
Shame about the horrendous spelling error in the title and the menu entry. People who can\'t spell arithmetic shouldn\'t try to write about it!

Dane Clarke [dane@yacc.net.au] Posted: 2 times. says:
Shame about the horrendous spelling error in the title and the menu entry. People who can\'t spell arithmetic shouldn\'t try to write about it!

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
Thanks but you gotta admit that this page is among one of the best pages in the entire tutorial :)

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
Thanks but you gotta admit that this page is among one of the best pages in the entire tutorial :) says:
i thought this was a programming tutorial not a spelling tutorial.....

kahl [tikal_@hotmail.com] Posted: 5 times. says:
is it me or did you forget all the \n instead of just n? for newline? or is it because of the html that they are not showing up?

kahl [tikal_@hotmail.com] Posted: 5 times. says:
adding the - on the relational operators is just pointless and must be confusing to newbs.

kahl [tikal_@hotmail.com] Posted: 5 times. says:
btw very nice page and who cares about the spealling!? what was the point of that comment. horrendous spelling!? ok....




Add Comment:
Name:
Email:


 «4» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.