C++

C++ Complete Language!

Full course with source code examples.

 

 

 

C++

 

Pronounced as C Plus Plus, it is a general purpose object oriented programming language with low level memory manipulation feature.
C++ is a powerful resource and has found extensive application and use in various sectors ranging from the financial sector, to the business of manufacturing, to the banking sector, and many such more.It is for this reason that C++ has been in existence for a long time and has found its use even in mobile app development.
C++ has been doing quite well in the mobile app development arena as it is does wonders in helping develop cross-platform mobile apps easily with its unified debugging experience and a powerful environment.

The language is good for developing apps for Android, Windows, and iOS. C++ has potential well beyond mobile apps and can be used to create some of the strongest tools like Photoshop, Google Chrome. PayPal, Amazon and more.

C++ can be used to develop operating systems, new programming language, graphics & designs, game development, app development, web browsers, development of compilers of programming languages, medical, mathematical & engineering applications, enterprise tools, and computation platforms.

Contents are as:

    • Types & Expressions.
    • Control Flow.

Switch Statements
Loops
Functions
Exceptions

    • Arrays.

One-Dimensional Arrays
2-Dimensional Arrays
C-Strings(Character Arrays)
Sorting Arrays
Array Operations(Read, Insert, Erase, Reverse, Average, Length )

  • Pointers, References and Dynamic Allocation.
  • Structs.
  • Object Oriented Programming with Classes.
  • Containers, Iterators and Algorithms.

Variable Types

    • Integers (int, short, long)
    • Floating Points (float, double)
    • Characters (Alphabets i.e Names)
    • Bool (True or False)
    • Enums (Collection of Objects.)

 

Expressions

Parentheses () have two main uses:
1. Grouping to control order of evaluation, or for clarity.
eg, (a + b) * (c – d)
2. After a function name to enclose parameters. Eg, x = sum(a, b);

Operator Precedence Higher precedence are done before lower precedence as:
Unary operators
* / %
+ –
comparisons
&& ||
= assignments

Arithmetic Operators
The result of arithmetic operators is double if either operand is double, else float if either operand is float, else long if either operand is long, else int.
n + m Addition. Eg 7+5 is 12, 3 + 0.14 is 3.14
n – m Subtraction
n * m Multiplication. Eg 3 * 6 is 18
n / m Division. Eg 3.0 / 2 is 1.5 , 3 / 2 is 1
n % m Remainder (Mod) after dividing n by m. Eg 7 % 3 is 1
++i Add 1 to i before using the value.
–i As above for subtraction
i++ Add 1 to i after using the value.
i– As above for subtraction
Comparison Operators
The result of all comparisons is 0 (false) or non-zero (true).
< :less than
<= : less than or equal to
== : equal to
!= :not equal to
> :greater than
>= :greater than or equal to
Logical Operators
Logical values are zero (false) and non-zero (true).
b && c Conditional “and”. true if both operands are true, otherwise false. Short circuit evaluation. Eg (false && anything) is false.
b || c Conditional “or”. true if either operand is true, otherwise false. Short circuit evaluation. Eg (true || anything) is true.
!b true if b is false, false if b is true.

I/O Operators
There are two operators defined in .
cout << x Output “insertion” operator.
cin >> x Input “extraction” operator.

If-Else Statements!

C++ has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Code example:

1
2
3
4
5
6
7
8
int time = 22;
if (time < 10) {
  cout << "Good morning.";
} else if (time < 20) {
  cout << "Good day.";
} else {
  cout << "Good evening.";
}

Switch Case

The switch statement chooses statements to execute depending on an integer value.
The same effect can be achieved with a series of cascading if statements,
but in some cases the switch statement is easier to read, and some compilers will produce more efficient code.
The break statement exits from the switch statement. If there is no break at the end of a case, execution continues in the next case, which is usually an error.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
switch (expr) {
  case c1:
        statements  // do these if expr == c1
        break;
        
  case c2: 
        statements  // do these if expr == c2
        break;
        
  case c2:  // multiple values can share same statements
  case c3:
  case c4:
        statements  // do these if expr == any of c2, c3, or c4
        break;
        
  default:
        statements  // do these if expr != any above
}

Write a program to perform arithmetic calculations of two numbers?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int  left, right;   // Operands
    char oper;          // Operator
    int  result;        // Resulting value
    
    while (cin >> left >> oper >> right) {
        switch (oper) {
            case '+': result = left + right; 
                      break;
            case '-': result = left - right; 
                      break;
            case '*': result = left * right; 
                      break;
            case '/': result = left / right; 
                      break;
            default : cout << "Bad operator '" << oper << "'" << endl;
                      continue;  // Start next loop iteration.
        }
        cout << result << endl << endl;
    }

    return 0;
}

LOOPS

A loop is used for executing a block of statements repeatedly until a particular condition is satisfied.
For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration.

In C++ we have three types of basic loops: FOR loop, WHILE loop and DO-WHILE loop.
While loop is a most basic loop in C++. while loop has one control condition, and executes as long the condition is true.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;
 
int main ()
{
   /* local variable Initialization */   int n = 1,times=5;

   /* while loops execution */   while( n <= times )
   {
      cout << "C++ while loops: " << n <<endl;
      n++;
   }
   return 0;
}

Do-While loop is a variant of the while loop with one important difference.
The body of do-while loop is executed once before the test expression is checked.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main() 
{
    float number, sum = 0.0;
    
    do {
        cout<<"Enter a number: ";
        cin>>number;
        sum += number;
    }
    while(number != 0.0);
    cout<<"Total sum = "<<sum;
    
    return 0;
}

For loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Live Demo
#include <iostream>
using namespace std;
 
int main () {
   // for loop execution
   for( int a = 10; a < 20; a = a + 1 ) {
      cout << "value of a: " << a << endl;
   }
 
   return 0;
}

Programming implementation of Loops!
Write a program to calculate the factorial of given number?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;
void fac(int a)
 {
	int factorial=1;

	for ( int i=1;i<=a;i++)
	{
		factorial=factorial*a;
	}
	cout<<"Factorial of Given Number is ="<<factorial<<endl;

}
int main()
{
	int num;
		cout<<" Enter Number To Find Its Factorial:  ";
	cin>>num;
	fac(num);
}

Write a program to draw a pyramid of numbers?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;
int main()
{
    int rows, count = 0, count1 = 0, k = 0;
    cout << "Enter number of rows: ";
    cin >> rows;
    for(int i = 1; i <= rows; ++i)
    {
        for(int space = 1; space <= rows-i; ++space)
        {
            cout << "  ";
            ++count;
        }
        while(k != 2*i-1)
        {
            if (count <= rows-1)
            {
                cout << i+k << " ";
                ++count;
            }
            else
            {
                ++count1;
                cout << i+k-2*count1 << " ";
            }
            ++k;
        }
        count1 = count = k = 0;
        cout << endl;
    }
    return 0;
}

Output:

1
2
3
4
5
  1
      2 3 2
    3 4 5 4 3
  4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

Functions

Write code once, and call it from many places. This insures consistency, and reduces the cost of writing and debugging.
A function allows code to be parameterized by passing values to it.
Functions can be collected in libraries and reused in other programs.
Functions create new conceptual units that form the units that programmers use in thinking about a problem.
The first line of a function definition (called the function header) is the same at a prototype, except that it is followed by the function body in braces.
Neither the header nor the body is followed by a semicolon.
the function Structure is as:

1
2
3
4
5
6
7
void printChars(char c, int count) 
{
   for (int i=0; i<count; i++)
 {
     cout << c;
   }
}//end printChars

Example:
A function to identify the “even” numbers!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;
//--------------------------------- prototypes
int even(int a);
int odd(int b);
int ulam(int c);

//--------------------------------- main
int main() {
    // What does each statement print?
    cout << odd(4)              << endl;
    cout << (even(2) + odd(3))  << endl; // (Note 1)
    cout << ulam(ulam(ulam(5))) << endl; // (Note 2)
}
 

//---------------------------------- even
int even(int a) {
    cout << "even(" << a << ")" << endl;
    return a/2;
}

//---------------------------------- odd
int odd(int b) {
    cout << "odd(" << b << ")" << endl;
    return 3*b + 1;
}

//---------------------------------- ulam
int ulam(int c) {  
    cout << "ulam(" << c << ")" << endl;
    if (c%2 == 0) {
       return even(c);
    }else{
       return odd(c);
    }
} printChars

Exceptions

Exceptions allow passing information about some exception condition (usually an error) by means of the throw statement to the catch clause that encloses it or any of the calls on the call stack.
The beauty of this solution is that calls look identical, and the error processing code is in the function that wants to catch it.
The following program illustrates exception handling.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

//================================================ prototypes
void generateException(int whichException);

//====================================================== main
int main() {
    for (int i=1; ; i++) {  // Loop forever
        try {
            cout << i;
            generateException(i);
        } catch (out_of_range orex) {
            cout << "    Catching: out_of_range "<< orex.what() << endl;
        } catch (const char* mess) {
            cout << "    Catching: const char* " << mess << endl;
        } catch (string smess) {
            cout << "    Catching: string " << smess << endl;
        } catch (int iex) {
            cout << "    Catching: int " << iex << endl;
        } catch (runtime_error rex) {
            cout << "    Catching: runtime_error " << rex.what() << endl;
        } catch (exception eex) {
            cout << "    Catching: " << eex.what() << endl;
        } catch (...) {
            cout << "    ERROR: Nobody caught this!" << endl;
        }
    }            

    system("PAUSE");   // Keep Dev-C++ window open
    return 0;
}

//========================================= generateException
void generateException(int whichException) {
    switch (whichException) {
        
    case 1:
        cout << "  Throwing out_of_range()" << endl;
        throw out_of_range("out_of_range meaningful comment");
        break;
        
    case 2:
        cout << "  Throwing exception()   // Can't specify comment" << endl;
        throw exception();  // Doesn't take comment text.
        break;
        
    case 3:
        cout << "  Throwing underflow_error  // caught by base class (runtime_error)" << endl;
        throw underflow_error("underflow_error");
        break;
        
    case 4:
        cout << "  Throwing runtime_error" << endl;
        throw runtime_error("a comment");
        break;
        
    case 5:
        cout << "  Throwing length_error   // caught be super-super-class (exception)" << endl;
        throw length_error("length_error");
        break;
        
    case 6:
        cout << "  Throwing int" << endl;
        throw 26;
        break;
        
    case 7:
        cout << "  Throwing const char*" << endl;
        throw "This is a const char*";
        break;
        
    case 8:
        cout << "  Throwing string" << endl;
        throw string("I'm a string");
        break;
        
    case 9:
        cout << "  Throwing float" << endl;
        throw 3.14159;
        break;
        
    default:
        cout << "  Throwing up" << endl;
        system("PAUSE");
        exit(0);
    }
    return;

}

Arrays

Search Results
Featured snippet from the web
Image result for arrays in c++
An array in C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.
They are used to store similar type of elements as in the data type must be the same for all elements.
Here is an array declaration and code to initialize it.

1
2
3
4
5
6
int a[5];  // Allocates memory for 5 ints.
. . .
a[0] = 1;
for (int i=1; i<5; i++) {
    a[i] = a[i-1] * 2;
}

One-Dimensional Arrays is like a box of elements of same type. You can alter any element by single dimension.

Example: Add all elements of an array!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {
    int a[1000];       // Declare an array of 1000 ints
    int n = 0;         // Number of values in a.

    while (cin >> a[n]) {
        n++;
    }

    int sum = 0;       // Start the total sum at 0.
    for (int i=0; i<n; i++) {
        sum = sum + a[i];  // Add the next element to the total
    }
    
    cout << sum << endl;
    
    return 0;
}

Example: Print all the array values last to first!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main() {
    //--- Declare array and number of elements in it.
    float a[100000];
    int n;   // Number of values currently in array.
   
    //--- Read numbers into an array
    n = 0;
    while (cin >> a[n]) {
        n++;
    }
   
    //--- Print array in reverse order
    for (int i=n-1; i>=0; i--) {
        cout << a[i] << endl;
    }
   
    return 0;
}

2D-Array Data that is in rows and columns is usually stored in 2-dimensional arrays.Passing over all elements of a two-dimensional array is usually done with two nested for loops.
Let’s see a simple example of multidimensional array in C++ which declares, initializes and traverse two dimensional arrays.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>  
using namespace std;  
int main()  
{  
  int test[3][3];  //declaration of 2D array   
    test[0][0]=5;  //initialization   
    test[0][1]=10;   
    test[1][1]=15;  
    test[1][2]=20;  
    test[2][0]=30;  
    test[2][2]=10;  
    //traversal    
    for(int i = 0; i < 3; ++i)  
    {  
        for(int j = 0; j < 3; ++j)  
        {  
            cout<< test[i][j]<<" ";  
        }  
        cout<<"\n"; //new line at each row   
    }  
    return 0;  
}

C-Strings A double-quoted string of characters is a common way to write an array of characters.
The string “Hello” represents and array of six (not 5) characters. The last character is the terminating zero code. Example:

1
2
3
char greeting[] = "Hello";
is the same as
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Sorting Arrays Arranging elements in some order is called sorting. Typically this is an operation applied to arrays or other index-able data structures.

        • Bubble Sort Bubble sort compares two values next to each other and exchanges them if necessary to put them in the correct order.
          There are many variations on bubble sort, but they all examine adjacent pairs.
          Example:

           1
           2
           3
           4
           5
           6
           7
           8
           9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          36
          37
          38
          #include<bits/stdc++.h>
          using namespace std;
          int main()
          {
              int n;
              cout<<"Enter number of element you want to store: ";
              cin>>n;
              int arr[n],i,j;
              cout<<"Enter array values:\n";
              //taking the array value 
              //from user
              for(i=0;i<n;i++)
              {
                  cin>>arr[i];
              }
              //Now we will sort the array
              for(i=0;i<n-1;i++)
              {
                  for(j=0;j<n-i-1;j++)
                  {
                      //checking if previous value is
                      //grater than next one or not
                      if(arr[j]>arr[j+1])
                      {
                          //temp will temporarly store
                          //the value of arr[j]
                          //then we will swap the values
                          int temp=arr[j];
                          arr[j]=arr[j+1];
                          arr[j+1]=temp;
                      }
                  }
              }
              cout<<"After Bubble sort the array is:\n";
              for(i=0;i<n;i++)
              cout<<arr[i]<<" ";
              return 0;
          }
          
        • Selection Sort Selection sort successively chooses the largest (or smallest) value remaining in the array.
          While the performance on the average may be no better than bubble sort, it does allow for a significant reduction in the number of swaps,
          which can have a good performance effect on cache memory usage.
          Example:

           1
           2
           3
           4
           5
           6
           7
           8
           9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          36
          37
          38
          39
          40
          41
          42
          43
          #include<iostream>  
          using namespace std;  
          int findSmallest (int[],int);  
          int main ()  
          {  
              int myarray[10] = {11,5,2,20,42,53,23,34,101,22};  
              int pos,temp,pass=0;  
              cout<<"\n Input list of elements to be Sorted\n";  
              for(int i=0;i<10;i++)  
              {  
                  cout<<myarray[i]<<"\t";  
              } 
              for(int i=0;i<10;i++)  
              {  
                  pos = findSmallest (myarray,i);  
                  temp = myarray[i];  
                  myarray[i]=myarray[pos];  
                  myarray[pos] = temp; 
                  pass++;
              }  
              cout<<"\n Sorted list of elements is\n";  
              for(int i=0;i<10;i++)  
              {  
                  cout<<myarray[i]<<"\t";  
              } 
              cout<<"\number of passes required to sort the array: "<<pass;
              return 0;  
          }  
          int findSmallest(int myarray[],int i)  
          {  
              int ele_small,position,j;  
              ele_small = myarray[i];  
              position = i;  
              for(j=i+1;j<10;j++)  
              {  
                  if(myarray[j]<ele_small)  
                  {  
                      ele_small = myarray[j];  
                      position=j;  
                  }  
              }  
              return position;  
          }
          

Searching Arrays

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include<conio.h>

using namespace std;

#define ARRAY_SIZE 5
 
int main()
{
    int numbers[ARRAY_SIZE], i ,search_key;

	cout<<"Simple C++ Example Program for Simple Searching In Array\n";

	// Read Input
    for (i = 0; i < ARRAY_SIZE; i++)
    {
		cout<<"Enter the Number : "<< (i+1) <<"  : ";
        cin>>numbers[i];
    }
    
    cout<<"Enter the key\n";
    cin>>search_key;
    
    /*  Simple Search with Position */
	for (i = 0; i < ARRAY_SIZE; i++)
    {
		if(numbers[i] == search_key)
		{
			cout<<"Search Element Found . Position Is :"<< (i+1) <<" \n";
			break;
		}
		if(i == ARRAY_SIZE - 1)
		{
			cout<<"Search Element is not in Array.\n";
		}
    }
 }

Pointers

Pointers are variables that contain memory addresses.
Pointers are declared to point to a particular datatype.
A “*” is written after the type to indicate that this is a pointer to that type. For example, a pointer to an int would be declared like this.

1
int* ip;  // declares ip to be a pointer to an int.

Example:

1
2
3
4
5
6
7
8
9
char* cp;     // declare pointer to char
char  c, d;   // declare char variables

cp  = &c;     // puts address of c into cp
c   = 'x';    // assigns 'x' to c
*cp = 'x';    // also assigns 'x' to c
d   = *cp;    // copies c's value to d
cp  = &d;     // puts address of d into cp
*cp = c;      // puts value of c into d

Programming example: Write a code to swap two variables?
Here is the classic swap function implemented in four different styles:
using references, using pointers, using templates with references, and using the Standard Template Library swap.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <algorithm>
using namespace std;

//====================================== prototypes
void swap_ref(int& a, int& b);
void swap_ptr(int* a, int* b);

//=========================================== swap_tpl
template <class T>void swap_tpl(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

//=========================================== main
int main() {
    int x = 1;
    int y = 2;
    
    //std::cout << "start   : x = " << x << ", y = " << y << std::endl;
    
    std::swap(x, y);
    cout << "swap    : x = " << x << ", y = " << y << std::endl;
    
    swap_ref(x, y);
    cout << "swap_ref: x = " << x << ", y = " << y << std::endl;
    
    swap_ptr(&x, &y);
    cout << "swap_ptr: x = " << x << ", y = " << y << std::endl;
    
    swap_tpl(x, y);
    cout << "swap_tpl: x = " << x << ", y = " << y << std::endl;
    
    system("PAUSE");
}

//=========================================== swap_ref
void swap_ref(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

//=========================================== swap_ptr
void swap_ptr(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

References

The main use of references is acting as function formal parameters to support pass-by-reference.
In an reference variable is passed into a function, the function works on the original copy (instead of a clone copy in pass-by-value).
Changes inside the function are reflected outside the function.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
 
int main() {
   int number = 88;          // Declare an int variable called number
   int & refNumber = number; // Declare a reference (alias) to the variable number
                             // Both refNumber and number refer to the same value
 
   cout << number << endl;    // Print value of variable number (88)
   cout << refNumber << endl; // Print value of reference (88)
 
   refNumber = 99;            // Re-assign a new value to refNumber
   cout << refNumber << endl;
   cout << number << endl;    // Value of number also changes (99)
 
   number = 55;               // Re-assign a new value to number
   cout << number << endl;
   cout << refNumber << endl; // Value of refNumber also changes (55)
}

Structs

Structure is a collection of variables of different data types under a single name.
It is similar to a class in that, both holds a collection of data of different data types.
The struct keyword defines a structure type followed by an identifier (name of the structure).

Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure.
For example:

1
2
3
4
5
6
struct Person
{
    char name[50];
    int age;
    float salary;
};

Programming Example:C++ Program to assign data to members of a structure variable and display it!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
struct Person
{
    char name[50];
    int age;
    float salary;
};
int main()
{
    Person p1;
    
    cout << "Enter Full name: ";
    cin.get(p1.name, 50);
    cout << "Enter age: ";
    cin >> p1.age;
    cout << "Enter salary: ";
    cin >> p1.salary;
    cout << "\n Displaying Information." << endl;
    cout << "Name: " << p1.name << endl;
    cout <<"Age: " << p1.age << endl;
    cout << "Salary: " << p1.salary;
    return 0;
}

Another Example: Source Code to Add Two Complex Numbers!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;
typedef struct complex
{
    float real;
    float imag;
} complexNumber;
complexNumber addComplexNumbers(complex, complex);
int main()
{
    complexNumber n1, n2, temporaryNumber;
    char signOfImag;
    cout << "For 1st complex number," << endl;
    cout << "Enter real and imaginary parts respectively:" << endl;
    cin >> n1.real >> n1.imag;
    cout << endl << "For 2nd complex number," << endl;
    cout << "Enter real and imaginary parts respectively:" << endl;
    cin >> n2.real >> n2.imag;
    signOfImag = (temporaryNumber.imag > 0) ? '+' : '-';
    temporaryNumber.imag = (temporaryNumber.imag > 0) ? temporaryNumber.imag : -temporaryNumber.imag; 
    temporaryNumber = addComplexNumbers(n1, n2);    
    cout << "Sum = "  << temporaryNumber.real << temporaryNumber.imag << "i";
    return 0;
}
complexNumber addComplexNumbers(complex n1,complex n2)
{
      complex temp;
      temp.real = n1.real+n2.real;
      temp.imag = n1.imag+n2.imag;
      return(temp);
}

Object Oriented Programming Using Classes

Object-oriented programming is about creating objects that contain both data and functions.
Classes and objects are the two main aspects of object-oriented programming.
As:
Class: Fruits.
Objects: Apple, Banana, Mango!

Another example:
Class: Car.
Objects: Engine, Tyre, Lights,Steer and Seats!
So, a class is a template for objects, and an object is an instance of a class.
Creating Classes & Objects!
To create a class, use the class keyword as:

1
2
3
4
5
class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
}

To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
  myObj.myNum = 15; 
  myObj.myString = "Some text";

  // Print attribute values
  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  return 0;
}

Class Methods Methods are functions that belongs to the class.
To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class.
This is done by specifying the name of the class, followed the scope resolution :: operator, followed by the name of the function!
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

class Car {
  public:
    int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {
  return maxSpeed;
}

int main() {
  Car myObj; // Create an object of Car
  cout << myObj.speed(200); // Call the method with an argument
  return 0;
}

Class Constructors in C++ is a special method that is automatically called when an object of a class is created.
To create a constructor, use the same name as the class, followed by parentheses ().
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  return 0;
}

Just like functions, constructors can also be defined outside the class.
First, declare the constructor inside the class, and then define it outside of the class by specifying the name of the class,
followed by the scope resolution :: operator, followed by the name of the constructor (which is the same as the class).
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class
Car::Car(string x, string y, int z) {
  brand = x;
  model = y;
  year = z;
}

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

Access Specifiers Access specifiers define how the members (attributes and methods) of a class can be accessed.
In C++, there are three access specifiers:

        • Public : members are accessible from outside the class.
        • Private : members cannot be accessed (or viewed) from outside the class.
        • Protected – members cannot be accessed from outside the class, however, they can be accessed in inherited classes.

In the following example, we demonstrate the differences between public and private members!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class MyClass {
  public:    // Public access specifier
    int x;   // Public attribute
  private:   // Private access specifier
    int y;   // Private attribute
};

int main() {
  MyClass myObj;
  myObj.x = 25;  // Allowed (public)
  myObj.y = 50;  // Not allowed (private)
  return 0;
}

If you try ‘Private’ member of the class it will generate an error!

Encapsulation The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users.
To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class).
If you want others to read or modify the value of a private member, you can provide public get and set methods.
Encapsulation ensures better control of your data, because you (or others) can change one part of the code without affecting other parts.
To access a private attribute, use public “get” and “set” methods!
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

class Employee {
  private:
    // Private attribute
    int salary;

  public:
    // Setter
    void setSalary(int s) {
      salary = s;
    }
    // Getter
    int getSalary() {
      return salary;
    }
};

int main() {
  Employee myObj;
  myObj.setSalary(50000);
  cout << myObj.getSalary();
  return 0;
}

Inheritance In C++, it is possible to inherit attributes and methods from one class to another.
We group the “inheritance concept” into two categories:

        • Derived class (child) : the class that inherits from another class.
        • Base class (parent) : the class being inherited from.

To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent)!
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Base class
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut! \n" ;
    }
};

// Derived class
class Car: public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model;
  return 0;
}

Multiple Inheritance A class can also be derived from more than one base class, using a comma-separated list!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Base class
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Another base class
class MyOtherClass {
  public:
    void myOtherFunction() {
      cout << "Some content in another class." ;
    }
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
  MyChildClass myObj;
  myObj.myFunction();
  myObj.myOtherFunction();
  return 0;
}

The third specifier,protected, is similar to private, but it can also be accessed in the inherited class!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Employee {
  protected: // Protected access specifier
    int salary;
};

// Derived class
class Programmer: public Employee {
  public:
    int bonus;
    void setSalary(int s) {
      salary = s;
    }
    int getSalary() {
      return salary;
    }
};

int main() {
  Programmer myObj;
  myObj.setSalary(50000);
  myObj.bonus = 15000;
  cout << "Salary: " << myObj.getSalary() << "\n";
  cout << "Bonus: " << myObj.bonus << "\n";
  return 0;
}

Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.
This allows us to perform a single action in different ways.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Base class
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
   }
};

// Derived class
class Dog : public Animal {
  public:
    void animalSound() {
    cout << "The dog says: bow wow \n" ;
  }
};

int main() {
  Animal myAnimal;
  Pig myPig;
  Dog myDog;

  myAnimal.animalSound();
  myPig.animalSound();
  myDog.animalSound();
  return 0;
}

Files Handling The fstream library allows us to work with files.
There are three objects included in the fstream library, which are used to create, write or read files!

        • Ofstream : Creates and writes to files.
        • Ifstream : Reads from files.
        • Fstream : A combination of ofstream and ifstream: creates, reads, and writes to files.

Create and write to a file : To create a file, use either the ofstream or fstream object, and specify the name of the file.
To write to the file, use the insertion operator (<<).
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
#include <fstream>
using namespace std;

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file
  MyFile << "Files can be tricky, but it is fun enough!";

  // Close the file
  MyFile.close();
}

Read a file : To read from a file, use either the ifstream or fstream object, and the name of the file.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Create a text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
  // Output the text from the file
  cout << myText;
}

// Close the file
MyReadFile.close();

Containers and Algorithms of Data Structures

The STL (Standard Template Library) provides a number of predefined containers (data structures),
most of which are generalize as templates to hold any type element.
Types:

        • Sequence Containers
          • Vectors
          • Deques
          • Lists
        • Associative Containers
          • Maps
          • Sets
        • Adapter Containers
          • Stacks
          • Queues

Vectors
C++ has a vector class within the std namespace.
A vector is similar to an array, in a sense where a series of elements are stored with the same variable name.
Unlike arrays, vectors are dynamically sized, which is a major advantage.
Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
vector<dataType> vectorName;

//if you want to provide a size
vector<dataType> vectorName(size);

//adding an item to a vector
vectorName.push_back(value);

//accessing an index of a vector
vectorName[index];

//changing a value at a certain index
vectorName[index] = value;

Deque is a data structure that is implemented on the double-ended queue.
It is related to queue as in queue insertion is done at the end, and deletion is done from the front.
Double-ended queues are individual queues in which insertion and deletion are possible at both ends.
Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <deque>

using namespace std;

void showdata(deque<int> deque1)
{
  deque<int>::iterator iterator_1;
  for (iterator_1 = deque1.begin(); iterator_1 != deque1.end(); ++iterator_1)
    cout << "\t" << *iterator_1;
  cout << "\n";
}

int main()
{
  deque<int> myqueue;
  myqueue.push_front(230); // getting data from front
  myqueue.push_front(240); // getting data from front
  myqueue.push_back(250);  // getting data from back
  myqueue.push_back(260);  // getting data from back
  cout << "Deque elements are: ";
  showdata(myqueue);

  return (0);
}

Lists are sequence containers that allow non-contiguous memory allocation.
As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick.
Normally, when we say a List, we talk about doubly linked list.
Below is the program to show the working of some functions of List:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream> 
#include <list> 
#include <iterator> 
using namespace std; 
  
//function for printing the elements in a list 
void showlist(list <int> g) 
{ 
    list <int> :: iterator it; 
    for(it = g.begin(); it != g.end(); ++it) 
        cout << '\t' << *it; 
    cout << '\n'; 
} 
  
int main() 
{ 
  
    list <int> gqlist1, gqlist2; 
  
  
    for (int i = 0; i < 10; ++i) 
    { 
        gqlist1.push_back(i * 2); 
        gqlist2.push_front(i * 3); 
    } 
    cout << "\n List 1 (gqlist1) is : "; 
    showlist(gqlist1); 
  
    cout << "\n List 2 (gqlist2) is : "; 
    showlist(gqlist2); 
  
    cout << "\n gqlist1.front() : " << gqlist1.front(); 
    cout << "\n gqlist1.back() : " << gqlist1.back(); 
  
    cout << "\n gqlist1.pop_front() : "; 
    gqlist1.pop_front(); 
    showlist(gqlist1); 
  
    cout << "\n gqlist2.pop_back() : "; 
    gqlist2.pop_back(); 
    showlist(gqlist2); 
  
    cout << "\n gqlist1.reverse() : "; 
    gqlist1.reverse(); 
    showlist(gqlist1); 
  
    cout << "\n gqlist2.sort(): "; 
    gqlist2.sort(); 
    showlist(gqlist2); 
  
    return 0; 
  
} 

Map is a sequence of (key, value) pair, where only single value is associated with each unique key.
It is often referred as associative array.
In map key values generally used to sort the elements.
Example in keys and Elements!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
brightness_4
#include <iostream> 
#include <iterator> 
#include <map> 
  
using namespace std; 
  
int main() 
{ 
  
    // empty map container 
    map<int, int> gquiz1; 
  
    // insert elements in random order 
    gquiz1.insert(pair<int, int>(1, 40)); 
    gquiz1.insert(pair<int, int>(2, 30)); 
    gquiz1.insert(pair<int, int>(3, 60)); 
    gquiz1.insert(pair<int, int>(4, 20)); 
    gquiz1.insert(pair<int, int>(5, 50)); 
    gquiz1.insert(pair<int, int>(6, 50)); 
    gquiz1.insert(pair<int, int>(7, 10)); 
  
    // printing map gquiz1 
    map<int, int>::iterator itr; 
    cout << "\n The map gquiz1 is : \n"; 
    cout << "\t KEY\t ELEMENT\n"; 
    for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { 
        cout << '\t' << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
    cout << endl; 
  
    // assigning the elements from gquiz1 to gquiz2 
    map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); 
  
    // print all elements of the map gquiz2 
    cout << "\n The map gquiz2 after"
         << " assign from gquiz1 is : \n"; 
    cout << "\t KEY\t ELEMENT\n"; 
    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 
        cout << '\t' << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
    cout << endl; 
  
    // remove all elements up to 
    // element with key=3 in gquiz2 
    cout << "\n gquiz2 after removal of"
            " elements less than key=3 : \n"; 
    cout << "\t KEY\t ELEMENT\n"; 
    gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); 
    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 
        cout << '\t' << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
  
    // remove all elements with key = 4 
    int num; 
    num = gquiz2.erase(4); 
    cout << "\n gquiz2.erase(4) : "; 
    cout << num << " removed \n"; 
    cout << "\t KEY\t ELEMENT\n"; 
    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 
        cout << '\t' << itr->first 
             << '\t' << itr->second << '\n'; 
    } 
  
    cout << endl; 
  
    // lower bound and upper bound for map gquiz1 key = 5 
    cout << "gquiz1.lower_bound(5) : "
         << "\t KEY = "; 
    cout << gquiz1.lower_bound(5)->first << '\t'; 
    cout << "\t ELEMENT = "
         << gquiz1.lower_bound(5)->second << endl; 
    cout << "gquiz1.upper_bound(5) : "
         << "\t KEY = "; 
    cout << gquiz1.upper_bound(5)->first << '\t'; 
    cout << "\t ELEMENT = "
         << gquiz1.upper_bound(5)->second << endl; 
  
    return 0; 
} 

Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it.
The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
Implementation :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream> 
#include <set> 
#include <iterator> 
  
using namespace std; 
  
int main() 
{ 
    // empty set container 
    set <int, greater <int> > gquiz1;         
  
    // insert elements in random order 
    gquiz1.insert(40); 
    gquiz1.insert(30); 
    gquiz1.insert(60); 
    gquiz1.insert(20); 
    gquiz1.insert(50); 
    gquiz1.insert(50); // only one 50 will be added to the set 
    gquiz1.insert(10); 
  
    // printing set gquiz1 
    set <int, greater <int> > :: iterator itr; 
    cout << "\n The set gquiz1 is : "; 
    for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) 
    { 
        cout << '\t' << *itr; 
    } 
    cout << endl; 
  
    // assigning the elements from gquiz1 to gquiz2 
    set <int> gquiz2(gquiz1.begin(), gquiz1.end()); 
  
    // print all elements of the set gquiz2 
    cout << "\n The set gquiz2 after assign from gquiz1 is : "; 
    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) 
    { 
        cout << '\t' << *itr; 
    } 
    cout << endl; 
  
    // remove all elements up to 30 in gquiz2 
    cout << "\n gquiz2 after removal of elements less than 30 : "; 
    gquiz2.erase(gquiz2.begin(), gquiz2.find(30)); 
    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) 
    { 
        cout << '\t' << *itr; 
    } 
  
    // remove element with value 50 in gquiz2 
    int num; 
    num = gquiz2.erase (50); 
    cout << "\n gquiz2.erase(50) : "; 
    cout << num << " removed \t" ; 
    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) 
    { 
        cout << '\t' << *itr; 
    } 
  
    cout << endl; 
  
    //lower bound and upper bound for set gquiz1 
    cout << "gquiz1.lower_bound(40) : "
         << *gquiz1.lower_bound(40) << endl; 
    cout << "gquiz1.upper_bound(40) : "
         << *gquiz1.upper_bound(40) << endl; 
  
    //lower bound and upper bound for set gquiz2 
    cout << "gquiz2.lower_bound(40) : "
         << *gquiz2.lower_bound(40) << endl; 
    cout << "gquiz2.upper_bound(40) : "
         << *gquiz2.upper_bound(40) << endl; 
  
    return 0; 
  
} 

Stack is a linear data structure which follows a particular order in which the operations are performed.
The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Implementing by arrays:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h> 
  
using namespace std; 
  
#define MAX 1000 
  
class Stack { 
    int top; 
  
public: 
    int a[MAX]; // Maximum size of Stack 
  
    Stack() { top = -1; } 
    bool push(int x); 
    int pop(); 
    int peek(); 
    bool isEmpty(); 
}; 
  
bool Stack::push(int x) 
{ 
    if (top >= (MAX - 1)) { 
        cout << "Stack Overflow"; 
        return false; 
    } 
    else { 
        a[++top] = x; 
        cout << x << " pushed into stack\n"; 
        return true; 
    } 
} 
  
int Stack::pop() 
{ 
    if (top < 0) { 
        cout << "Stack Underflow"; 
        return 0; 
    } 
    else { 
        int x = a[top--]; 
        return x; 
    } 
} 
int Stack::peek() 
{ 
    if (top < 0) { 
        cout << "Stack is Empty"; 
        return 0; 
    } 
    else { 
        int x = a[top]; 
        return x; 
    } 
} 
  
bool Stack::isEmpty() 
{ 
    return (top < 0); 
} 
  
// Driver program to test above functions 
int main() 
{ 
    class Stack s; 
    s.push(10); 
    s.push(20); 
    s.push(30); 
    cout << s.pop() << " Popped from stack\n"; 
  
    return 0; 
} 

Implementing by Link-list:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <bits/stdc++.h> 
using namespace std; 
  
// A structure to represent a stack 
class StackNode { 
public: 
    int data; 
    StackNode* next; 
}; 
  
StackNode* newNode(int data) 
{ 
    StackNode* stackNode = new StackNode(); 
    stackNode->data = data; 
    stackNode->next = NULL; 
    return stackNode; 
} 
  
int isEmpty(StackNode* root) 
{ 
    return !root; 
} 
  
void push(StackNode** root, int data) 
{ 
    StackNode* stackNode = newNode(data); 
    stackNode->next = *root; 
    *root = stackNode; 
    cout << data << " pushed to stack\n"; 
} 
  
int pop(StackNode** root) 
{ 
    if (isEmpty(*root)) 
        return INT_MIN; 
    StackNode* temp = *root; 
    *root = (*root)->next; 
    int popped = temp->data; 
    free(temp); 
  
    return popped; 
} 
  
int peek(StackNode* root) 
{ 
    if (isEmpty(root)) 
        return INT_MIN; 
    return root->data; 
} 
  
int main() 
{ 
    StackNode* root = NULL; 
  
    push(&root, 10); 
    push(&root, 20); 
    push(&root, 30); 
  
    cout << pop(&root) << " popped from stack\n"; 
  
    cout << "Top element is " << peek(root) << endl; 
  
    return 0; 
} 

Queues are a type of container adapters which operate in a first in first out (FIFO) type of arrangement.
Elements are inserted at the back (end) and are deleted from the front.
Implementing:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream> 
#include <queue> 
using namespace std; 
  
int main() 
{ 
    int c = 0; 
    // Empty Queue 
    queue<int> myqueue; 
    myqueue.push(5); 
    myqueue.push(13); 
    myqueue.push(0); 
    myqueue.push(9); 
    myqueue.push(4); 
    // queue becomes 5, 13, 0, 9, 4 
  
    // Counting number of elements in queue 
    while (!myqueue.empty()) { 
        myqueue.pop(); 
        c++; 
    } 
    cout << c; 
} 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Close
Back to top button
Close
Close