Lesson # 4 Performing arithmetic operations

Lesson #  4

Performing arithmetic operations

In C++, we can perform arithmetic operations such as addition (+), subtraction (-), multiplication (*) and division ( / ). The symbols (+,-,*,/) of these operations are known as arithmetic operators. Addition to these operators there is also a modulus operator % in C++ which returns the remainder. All these operators are binary operator which means they need two operands. Operators are used to combine expressions. For example, cout<< 20 + 40 will return 60 as output. In similar way, we can subtract by using -, multiply by using * (asterisk) , divide by using / (slash) and get remainder by using % (percentage). We can performs arithmetic operations both on constant literals and variables for example cout<<55 + 5 and cout<<x + y.
using namespace std;
#include<iostream>
main()
{
cout<<20+40;
cout<<endl;
int x=20, y=15;
cout<<x+y;
cout<<endl;
cout<<x-y;
cout<<endl;
cout<<x*y;
cout<<endl;
cout<<x/y;
cout<<endl;
cout<<x%y;
cout<<"\n";
system("pause");
}
Although, the code is very simple let’s discuss it.

using namespace std;
#include<iostream>
main()
{
cout<<20+40;                    // Displays the result (sum) two numbers i.e. 20 + 40
cout<<endl;                       // Inserts a new line / Move the cursor to next line
int x=20, y=15;                   // Declares and initializes the variable x with value 20 and variable y with 15
cout<<x+y;                         // Displays the sum of two variables values  i.e. values of x and y.
cout<<endl;                       // Inserts a new line / Move the cursor to next line
cout<<x-y;                          // Displays the subtraction result of x  minus y.
cout<<endl;                       // Inserts a new line / Move the cursor to next line
cout<<x*y;                         // Displays the multiplication result of x times y. Note that * multiplies two
   operands.
cout<<endl;                       // Inserts a new line / Move the cursor to next line
cout<<x/y;                          // Displays the division result of x divided by y. Mind it, that division operator truncates output as it returns only whole part of the answer and ignore the fractional part. In this case 20 / 15 = 1.33 but complier returns whole part of the answer i.e. 1.

cout<<x%y;                        // Displays the remainder after dividing the left side operand on right side operand. In this case, the compliers returns only remainder i.e. 5.

cout<<"\n";
system("pause");

}

Code & Output:


 Order of Precedence / Priority of operators: 

The order in which operators are computed is called the order of precedence or priority. In C++ each operator has a priority in which it is calculated, the multiply (*) has first priority, division has the second priority, addition and subtraction has third and fourth priority respectively.
 For example in the expression 3+5-5*2/2,  Multiplication (5*2) is computed first which gives 10 as result, then division 10/ 2  which returns 5, now addition is performed 3+5 = 8 and at last subtraction is carried out 8 – 5 so the final result of the expression is 3. We can enforce the complier to perform a specific operation first by putting parenthesis. For example in (9+3+2)*4/2+3  expression (9+3+2) are computed first because of the parenthesis around them. An example can make it even clearer.
using namespace std;
#include<iostream>
main()
{
cout<<3+5-5*2/2;
cout<<endl;
cout<<9+3+2*4/2+3;
cout<<endl;
cout<<(9+3+2)*4/2+3;
cout<<"\n";
system("pause");
}

The code is simple and straight forward; anyhow let’s do a little discussion about it.
using namespace std;
#include<iostream>
main()
{
cout<<3+5-5*2/2;            // Displays result of expression 3+5-5*2/2 which is 3, C++ and other programming languages follow the natural order of precedence in arithmetic operations. The word PEMDAS (Parenthesis, Exponentiation, Multiplication, Division, Addition, Subtraction) can remind the natural order of precedence. 

cout<<endl;                       // Move the cursor to next line.
cout<<9+3+2*4/2+3;      // Displays result of the expression 9+3+2*4/2+3 which is 19.     
cout<<endl;                       // Mover the cursor to next line.
cout<<(9+3+2)*4/2+3;  // Displays the result of expression (9+3+2)*4/2+3 in which (9+3+2) is evaluated first because of parenthesis.   
cout<<"\n";
system("pause");
}

Code & Output:


Constant Variables

A constant variable is a variable which is initialized at time of declaration and once the value has assigned, it does not change for life time of the program. It is a good programming practice to use constant where the value of variable does not need to change. The keyword const is used to declare a variable as constant. We must assign a value to constant variable at time of declaration, otherwise later the complier will not let us to change the value of the constant. Let’s write a program which calculates the average of given numbers.
using namespace std;
#include<iostream>
main()
{
int num1, num2,num3,num4,sum;
const int totalnum=4;
double average;
num1=50;
num2=52;
num3=55;
num4=54;
sum=num1+num2+num3+num4;
average=sum/totalnum;
cout<<average;
cout<<"\n";
system("pause");
}

Let’s discuss how this code works to find out average.
using namespace std;
#include<iostream>
main()
{
int num1, num2,num3,num4,sum;           // Declares five variables 
const int totalnum=4;                                     // Declares a constant int variable totalnum and initializes it with literal 4. Remember that value of a const variable can’t be change once it is initialized.
double average;                                               // Declares double variable average
num1=50;                                                            // Assigns 50 to num1 variable
num2=52;                                                            // Assigns 52 to num2 variable
num3=55;                                                            // Assigns 55 to num3 variable
num4=54;                                                            // Assigns 54 to num4 variable
sum=num1+num2+num3+num4;             // Assigns the sum of num1+num2+num3+num4 to sum variable
average=sum/totalnum;                              // Calculates the average i.e. dividing sum by totalnum;
cout<<average;                                                                // Displays the average on the screen
cout<<"\n";
system("pause");
}

Code & Output:

Doing Math in C++

There is a cmath library which provides us with advance mathematical functions such as pow() function used for power. In similar way, the Sqrt() function returns the square root of a number. To use these mathematical functions, we have to include cmath library using #include<cmath>.   
using namespace std;
#include<iostream>
#include<cmath>
main()
{
int x=45;
double y=5;
cout<<"The power of 5 : " <<pow(y,2)<<endl;
cout<<"The square root of 25 : " <<sqrt(25)<<endl;
cout<<"The absoluate value of -133 : " <<abs(-133)<<endl;;
cout<<"The sin of x (45) : " <<sin(x)<<endl;
cout<<"The tan of x (45) : " <<tan(x)<<endl;
system("pause");
}
Here is the discussion of the code line by line.
using namespace std;
#include<iostream>
#include<cmath>             // Includes c standard math library i.e. cmath
main()
{
int x=45;                               // declares and initializes x variable

double y=5;                        // declares and initializes y variable

cout<<"The power of 5 : " <<pow(y,2)<<endl;   // pow() function calculates the power of y variable, which takes two arguments, first argument y as base and second argument as power. In our case y is base and 2 is power.

cout<<"The square root of 25 : " <<sqrt(25)<<endl;         // sqrt() function calculates the square root of the number 25
cout<<"The absoluate value of -133 : " <<abs(-133)<<endl;          // abs()  function calculates the absolute value for passing value.
cout<<"The sin of x (45) : " <<sin(x)<<endl;         // sin() function calculates the sin value of passing  value
                                                                                               
cout<<"The tan of x (45) : " <<tan(x)<<endl;       // tan() function calculates the tan value of passing  value           
system("pause");
}

Code & Output: 



Lesson # 3 Working with cout and cin

Lesson # 3

WORKING WITH COUT AND CIN
cout is a function from iostream (input output stream) used to display something on the screen, we always put << sign after cout function, which indicates output. We use Special Characters with cout, in order to enhanced its functionality.

Endl
Writes new line move the cursor to next line. e.g. cout<<endl;

\n
Writes a new line or move the cursor to next line, and \n can be used within a string e.g. cout<< “hello \n world”;

\t
Inserts five spaces, just like tab key on keyboard e.g. cout<< “Hello\tworld”;

Let’s make it clear with an example
C ++
Explanation
using namespace std;
#include<iostream>
main()
{

cout<<"Hello World";
Displays the whole string on the screen
cout<<endl;
Inserts a new line. endl is a special command used in c++.

cout<<"My name is...";
Display the whole string on the screen
cout<<"\nHello World\nMy name is ...";
 \n at the beginning of the string  (i.e. \nHello World) inserts a new line before the string.
 \n in the middle of the strings (i.e.  Word\nMy) inserts a new line between Hello world and My name is …”.
Mind it, \n is a special character from C programming language.

cout<<"\nHello World\tMy name is ...";
\n at the beginning of the string  (i.e. \nHello World) inserts a new line before the string.
 \t in the middle of the strings (i.e.  Word\tMy) inserts a five spaces between Hello world and My name is …”.

cout<<"\n";
Insert a new line.
Remember you can use these special characters many times in a single string such as  cout<< “\t \t My name is…”
system("pause");
}


Output
Hello World
My name is...
Hello World
My name is ...
Hello World     My name is ...
Press any key to continue . . .

CODE IN ACTION 



PROBLEMS WITH COUT
The problem with cout is that it can display four digits precision for example cout<<545.645444 will be displayed as 545.654 in the output. To tackle this problem. we use setprecision function from iomanip library. First we have include the library using #include(iomanip). Here is an example how to do it.

C ++
Explanation
using namespace std;

#include<iostream>

#include<iomanip>
Includes the iomanip (input output manipulation) library
main()

{

double x=545.645444;
Declares and initialize a double variable with value of  545.645444
cout<<x;
Displays the variable with default digits precision
cout<<endl;

cout<<setprecision(10);
Sets precision as 10 digits by calling setprecision methods.
cout<<x;
displays the variable x with defined precision i.e. setprecision(10)
cout<<"\n";

system("pause");

}

Output
545.645
545.645444
Press any key to continue . . .

CODE IN ACTION


cin is also a function from header file iostream and is used to get data (input) from the keyboard. We always put >> sign after cin function, which indicates input to be enter from keyboard.
C ++
Explanation
using namespace std;
#include<iostream>
main()
{

int y;
declares  an integer variable y
cin>>y;
gets input from keyboard and store it in y variable
cout<<y;
displays  y variable on the screen.
cout<<"\n";

system("pause");

}

Output
88
88
Press any key to continue . . .
  
CODE IN ACTION
 



PROBLEMS WITH CIN
We can also use cin for strings but it can work only with a single variable with no spaces. For example, while entering from keyboard if we type Hello world, it will store only Hello and will ignore world because cin works with a string without spaces. C++ provides a better way to handle this problem, getline function can enforce cin to get string with spaces between. Here is an example how to do it.

C ++
Explanation
using namespace std;

#include<iostream>

main()

{

string fullname;
declares a string variable fullname
getline(cin,fullname);
enforces cin to get string with spaces, two parameters are passed to getline function; cin and the name of the string i.e. fullname.
cout<<fullname;
displays fullname string on the screen
cout<<"\n";

system("pause");

}

Output
Amir Saleem
Amir Saleem
Press any key to continue . . .

CODE IN ACTION
 CODE 


Comments: Note the input string from keyboard which is Amir Saleem but cout dispalys Amir only , it is because of cin stores only amir as single string.

C++ provides a better way to handle this problem, getline function can enforce cin to get string with spaces between. Here is an example how to do it.
 using namespace std;
#include<iostream>
main()
{
string fullname;
getline(cin,fullname);
cout<<fullname;
cout<<"\n";
system("pause");
}

Let’s do a little discussion on code.
using namespace std;
#include<iostream>
main()
{
string fullname;                                //declares a string variable fullname
getline(cin,fullname);    // enforces cin to get string with spaces, two parameters are passed to getline function; cin and the name of the string i.e. fullname.
cout<<fullname;              // displays fullname string on the screen
cout<<"\n";
system("pause");
}

 Code & output:


Lesson # 2 Variable and data types

LESSON  # 2

VARIABLE AND DATA TYPES
Variables and data types are building blocks of C++. A variable is a container which stores different data types. Data types determine that what kind of data (value) can be stored in a variable. There are several data types in C++  such as:
Numeric (5585, 953.52) can be an integer, unsigned integer, double or  float.

INTEGER
An integer is whole number without decimal point e.g. 5585. In C++ keyword int is used to declare an integer. An integer can hold a number that contains 4 bytes i.e. -2000000000  to + 2000000000. For storing 8 bytes number we use unsigned int but unsigned int only store positive numbers. 

DOUBLE
Double holds a number with decimal point e.g. 953.52. It can store a number with 8 bytes.  Keyword double is used to declare a double. We can also use float which only takes a number of 4 bytes. In C++, to check size of a data type, we use sizeof(data type) function. For example, cout<<sizeof(int) returns the size of int.

STRING
String is zero or more characters enclosed in double quotes. For example “Hello world” is string because it has been enclosed in double quotes “ ”. Keyword string is used to declare a string.            

CHARACTER
Character is single letter enclosed in single quotes e.g ‘d’ is a character. To declare a character, the keyword  char is used.   ( single letter e.g. ‘d’ , ‘y’) . Remember that these values are stored as numbers which based on ASCII code.

BOOLEAN
Boolean holds true or false and is declared with keyword bool.

RULES FOR NAMING VARIABLES:
Must begin with a letter
May consist of letters, numbers, letter and underscore
No space between
            Good example:
             Name, last_name; a2z
            Bad example:  
            first name; 4family

Let illustrate these ideas with help of an example:
C++ Code
Explanation
using namespace std;
#include<iostream>
main()
{ 

int a;
Declaring an integer variable with name a
a=5585;
Assigning (storing) the data 5585 into variable a
double b;
Declaring a double variable with name b
b=953.52;
Assigning (storing) the data 953.52 in into variable b
string c;
Declaring a string variable with name c
c="Hello world";

Assigning (storing) the text data hello world in into variable c
char d;
Declaring a char variable with name d
d='d';
Assigning (storing) the data d in into variable d

cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\n";     

Displays all variables on the screen, note we are putting all variable together by inserting << after each variable and a tab \t character after variable. At end \n is for next line. 
system("pause");
}

Output
5585    953.52  Hello world     d
Press any key to continue . . .

CODE IN ACTION 

Let’s do one more example:
C++ Code
Explanation
using namespace std;
#include<iostream>
main()
{

int x,y,z;
Declaring three int variables i.e. x,y,z. Remember
we can declare variables in a single line, in this case
all these three variables are of type int.
x=10;
Assigning value
y=15;
Assigning value
z=x+y;
Assigns the values of another two variables. Variable z holds the sum of x and y.
cout<<z;
Displays z on the screen
cout<<y-x;
Displays the result of y – z, note that we can also do simple arithmetic operations with variables. 
cout<<"\n";
Moves the cursor to next line
double a=5.5,b=4.5,c=a*b;
Declaration and initialization (assigning values ) at the same time, it does not matter as far as we are dealing with a single data type.
cout<<c;
Displays c on the screen
cout<<"\n";

cout<<sizeof(int);
sizeof() functions returns the size of int
cout<<"\n";

system("pause");
}

Output
255
24.75
5345.654
Press any key to continue . . .


CODE IN ACTION