C++ Programming

Introduction to C++ : 

            C++ is a cross-platform language that can be used to create high-performance applications.  C++ was developed by Bjarne Stroustrup, as an extension to the C language. C++ gives programmers a high level of control over system resources and memory. C++ is one of the world's most popular programming languages. C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems. C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs. C++ is portable and can be used to develop applications that can be adapted to multiple platforms. C++ is fun and easy to learn!


Lets Know About C++ Basic syntax with a simple Program :

/* Comment Line */


#include<iostream>

using namespace std;

int main()

{

    cout<<"Hello World!";

   return 0;

}

Output:  Hello World!


1. Comments – You can see two types of comments in the above program

// This is a single line comment

/* This is a multiple line comment */

            Comments as the names suggests are just a text written by programmer during code development. Comment doesn’t affect your program logic in any way, you can write whatever you want in comments but it should be related to the code and have some meaning so that when someone else look into your code, the person should understand what you did in the code by just reading your comment.

2. #include<iostream> – This statements tells the compiler to include iostream file. This file contains pre defined input/output functions that we can use in our program.

3. using namespace std; – A namespace is like a region, where we have functions, variables etc and their scope is limited to that particular region. Here std is a namespace name, this tells the compiler to look into that particular region for all the variables, functions, etc. I will not discuss this in detail here as it may confuse you. I have covered this topic in a separate tutorial with examples. Just follow the tutorial in the given sequence and you would be fine.

4. int main() – As the name suggests this is the main function of our program and the execution of program begins with this function, the int here is the return type which indicates to the compiler that this function will return a integer value. That is the main reason we have a return 0 statement at the end of main function.

5. cout << “Hello World!”; – The cout object belongs to the iostream file and the purpose of this object is to display the content between double quotes as it is on the screen. This object can also display the value of variables on screen(don’t worry, we will see that in the coming tutorials).

6. return 0; – This statement returns value 0 from the main() function which indicates that the execution of main function is successful. The value 1 represents failed execution.


Variables in C++ :

            A variable is a name which is associated with a value that can be changed. For example when we write int n=200; here variable name is n which is associated with value 200, int is a data type that represents that this variable can hold integer values. 

Syntax of declaring a variable in C++

data_type variable1_name = value1, variable2_name = value2;


For example:

int num1=20, num2=100;

 or

int num1,num2;

num1=20;

num2=100;


Types of variables

             Any variable declared inside these curly braces have scope limited within these curly braces, if you declare a variable in main() function.

1. Global variable

2. Local variable


Global Variable

        A variable declared outside of any function (including main as well) is called global variable. Global variables have their scope throughout the program, they can be accessed anywhere in the program, in the main, in the user defined function, anywhere.

Global variable example :

Here we have a global variable myVar, that is declared outside of main. We have accessed the variable twice in the main() function without any issues.


#include <iostream>

using namespace std;

// This is a global variable

char myVar = 'A';

int main()

{

   cout <<"Value of myVar: "<< myVar<<endl;

   myVar='Z';

   cout <<"Value of myVar: "<< myVar;

   return 0;

}

Output:

Value of myVar: A

Value of myVar: Z


Local variable

            Local variables are declared inside the braces of any user defined function, main function, loops or any control statements(if, if-else etc) and have their scope limited inside those braces.


#include <iostream>

using namespace std;

// This is a global variable

char myVar = 'A';

char myFuncn() {

   // This is a local variable

   char myVar = 'B';

   return myVar;

}

int main()

{

   cout <<"Funcn call: "<< myFuncn()<<endl;

   cout <<"Value of myVar: "<< myVar<<endl;

   myVar='Z';

   cout <<"Funcn call: "<< myFuncn()<<endl;

   cout <<"Value of myVar: "<< myVar<<endl;

   return 0;

}

Output:


Funcn call: B

Value of myVar: A

Funcn call: B

Value of myVar: Z

        The value of myVar in the main function, it only changed the value of global variable myVar because local variable myVar scope is limited to the function myFuncn().


Data Types in C++ :

        Data types define the type of data a variable can hold, for example an integer variable can hold integer data, a character type variable can hold character data etc.

Built in data types

char: For characters. Size 1 byte.

char ch = 'A';

int: For integers. Size 2 bytes.

int num = 100;

float: For single precision floating point. Size 4 bytes.

float num = 123.78987;

double: For double precision floating point. Size 8 bytes.

double num = 10098.98899;

bool: For booleans, true or false.

bool b = true;

wchar_t: Wide Character. This should be avoided because its size is implementation defined and not reliable.


User-defined data types

We have three types of user-defined data types in C++

1. struct

2. union

3. enum


Derived data types in C++

We have three types of derived-defined data types in C++

1. Array

2. Function

3. Pointer


Operators in C++ :

        Operator represents an action. For example + is an operator that represents addition. An operator works on two or more operands and produce an output. For example 3+4+5 here + operator works on three operands and produce 12 as output.


Types of Operators in C++

1) Basic Arithmetic Operators

2) Assignment Operators

3) Auto-increment and Auto-decrement Operators

4) Logical Operators

5) Comparison (relational) operators

6) Bitwise Operators

7) Ternary Operator


1) Basic Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %

+ is for addition.

– is for subtraction.

* is for multiplication.

/ is for division.

% is for modulo.


Example of Arithmetic Operators

#include <iostream>

using namespace std;

int main(){

  int num1 = 240;

  int num2 = 40;

  cout<<"num1 + num2: "<<(num1 + num2)<<endl;

  cout<<"num1 - num2: "<<(num1 - num2)<<endl;

  cout<<"num1 * num2: "<<(num1 * num2)<<endl;

  cout<<"num1 / num2: "<<(num1 / num2)<<endl;

  cout<<"num1 % num2: "<<(num1 % num2)<<endl;

  return 0;

}

Output:


num1 + num2: 280

num1 - num2: 200

num1 * num2: 9600

num1 / num2: 6

num1 % num2: 0


2) Assignment Operators

Assignments operators in C++ are: =, +=, -=, *=, /=, %=


num2 = num1 would assign value of variable num1 to the variable.


num2+=num1 is equal to num2 = num2+num1


num2-=num1 is equal to num2 = num2-num1


num2*=num1 is equal to num2 = num2*num1


num2/=num1 is equal to num2 = num2/num1


num2%=num1 is equal to num2 = num2%num1


Example of Assignment Operators

#include <iostream>

using namespace std;

int main(){

 int num1 = 240;

 int num2 = 40;

 num2 = num1;

 cout<<"= Output: "<<num2<<endl;

 num2 += num1;

 cout<<"+= Output: "<<num2<<endl;

 num2 -= num1;

 cout<<"-= Output: "<<num2<<endl;

 num2 *= num1;      

 cout<<"*= Output: "<<num2<<endl;

 num2 /= num1;      

 cout<<"/= Output: "<<num2<<endl;

 num2 %= num1;      

 cout<<"%= Output: "<<num2<<endl;

 return 0;

}

Output:


= Output: 240

+= Output: 480

-= Output: 240

*= Output: 57600

/= Output: 240

%= Output: 0


3) Auto-increment and Auto-decrement Operators

++ and —

num++ is equivalent to num=num+1;


num–- is equivalent to num=num-1;


Example of Auto-increment and Auto-decrement Operators

#include <iostream>

using namespace std;

int main(){

  int num1 = 240;

  int num2 = 40;

  num1++; num2--;

  cout<<"num1++ is: "<<num1<<endl;

  cout<<"num2-- is: "<<num2;

  return 0;

}

Output:


num1++ is: 241

num2-- is: 39


4) Logical Operators

            Logical Operators are used with binary variables. They are mainly used in conditional statements and loops for evaluating a condition.


Logical operators in C++ are: &&, ||, !


Let’s say we have two boolean variables b1 and b2.


b1&&b2 will return true if both b1 and b2 are true else it would return false.


b1||b2 will return false if both b1 and b2 are false else it would return true.


!b1 would return the opposite of b1, that means it would be true if b1 is false and it would return false if b1 is true.


Example of Logical Operators

#include <iostream>

using namespace std;

int main(){

   bool b1 = true;

   bool b2 = false;

   cout<<"b1 && b2: "<<(b1&&b2)<<endl;

   cout<<"b1 || b2: "<<(b1||b2)<<endl;

   cout<<"!(b1 && b2): "<<!(b1&&b2);

   return 0;

}

Output:


b1 && b2: 0

b1 || b2: 1

!(b1 && b2): 1


5) Relational operators

We have six relational operators in C++: ==, !=, >, <, >=, <=


== returns true if both the left side and right side are equal


!= returns true if left side is not equal to the right side of operator.


> returns true if left side is greater than right.


< returns true if left side is less than right side.


>= returns true if left side is greater than or equal to right side.


<= returns true if left side is less than or equal to right side.


Example of Relational operators

#include <iostream>

using namespace std;

int main(){

   int num1 = 240;

   int num2 =40;

   if (num1==num2) {

      cout<<"num1 and num2 are equal"<<endl;

   }

   else{

      cout<<"num1 and num2 are not equal"<<endl;

   }

   if( num1 != num2 ){

      cout<<"num1 and num2 are not equal"<<endl;

   }

   else{ 

      cout<<"num1 and num2 are equal"<<endl;

   }

   if( num1 > num2 ){

      cout<<"num1 is greater than num2"<<endl;

   }

   else{

      cout<<"num1 is not greater than num2"<<endl;

   }

   if( num1 >= num2 ){ 

      cout<<"num1 is greater than or equal to num2"<<endl;

   }

   else{

      cout<<"num1 is less than num2"<<endl;

   }

   if( num1 < num2 ){

      cout<<"num1 is less than num2"<<endl;

   }

   else{

      cout<<"num1 is not less than num2"<<endl;

   }

   if( num1 <= num2){

      cout<<"num1 is less than or equal to num2"<<endl;

   }

   else{

      cout<<"num1 is greater than num2"<<endl;

   }

   return 0;

}

Output:


num1 and num2 are not equal

num1 and num2 are not equal

num1 is greater than num2

num1 is greater than or equal to num2

num1 is not less than num2

num1 is greater than num2


6) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>


num1 = 11; /* equal to 00001011*/

num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.

        num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the binary form of num1 and num2 only second last bits are matching.

        num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is 1, else it returns 0. In our case it would return 31 which is 00011111

        num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101

        ~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our example it would return -12 which is signed 8 bit equivalent to 11110100

        num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to 00101100

        num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010


Example of Bitwise Operators

#include <iostream>

using namespace std;

int main(){

   int num1 = 11;  /* 11 = 00001011 */

   int num2 = 22;  /* 22 = 00010110 */ 

   int result = 0;

   result = num1 & num2;

   cout<<"num1 & num2: "<<result<<endl;

   result = num1 | num2;

   cout<<"num1 | num2: "<<result<<endl;

   result = num1 ^ num2;

   cout<<"num1 ^ num2: "<<result<<endl;

   result = ~num1;

   cout<<"~num1: "<<result<<endl;

   result = num1 << 2;

   cout<<"num1 << 2: "<<result<<endl;

   result = num1 >> 2;

   cout<<"num1 >> 2: "<<result;

   return 0;

}

Output:


num1 & num2: 2

num1 | num2: 31

num1 ^ num2: 29

~num1: -12

num1 << 2: 44 num1 >> 2: 2


7) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.

Syntax:  variable num1 = (expression) ? value if true : value if false

        If the expression results true then the first value before the colon (:) is assigned to the variable num1 else the second value is assigned to the num1.


Example of Ternary Operator

#include <iostream>

using namespace std;

int main(){

  int num1, num2; num1 = 99;

  /* num1 is not equal to 10 that's why

   * the second value after colon is assigned

   * to the variable num2

   */

  num2 = (num1 == 10) ? 100: 200;

  cout<<"num2: "<<num2<<endl;

  /* num1 is equal to 99 that's why

   * the first value is assigned

   * to the variable num2

   */

  num2 = (num1 == 99) ? 100: 200;

  cout<<"num2: "<<num2;

  return 0;

}

Output:


num2: 200

num2: 100


Other Operators

There are few other operators in C++ such as Comma operator and sizeof operator. We will cover them in detail in a separate tutorial.


Operator Precedence in C++

This determines which operator needs to be evaluated first if an expression has more than one operator. Operator with higher precedence at the top and lower precedence at the bottom.


Unary Operators  ++ – – ! ~

Multiplicative * / %

Additive + –

Shift  << >> >>>

Relational > >= < <=

Equality == !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

 Ternary ?:

Assignment  = += -= *= /= %= > >= < <= &= ^= |=


For flow control - If, If-else, Switch, etc statements kindly refer to  my C Programming notes.


Functions in C++ :

        A function is block of code which is used to perform a particular task, for example let’s say you are writing a large C++ program and in that program you want to do a particular task several number of times, like displaying value from 1 to 10, in order to do that you have to write few lines of code and you need to repeat these lines every time you display values. Another way of doing this is that you write these lines inside a function and call that function every time you want to display values. This would make you code simple, readable and reusable.


Syntax of Function

return_type function_name (parameter_list)

{

   //C++ Statements

}

Let’s take a simple example to understand this concept.


A simple function example


#include <iostream>

using namespace std;

/* This function adds two integer values

 * and returns the result

 */int

sum(int num1, int num2){

   int num3 = num1+num2; return num3;

}


int main(){

   //Calling the function

   cout<<sum(1,99);

   return 0;

}

Output:


100



#include <iostream>

using namespace std;

//Function declaration

int sum(int,int);


//Main function

int main(){

   //Calling the function

   cout<<sum(1,99);

   return 0;

}

/* Function is defined after the main method 

 */

int sum(int num1, int num2){

   int num3 = num1+num2;

   return num3;

}


Function Declaration:  before using functions, we need to declare them 

syntax of function declaration:

return_type function_name(parameter_list);

        While providing parameter_list you can avoid the parameter names, just like I did in the above example. I have given int sum(int,int); instead of int sum(int num1,int num2);.

Function definition: Writing the full body of function is known as defining a function.

syntax of function definition: 

return_type function_name(parameter_list) {

    //Statements inside function

}

Calling function: We can call the function like this:


function_name(parameters);


Types of function


1) Built-in functions

2) User-defined functions


1) Built-in functions

Built-in functions are also known as library functions. We need not to declare and define these functions as they are already written in the C++ libraries such as iostream, cmath etc. We can directly call them when we need.


Example: C++ built-in function example

Here we are using built-in function pow(x,y) which is x to the power y. This function is declared in cmath header file so we have included the file in our program using #include directive.


#include <iostream>

#include <cmath>

using namespace std;

int main(){

    /* Calling the built-in function 

     * pow(x, y) which is x to the power y

     * We are directly calling this function

     */

    cout<<pow(2,5);

    return 0;

}


Output:


32


2) User-defined functions


#include <iostream>

#include <cmath>

using namespace std;

//Declaring the function sum

int sum(int,int);

int main(){

   int x, y;

   cout<<"enter first number: ";

   cin>> x;


   cout<<"enter second number: ";

   cin>>y;


   cout<<"Sum of these two :"<<sum(x,y);

   return 0;

}

//Defining the function sum

int sum(int a, int b) {

   int c = a+b;

   return c;

}

Output:


enter first number: 22

enter second number: 19

Sum of these two :41


Default Arguments in C++ Functions :

        The default arguments are used when you provide no arguments or only few arguments while calling a function. The default arguments are used during compilation of program. For example, lets say you have a user-defined function sum declared like this: int sum(int a=10, int b=20), now while calling this function you do not provide any arguments, simply called sum(); then in this case the result would be 30, compiler used the default values 10 and 20 declared in function signature. If you pass only one argument like this: sum(80) then the result would be 100, using the passed argument 80 as first value and 20 taken from the default argument.


Example: Default arguments in C++

#include <iostream>

using namespace std;

int sum(int a, int b=10, int c=20);


int main(){

   /* In this case a value is passed as

    * 1 and b and c values are taken from

    * default arguments.

    */

   cout<<sum(1)<<endl;


   /* In this case a value is passed as

    * 1 and b value as 2, value of c values is

    * taken from default arguments.

    */

   cout<<sum(1, 2)<<endl;


   /* In this case all the three values are

    * passed during function call, hence no

    * default arguments have been used.

    */

   cout<<sum(1, 2, 3)<<endl;

   return 0;

}

int sum(int a, int b, int c){

   int z;

   z = a+b+c;

   return z;

}

Output:


31

23

6


Rules of default arguments

         default values for only two arguments b and c during function declaration. It is up to you to assign default values to all arguments or only selected arguments but remember the following rule while assigning default values to only some of the arguments:

         assign default value to an argument, the subsequent arguments must have default values assigned to them, else you will get compilation error.


Valid: Following function declarations are valid –


int sum(int a=10, int b=20, int c=30);

int sum(int a, int b=20, int c=30);

int sum(int a, int b, int c=30);


Invalid: Following function declarations are invalid –


/* Since a has default value assigned, all the

 * arguments after a (in this case b and c) must have 

 * default values assigned

 */

int sum(int a=10, int b, int c=30);


/* Since b has default value assigned, all the

 * arguments after b (in this case c) must have 

 * default values assigned

 */

int sum(int a, int b=20, int c);


/* Since a has default value assigned, all the

 * arguments after a (in this case b and c) must have 

 * default values assigned, b has default value but

 * c doesn't have, thats why this is also invalid

 */

int sum(int a=10, int b=20, int c);


C++ Recursion :

        The process in which a function calls itself is known as recursion and the corresponding function is called the recursive function. The popular example to understand the recursion is factorial function.

Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = n.


C++ recursion example:

#include <iostream>

using namespace std;

//Factorial function

int f(int n){

     if (n <= 1)

        return 1;

   else 

       return n*f(n-1);

}

int main(){

   int num;

   cout<<"Enter a number: ";

   cin>>num;

   cout<<"Factorial of entered number: "<<f(num);

   return 0;

}

Output:


Enter a number: 5

Factorial of entered number: 120


a base condition in the recursive function. 

The condition is:  if (n <= 1)

        return 1;

            The purpose of recursion is to divide the problem into smaller problems till the base condition is reached. F

Direct recursion vs indirect recursion

Direct recursion: When function calls itself, it is called direct recursion, the example we have seen above is a direct recursion example.

Indirect recursion: When function calls another function and that function calls the calling function, then this is called indirect recursion. For example: function A calls function B and Function B calls function A.


Indirect Recursion Example in C++

#include <iostream>

using namespace std;

int fa(int);

int fb(int);

int fa(int n){

   if(n<=1)

      return 1;

   else

      return n*fb(n-1);

}

int fb(int n){

   if(n<=1)

      return 1;

   else

      return n*fa(n-1);

}

int main(){

   int num=5;

   cout<<fa(num);

   return 0;

}

Output: 120


Arrays in C++ :

        An array is a collection of similar items stored in contiguous memory locations. In programming, sometimes a simple variable is not enough to hold all the data. For example, lets say we want to store the marks of 500 students, having 500 different variables for this task is not feasible, we can define an array with size 500 that can hold the marks of all students.

Declaring an array in C++

Method 1:

int arr[5];

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;


Method 2:

int arr[] = {10, 20, 30, 40, 50};


Method 3:

int arr[5] = {10, 20, 30, 40, 50};


Accessing Array Elements

        Array index starts with 0, which means the first array element is at index 0, second is at index 1 and so on. We can use this information to display the array elements.

#include <iostream>

using namespace std;

int main(){

   int arr[] = {11, 22, 33, 44, 55};

   cout<<arr[0]<<endl;

   cout<<arr[1]<<endl;

   cout<<arr[2]<<endl;

   cout<<arr[3]<<endl;

   cout<<arr[4]<<endl;

   return 0;

}

Output:

11

22

33

44

55

        displaying all the elements of array like this is not recommended. When you want to access a particular array element then this is fine but if you want to display all the elements then you should use a loop like this:

#include <iostream>

using namespace std;

int main(){

   int arr[] = {11, 22, 33, 44, 55};

   int n=0;

  

   while(n<=4){

      cout<<arr[n]<<endl;

      n++;

   }

   return 0;

}


Multidimensional Arrays in C++ :

        Multidimensional arrays are also known as array of arrays. The data in multidimensional array is stored in a tabular form 


A two dimensional array:

int arr[2][3];

This array has total 2*3 = 6 elements.


A three dimensional array:

int arr[2][2][2];

This array has total 2*2*2 = 8 elements.


Two dimensional array - declare, initialize and access Two Dimensional Array elements

int myarray[2][3];


Initialization:

Method 1:

int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};


Method 2:

This way of initializing is preferred as you can visualize the rows and columns here.

int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};


Accessing array elements:

arr[0][0] – first element

arr[0][1] – second element

arr[0][2] – third element

arr[1][0] – fourth element

arr[1][1] – fifth element

arr[1][2] – sixth element


Example: Two dimensional array in C++

#include <iostream>

using namespace std;

int main(){

   int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};

   for(int i=0; i<2;i++){

      for(int j=0; j<3; j++){

        cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;

      }

   }

   return 0;

}

Output:

arr[0][0]: 11

arr[0][1]: 22

arr[0][2]: 33

arr[1][0]: 44

arr[1][1]: 55

arr[1][2]: 66


Three dimensional array

        Lets see how to declare, initialize and access Three Dimensional Array elements.


Declaring a three dimensional array:

int myarray[2][3][2];


Initialization:

We can initialize the array in many ways:

Method 1:

int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};


Method 2:

This way of initializing is preferred as you can visualize the rows and columns here.

int arr[2][3][2] = {

     { {1,-1}, {2, -2}, {3, -3}},

     { {4, -4}, {5, -5}, {6, -6}}

}


Three dimensional array example

#include <iostream>

using namespace std;

int main(){

   // initializing the array

   int arr[2][3][2] = {

      { {1,-1}, {2,-2}, {3,-3} },

      { {4,-4}, {5,-5}, {6,-6} }

   };

   // displaying array values 

   for (int x = 0; x < 2; x++) {

     for (int y = 0; y < 3; y++) {

       for (int z = 0; z < 2; z++) {

         cout<<arr[x][y][z]<<" ";

       }

     }

   }

   return 0;

}

Output:


1 -1 2 -2 3 -3 4 -4 5 -5 6 -6


Passing Array to Function in C++ :

        pass array as an argument to a function just like you pass variables as arguments. In order to pass array to the function you just need to mention the array name during function call like this:

function_name(array_name);

Example: Passing arrays to a function

        In this example, we are passing two arrays a & b to the function sum(). This function adds the corresponding elements of both the arrays and display them.

#include <iostream>

using namespace std;

/* This function adds the corresponding

 * elements of both the arrays and

 * displays it.

 */

void sum(int arr1[], int arr2[]){

   int temp[5];

   for(int i=0; i<5; i++){

      temp[i] = arr1[i]+arr2[i];

      cout<<temp[i]<<endl;

   }

}

int main(){

   int a[5] = {10, 20, 30, 40 ,50};

   int b[5] = {1, 2, 3, 4, 5};

   //Passing arrays to function

   sum(a, b);

   return 0;

}

Output:

11

22

33

44

55


Example 2: Passing multidimensional array to function

In this example we are passing a multidimensional array to the function square which displays the square of each element.

#include <iostream>

#include <cmath>

using namespace std;

/* This method prints the square of each

 * of the elements of multidimensional array

 */

void square(int arr[2][3]){

   int temp;

   for(int i=0; i<2; i++){

      for(int j=0; j<3; j++){

        temp = arr[i][j];

        cout<<pow(temp, 2)<<endl;

      }

   }

}

int main(){

   int arr[2][3] = { 

       {1, 2, 3},

       {4, 5, 6}

   };

   square(arr);

   return 0;

}

Output:

1

4

9

16

25

36


Strings in C++ :

            Strings are words that are made up of characters, hence they are known as sequence of characters. In C++ we have two ways to create and use strings: 

1) By creating char arrays and treat them as string 

2) By creating string object


1) Array of Characters – Also known as C Strings


Example 1:

A simple example where we have initialized the char array during declaration.

#include <iostream>

using namespace std;

int main(){

   char book[50] = "A Song of Ice and Fire";

   cout<<book;

   return 0;

}

Output:

A Song of Ice and Fire


Example 2: Getting user input as string

            This can be considered as inefficient method of reading user input, why? Because when we read the user input string using cin then only the first word of the string is stored in char array and rest get ignored. The cin function considers the space in the string as delimiter and ignore the part after it.


#include <iostream>

using namespace std;

int main(){

   char book[50];

   cout<<"Enter your favorite book name:";

   //reading user input

   cin>>book;

   cout<<"You entered: "<<book;

   return 0;

}

Output:

Enter your favorite book name: The Murder of Roger Ackroyd

You entered: The

You can see that only the “The” got captured in the book and remaining part after space got ignored. How to deal with this then? Well, for this we can use cin.get function, which reads the complete line entered by user.


Example 3: Correct way of capturing user input string using cin.get

#include <iostream>

using namespace std;

int main(){

   char book[50];

   cout<<"Enter your favorite book name:";

 

   //reading user input

   cin.get(book, 50);

   cout<<"You entered: "<<book;

   return 0;

}

Output:


Enter your favorite book name: The Murder of Roger Ackroyd

You entered: The Murder of Roger Ackroyd

Drawback of this method

1) Size of the char array is fixed, which means the size of the string created through it is fixed in size, more memory cannot be allocated to it during runtime. For example, lets say you have created an array of character with the size 10 and user enters the string of size 15 then the last five characters would be truncated from the string.

        On the other hand if you create a larger array to accommodate user input then the memory is wasted if the user input is small and array is much larger then what is needed.


2) In this method, you can only use the in-built functions created for array which don’t help much in string manipulation.


String object in C++

        Till now we have seen how to handle strings in C++ using char arrays. Lets see another and better way of handling strings in C++ – string objects.


#include<iostream>

using namespace std;

int main(){

   // This is how we create string object

   string str;

   cout<<"Enter a String:";

   /* This is used to get the user input

    * and store it into str

    */

   getline(cin,str);

   cout<<"You entered: ";

   cout<<str<<endl;


   /* This function adds a character at

    * the end of the string

    */ str.push_back('A');

   cout<<"The string after push_back: "<<str<<endl;

   /* This function deletes a character from

    * the end of the string

    */

   str.pop_back();

   cout << "The string after pop_back: "<<str<<endl;

   return 0;

}

Output:

Enter a String:XYZ

You entered: XYZ

The string after push_back: XYZA

The string after pop_back: XYZ


Pointers in C++ :

            Pointer is a variable in C++ that holds the address of another variable. They have data type just like variables, for example an integer type pointer can hold the address of an integer variable and an character type pointer can hold the address of char variable.


Syntax of pointer data_type *pointer_name;


/* This pointer p can hold the address of an integer 

 * variable, here p is a pointer and var is just a

 * simple integer variable

 */

int *p, var


Assignment

         an integer type pointer can hold the address of another int variable. Here we have an integer variable var and pointer p holds the address of var. To assign the address of variable to pointer we use ampersand symbol (&).


/* This is how you assign the address of another variable

 * to the pointer

 */

p = &var;

How to use it?


// This will print the address of variable var

cout<<&var;    


/* This will also print the address of variable

 * var because the pointer p holds the address of var

 */

cout<<p;    


/* This will print the value of var, This is 

 * important, this is how we access the value of

 * variable through pointer

*/

cout<<*p; 

Example of Pointer

Lets take a simple example to understand what we discussed above.


#include <iostream>

using namespace std;

int main(){

   //Pointer declaration

   int *p, var=101;

 

   //Assignment

   p = &var;


   cout<<"Address of var: "<<&var<<endl;

   cout<<"Address of var: "<<p<<endl;

   cout<<"Address of p: "<<&p<<endl;

   cout<<"Value of var: "<<*p;

   return 0;

}

Output:

Address of var: 0x7fff5dfffc0c

Address of var: 0x7fff5dfffc0c

Address of p: 0x7fff5dfffc10

Value of var: 101


Pointer and arrays

        While handling arrays with pointers you need to take care few things. First and very important point to note regarding arrays is that the array name alone represents the base address of array so while assigning the address of array to pointer don’t use ampersand sign(&). Do it like this:

Correct: Because arr represent the address of array.

p = arr;


Incorrect:  p = &arr;

Example: Traversing the array using Pointers

#include <iostream>

using namespace std;

int main(){

   //Pointer declaration

   int *p;

   //Array declaration

   int arr[]={1, 2, 3, 4, 5, 6};

   //Assignment

   p = arr;

   for(int i=0; i<6;i++){

     cout<<*p<<endl;

     //++ moves the pointer to next int position

     p++;

   }

   return 0;

}

Output:

1

2

3

4

5

6


increment pointer address and pointer’s value

            When we are accessing the value of a variable through pointer, sometimes we just need to increment or decrement the value of variable though it or we may need to move the pointer to next int position(just like we did above while working with arrays). The ++ operator is used for this purpose. One of the example of ++ operator we have seen above where we traversed the array using pointer by incrementing the pointer value using ++ operator. Lets see few more cases.


// Pointer moves to the next int position (as if it was an array)

p++; 

// Pointer moves to the next int position (as if it was an array)   

++p;   


/* All the following three cases are same they increment the value 

 * of variable that the pointer p points.

 */

++*p;   

++(*p); 

++*(p); 


 ‘this’ Pointer in c++ :

            The "this" pointer holds the address of current object, in simple words you can say that this pointer points to the current object of the class. Let’s take an example to understand this concept.


C++ Example: this pointer

Here you can see that we have two data members num and ch. In member function setMyValues() we have two local variables having same name as data members name. In such case if you want to assign the local variable value to the data members then you won’t be able to do until unless you use this pointer, because the compiler won’t know that you are referring to object’s data members unless you use this pointer. This is one of the example where you must use this pointer.


#include <iostream>

using namespace std;

class Demo {

private:

  int num;

  char ch;

public:

  void setMyValues(int num, char ch){

    this->num =num;

    this->ch=ch;

  }

  void displayMyValues(){

    cout<<num<<endl;

    cout<<ch;

  }

};

int main(){

  Demo obj;

  obj.setMyValues(100, 'A');

  obj.displayMyValues();

  return 0;

}

Output:


100

A

Example 2: function chaining calls using this pointer

            Another example of using this pointer is to return the reference of current object so that you can chain function calls, this way you can call all the functions for the current object in one go. Another important point to note in this program is that I have incremented the value of object’s num in the second function and you can see in the output that it actually incremented the value that we have set in the first function call. This shows that the chaining is sequential and the changes made to the object’s data members retains for further chaining calls.



#include <iostream>

using namespace std;

class Demo {

private:

  int num;

  char ch;

public:

  Demo &setNum(int num){

    this->num =num;

    return *this;

  }

  Demo &setCh(char ch){

    this->num++;

    this->ch =ch;

    return *this;

  }

  void displayMyValues(){

    cout<<num<<endl;

    cout<<ch;

  }

};

int main(){

  Demo obj;

  //Chaining calls

  obj.setNum(100).setCh('A');

  obj.displayMyValues();

  return 0;

}

Output:

101

A