User Tools

Site Tools


Lesson 2:Doing Arithmetic


Before you begin this lesson, please read these articles:

Declaring Variables

In order to use variables in a program, they must be declared.

The first order of business is to decide the scope of the variable: global or local. If the variable is needed for many different functions, it is declared prior to the code for these functions. Variables must be declared outside of the function in which they are used.

To declare a variable, we must know what kind of a variable it is. Here are some types of variables and what that type means:

  • int integers or whole numbers
  • double a decimal number
  • signed positive or negative number
  • unsigned positive number only
  • char one character or byte
  • string one or more characters or bytes


  • double always has a decimal point even when referring to a whole number. For example:
  • Punctuation can be included in a string.
  • A string can contain an entire sentence. For example:
    Hello World!

Some Simple Arithmetic Operators

You are probably familiar with these operators.

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % modulo
  • Note:The percent sign ("%") does not calculate percentages. It returns the remainder after division. For example:

    returns "1" because after dividing "3" into "10" there is a remainder of "1". There are a couple of ways to write calculations in c++. We declare myNumber to be an unsigned integer:

          int unsigned myNumber;

    We want to assign it a value of "3".

    myNumber = 3;

    Now we want to increase myNumber by adding "5" to it. There are two ways to do this.

    myNumber = myNumber + 5;


    myNumber += 5;

    We can use are other operators in the same way. Note:The equals sign comes last.

Getting User Input

To receive information from a user and put that information into a variable we can write the following statement using our variable "myNumber":

cin >> myNumber;

Best Practices:Variables are clearly named. The first word in a variable's name is lower case while the remaining words are upper case. For example:


It is not necessary to use "endl" with "cout" when you ask for user input. This is done automatically.


  1. Write, compile and test five related programs to prompt the user for two numbers. Prompt the user twice. Perform addition, subtraction, multiplication, division and modulo with these user provided numbers. Display the result to the user. Be sure your final prompt is on a separate line.
  2. Write, compile and test a program prompting the user to enter a name. Display the message:

    followed by the name entered. Be sure to have the final prompt appear on a separate line.

  3. Read the following articles:
cpp_lesson02.txt · Last modified: 2013/07/03 14:27 (external edit)