-->




Learn Pointers in C++ Programming with Examples

Leave a Comment
This C++ Tutorial Covers

  • Pointers Syntax, declaration, initialization 
  • Pointers with address (&) and asterisk (*) operator
  • Errors may found while working with pointers
  • Basic example pointers C++ program
  • Relation of Asterisk and address operator

What is a Pointer in C++ Programming?
A pointer is a variable which stores or points to memory address of a variable. Pointer can access indirectly the value of a variable using its address. Both pointer and variable will be of same data type. 

Declaration of a Pointer
Like other variables pointer declares in the same way. First write the data type then its name with asterisk before pointer's variable name.
Declaration Syntax
int *ptr;
where ptr is a pointer of integer and will point to an integer address variable normally we read it from right to left as ptr is a pointer to an integer value
Its is recommend that while declaring a pointer use the short word _ptr after variable name which will increase the readability of program.

Initialization of a Pointer
Like other variables pointers can be initialize at the time of declaration or after it using assignment method.
It initialize with value 0 or NULL and corresponding data type.
For example
int *ptr, a=5; 
ptr=NULL; and ptr=0;   both have same meaning

A pointer which points to a NULL value called as a NULL Pointer.  The point to be noted here 0 is an interger value but pointer stores address only if we do int *ptr=7; or any other integer value then error occurred.  
Students should Remember that 0 is the only integer value by which  
Pointer with Unary Operator & 
To get the address the unary operator & known as address operator is used.
for example
int *ptr;
int x=5;
ptr=&x; //  assigns the address of variable x to pointer ptr
we said that ptr is a pointer pointing to memory address of variable x and indirectly pointer can access the value of variable x. 

Asterisk * Operator With Pointer
The * operator is usually know as de-refrence operator used to get the value of variable using pointer.
For Example
To get Value of a variable
int *ptr; // Don't confuse here it is pointer declaration 
 x=10;
ptr=&x;
cout<<ptr; // will print the address of x
cout<<*ptr; // will print the value of x = 10;

Using on left side
*ptr=15;
cout<<*ptr; //  now will print 15;
 now the memory address of x value has changed replaced by 15

To take input 
cin>> *ptr; // it will take input 
now the memory address of x value has changed by what value is entered

Relation between * and address operator &
Both operators cancel the each other value and the value of variable is provided as result.
For example
int *ptr, a=5;
ptr=&a;
Let address of a= 0X100; so ptr=0X100;
    cout<<*ptr<<endl;      // 5
    cout<<ptr;                    // 0X100
    cout<<*&ptr<<endl;   // 0X100
    cout<<&*ptr<<endl;   // 0X100

    cout<<*(&ptr)<<endl; // 0X100
    cout<<&(*ptr)<<endl; // 0X100

Errors while working with pointers 
  • De-referencing  a NULL Pointer is an error
           int   *nPtr=NULL;
    cout<<  *nPtr;  // Error
  • Assigning a pointer to different data type
    int n;  double *dPtr;
             dPtr=&n;  // error: cannot convert int to double
  •  Trying to de-refrence a non pointer variable
Pointers Example program which displays different ways to deal with pointers
Compiler Used CodeBlocks C++ Compiler

#include<iostream>
using namespace std;

int main()
{
    int *ptr; double a=222;
    int x=10;
    // ptr=&a; error
    ptr=&x;
    cout<<"Address of ptr =   "<<ptr<<"\n\n\n";
    cout<<"Defrefrecned to get Value of s  *ptr=   "        <<*ptr<<"\n\n\n";
    *ptr=50;

    cout<<"Changing value using *ptr=50 "<<"\n\n\n";
    cout<<"Now Defrefrecned to get Value of x  *ptr=   "<<*ptr<<"\n\n\n";

    int *nPtr=NULL;
    //error
    // cout<<*nPtr; 

    cout<<"NULL Pointer "<<&nPtr<<"\n\n\n";

    cout<<"Taking Input in pointer Using cin>> *ptr :  ";
    cin>>*ptr;

    cout<<"Input Value =  "<< *ptr<<"\n\n\n";
    return 0;
}

Output 
pointers in c++ programming


Recommendation: Copy the above code, edit it and examine the output of program. It will be very helpful for good learning.

See more Simple examples here of C++ programs
Read More...

c++ programs to find transpose of a matrix with function and without function

Leave a Comment
Write two C++ programs which asks user to enter number of rows and colums and calculate its transpose and display the result accordingly.
Note: One with function and one without Function
function prototype:
void calculate_transpose(int matrix[5][5], int rows, int cols);
    
First we have to clear about what is transpose of a matrix.
Its to replace the number of rows with number of colums and vice versa to make a new matrix.
for example
if a matrix 'A' has dimension 2X3  means 2 rows 3 colums then new transpose matrix 'T' will be 3X2

        1  2  3                     1    4    
A=   4  5  6              T=   2   5
                                       3   6

C++ Code:   Compiler Used:  CodeBlocks
Without Functioin



    #include<iostream>
    using namespace std;
    int main()
    {

    int matrix[5][5],transpose_matrix[5][5];
    int i,j,rows,cols;
    // Taking Input In Array

      cout<<"Enter Number of ROWS :";
      cin>>rows;

      cout<<"Enter Number Of COLS  :";
      cin>>cols;
       for( i=0;i<rows;i++){
           for( j=0;j<cols;j++)
           {
               cin>>matrix[i][j];
           }
          }

          cout<<"\n Matrix You Entered\n";

       for( i=0;i<rows;i++){
           for( j=0;j<cols;j++)
           {
               cout<<matrix[i][j]<<"     ";
           }
           cout<<endl;
          }



// Calculating Transpose of Matrix
    cout<<"\n\n\nTranspose of Entered Matrix\n";
       for( i=0;i<rows;i++){
           for( j=0;j<cols;j++)
           {
               transpose_matrix[j][i]=matrix[i][j];
           }
           cout<<endl;
          }


//Displaying Final Resultant Array
       for( i=0;i<cols;i++){
           for( j=0;j<rows;j++)
           {
               cout<<transpose_matrix[i][j]<<"    ";
           }
           cout<<endl;
          }

   return 0;
    }



Sample input Output
C++ program transpose example of a matrix




With Function C++ Code:

In this the same code is used but passing the 2D array to a function with size of rows and cols



    #include<iostream>
    using namespace std;

    void calculate_transpose(int matrix[5][5], int rows, int cols);
    int main()
    {

    int matrix[5][5];
    int i,j,rows,cols;
    // Taking Input In Array

      cout<<"Enter Number of ROWS :";
      cin>>rows;

      cout<<"Enter Number Of COLS  :";
      cin>>cols;
       for( i=0;i<rows;i++){
           for( j=0;j<cols;j++)
           {
               cin>>matrix[i][j];
           }
          }

          cout<<"\n Matrix You Entered\n";

       for( i=0;i<rows;i++){
           for( j=0;j<cols;j++)
           {
               cout<<matrix[i][j]<<"     ";
           }
           cout<<endl;
          }


//**********CALLING FUNCTION************//
      calculate_transpose(matrix,rows,cols);


   return 0;
    }

 void calculate_transpose(int matrix[5][5], int rows, int cols)
{    int i,j;
    int transpose_matrix[5][5];
    cout<<"\n\n\nTranspose of Entered Matrix\n";
       for(i=0;i<rows;i++){
           for( j=0;j<cols;j++)
           {
               transpose_matrix[j][i]=matrix[i][j];
           }
           cout<<endl;
          }

       for(i=0;i<cols;i++){
           for( j=0;j<rows;j++)
           {
               cout<<transpose_matrix[i][j]<<"   ";
           }
           cout<<endl;
          }

}



Find more examples here:


Read More...

Simple C++ program to convert binary decimal number

Leave a Comment
Cpp Tutorial Contains
  • Binary to Decimal Conversion Code in C++
  • Program Logic Explanation
  • Dry run the code with a simple input so the basic working of program can be understand easily
Concept Used
  • Know the basic math of converting one number to other number e.g BINARY to DECIMAL
  • functions 
  • while loop

Problem Statement
Write a C++ program which asks user to input a binary number then convert it into its equivalent decimal number and show the result. 
To improve readability of program make a separate function and function should return the resultant number.

C++ CODE
Compiler used: C++ codeBlocks Compiler

#include<iostream>
using namespace std;
long ConvertBinary2Decimal(unsigned long num);
int main()

{
    unsigned long binary_num, decimal = 0;
    cout <<"\n\tEnter a binary number to get 
    Equivalent Decimal : ";
    cin >> binary_num;
    decimal=ConvertBinary2Decimal(binary_num);
    cout <<"\n\tDecimal Value Of  
   " <<binary_num << " is = " << decimal << endl;
    return 0;

}

long ConvertBinary2Decimal(unsigned long bin_num)
{
    unsigned long decimal = 0;
    int remainder=0, base = 1;


    while (bin_num > 0)

    {
        remainder = bin_num % 10;
        decimal = decimal + remainder * base;
        bin_num = bin_num / 10;
        base = base * 2;
    }

return decimal;

}
Convert binary to decimal c++ code

Program Explanation
  • In main function user enters input number
  • Calls the function and pass the number 
  • Function calculates the required result and return
  • In main function program displays the final result

Dry Run of Code
Input = 101
--------------------------------
Iteration     = 1
 remainder  = 1
 decimal     = 1
 bin_num   = 10
 base          =  2
--------------------------------
Iteration     = 2
 remainder  = 0
 decimal     = 1
 bin_num   = 1
 base          =  4
--------------------------------
Iteration     = 3
 remainder  = 1 -> as 1 mod 10 =1
 decimal     = 5 -> previous value+remainder*base = 5 RESULT
 bin_num   =  0
 base          =  8
--------------------------------

Main logic of the program in while loop take another input and dry run it into a notebook. Best of Luck

See another example here
Read More...

C++ calculator code for beginner

Leave a Comment

Write a simple C++ program which have four different functions for basic operations like addition, subtraction, division and multiplication.
Program should be menu based asking user to enter option and if user enters a wrong option a proper message to enter right option should be displayed. 



Program explanation
  • Program has four different function for each calculator operation
  • do while loop is used to display menu options
  • if else statement is used to check option
  • Program has two variables on which all basic operations are applied 
  • Every functions receives two parameters and return result

    C++ source code compiler used Codeblocks


#include <iostream>
using namespace std;

int addition      (int num1, int num2);
int subtraction   (int num1, int num2);
int division      (int num1, int num2);
int multiplication(int num1, int num2);



int main()
{
    char option;
    int num1, num2, result;

    cout<<"\n\t\t\tSimple calculator"<<endl;
    do
    {

    cout<<"Enter + for Addtion\nEnter - for Subtraction\n
    Enter / for Division\nEnter * for Multiplication\n
    Enter E to EXIT\n";
    cout<<"\n\t\t\tEnter Option: ";
    cin>>option;

     if(option!='e'&&option!='E')
     {
     cout<<"\n\t\t\tEnter First Number: ";
     cin>>num1;
     cout<<"\n\t\t\tEnter Second Number: ";
     cin>>num2;
     }

    if(option!='+'&&option!='-'&&option!='/'
      &&option!='*'&&option!='e'&&option!='E')
    {
       cout<<"\n\t\t\tSELECT the VALID OPTION\n";
    }
    else if(option=='+')
    {
       result=addition(num1,num2);
       cout<<"\n\t\t\t"<<num1<<" + "<<num2<<" = "<<result<<endl;
    }
    else if(option=='-')
    {
       result=subtraction(num1,num2);
       cout<<"\n\t\t\t"<<num1<<" - "<<num2<<" = "<<result<<endl;
    }
    else if(option=='/')
    {
       result=division(num1,num2);
       cout<<"\n\t\t\t"<<num1<<" / "<<num2<<" = "<<result<<endl;

    }
    else if(option=='*')
    {
          result=multiplication(num1,num2);
       cout<<"\n\t\t\t"<<num1<<" X "<<num2<<" = "<<result<<endl;

    }



    }while(option!='e'&&option!='E');


 cout<<"\n\t\t\tProgram EXIT Successfully.......\n\t\t\t";
    return 0;
}
int addition(int num1, int num2)
{
    return (num1+num2);
}

int subtraction(int num1, int num2)
{

    return (num1-num2);
}

int division(int num1, int num2)
{
      if(num2==0)
      {
          cout<<"\n\t\t\tDivide by ZERO not allowed :"<<endl;
          return 0;
      }
    return (num1/num2);
}

int multiplication(int num1, int num2)
{
    return (num1*num2);
}


Program Output
simple calculator source code example

Find more examples here
C++ simple examples
Read More...