Blog

  • this Pointer in C++

    In C++, this is a keyword that refers to the current instance of a class and this pointer holds the address or points to the current object of the class. Also, only the member functions have this pointer.

    Members like friend functions do not have this pointer as they are not members of the class.

    Example of this pointer in C++

    Let us see an example of C++ this pointer that refers to the fields of the current class.

    #include <iostream>  
    using namespace std; 
    
    class Student 
    {  
       public:  
           int roll; //fields      
           string name;  
           float score;
           
           Student(int roll, string name, float score)    
           {    
               this->roll = roll;    
               this->name = name;    
               this->score = score;   
           }    
           void print()    
            {    
               cout << "Roll No: " << roll << endl;    
               cout << "Name: " << name << endl;    
               cout << "Score: " << score << endl << endl;    
            }    
    };  
    
    int main(void) 
    {  
        //creating Object
        Student s1 = Student(1101, "John", 80);  
        Student s2 = Student(1102, "Emma", 95); 
        
        s1.print();    
        s2.print();    
        
        return 0;  
    }  

    Output:

    Roll No: 1101
    Name: John
    Score: 80


    Roll No: 1102
    Name: Emma
    Score: 95


  • Inheritance in C++

    Inheritance is one of the most important concepts of object-oriented programming. In C++, inheritance is the process of deriving the properties and behaviors of one class to another class. It is like a child and parent where the child possesses the properties of the parent.

    • The class which inherits the members of another class is called the derived class (child/sub).
    • The class whose members are inherited is called the base class (super/parent).

    Importance of Inheritance:

    • For Code Reusability.
    • For Method Overriding (to achieve runtime polymorphism).

    A basic example of Inheritance.

    class Animal 
    {
        // eat() function
        // sleep() function
    };
    
    class Cat: public Animal 
    {
        // sound() function
    };

    As you can see in the above example Cat class inherits from the Animal class which means that the Cat class has can access the eat() and sleep() methods of Animal and also has its own additional method sound().

    Modes of Inheritance.

    It is the visibility mode that is used while deriving a parent class. such as:

    class derived_class_name : visibility-mode parent_class_name  
    {  
        // derived class members.  
    }  

    We can derive the parent class publicly or privately.

    Public mode: When the derive class publicly inherits the base class then the public members of the base class also become the public members of the derived class. Therefore, the public members of the base class are accessible by the objects of the derived class as well as by the member functions of the base class.

    Private mode: When the derive class privately inherits the base class then the public members of the base class become the private members of the derived class.


    Types Of Inheritance

    C++ supports the following five types of inheritance.

    1. Single inheritance
    2. Multiple inheritance
    3. Multilevel inheritance
    4. Hierarchical inheritance
    5. Hybrid inheritance

    1. Single Inheritance

    It refers to an inheritance where a child inherits a single-parent class.
    In the diagram below, class B inherits class A.

    single Inheritance

    Syntax:

    class subclass_name : access_mode base_class_name
    {
      //body of subclass
    };

    Example: C++ example for single inheritance.

    #include <iostream>  
    using namespace std; 
    
    class One  
    {  
        public:  
            int num1 = 10;  
            int num2 = 20; 
            
            int add()  
            {  
              int sum = num1 + num2;  
              return sum;  
            }     
    };  
      
    class Two : public One  
    {  
        public:  
            void print()  
            {  
              //Inheriting method
              int result = add();  
              cout <<"Result of addition: "<< result << endl;  
            }  
    };  
    
    int main()  
    {  
       Two two;  
       //Inheriting Field
       cout << two.num1 << endl;
       two.print();  
      
        return 0;  
    }  

    Output:

    10
    Result of addition: 30


    2. Multiple Inheritance

    Multiple inheritance is the process where the single class inherits the properties from two or more classes.

    In the diagram below, class C inherits from both Class A and Class B.

    multiple Inheritance

    Syntax:

    class subclass_name : specifier base_class1, specifier base_class2, ....
    {
      //body of subclass
    };

    Example: C++ example for multiple inheritance.

    #include <iostream>  
    using namespace std;  
    
    class One  
    {  
        protected:  
            int num1;  
        public:  
            void getNum1(int n)  
            {  
                num1 = n;  
            }  
    };  
      
    class Two  
    {  
        protected:  
            int num2;  
        public:  
            void getNum2(int n)  
            {  
                num2 = n;  
            }  
    };  
    
    //Inherits from One and Two
    class Three : public One, public Two  
    {  
       public:  
         void print()  
         {  
            int sum = num1 + num2;
            cout << "num1 : " << num1 << endl;  
            cout << "num2 : " << num2 << endl;  
            cout << "Result of sum: " << sum;  
         }  
    };  
    int main()  
    {  
       Three th;  
       th.getNum1(5);  
       th.getNum2(10);  
       th.print();  
      
        return 0;  
    }  

    Output:

    num1 : 5
    num2 : 10
    Result of sum: 15


    3. Multilevel Inheritance

    In this type inheritance derived class is created from another derived class. In multilevel inheritance, one class inherits from another class which is further inherited by another class. The last derived class possesses all the members of the above base classes.

    Multilevel Inheritance

    Example: C++ example for multilevel inheritance.

    #include <iostream>  
    using namespace std;  
    
    class Animal 
    {  
       public:  
          void sleep() 
          {   
            cout<<"Animal sleep"<<endl;   
          }    
       }; 
       
    class Dog: public Animal   
    {    
       public:  
          void bark()
          {  
            cout<<"Dog Barking"<<endl;   
          }    
    };
    
    class Puppy: public Dog   
    {    
       public:  
          void puppies() 
          {  
            cout<<"Puppies";   
          }    
     };  
     
    int main(void) 
    {  
        Puppy d;  
        d.sleep();  
        d.bark();  
        d.puppies();
         
         return 0;  
    }  

    Output:

    Animal sleep
    Dog Barking
    Puppies


    4. Hierarchical Inheritance

    The process of deriving more than one class from a base class is called hierarchical inheritance. In other words, we create more than one derived class from a single base class.

    hierarchical Inheritance

    Syntax:

    class One  
    {  
        // Class One members  
    }    
    class Two : public One   
    {  
        // Class Two members.  
    }  
    class Three : public One  
    {  
        // Class Three members  
    }   
    class Four : public One   
    {  
        // Class Four members  
    }  

    Example: C++ example for hierarchical Inheritance.

    #include <iostream>  
    using namespace std;  
    
    class Animal 
    {  
       public:  
          void sleep() 
          {   
            cout<<"Animal sleep"<<endl;   
          }    
       }; 
       
    class Dog: public Animal   
    {    
       public:  
          void dogSound()
          {  
            cout<< "Barks" <<endl;   
          }    
    };
    
    class Cat: public Animal   
    {    
       public:  
          void catSound() 
          {  
            cout<< "Meow" << endl;   
          }    
     };  
     
    int main(void) 
    {  
        Cat c;  
        c.sleep();  
        c.catSound();  
        Dog d;  
        d.sleep();  
        d.dogSound();
         
         return 0;  
    }  

    Output:

    Animal sleep
    Meow

    Animal sleep
    Barks


    5. Hybrid (Virtual) Inheritance

    Hybrid inheritance is the combination of more than one type of inheritance. In the diagram below is the combination of hierarchical Inheritanceand multiple inheritance.

    hybrid Inheritance

    Example: C++ example for hierarchical Inheritance.

    #include <iostream>  
    using namespace std; 
    
    class One 
    {  
        protected:  
            int a = 20;  
        public:  
            void getOne()  
            {  
               cout << "Value of a: " << a <<endl;   
            }  
    };  
    
    class Two   
    {  
        protected:  
            int b = 30;  
        public:  
            void getTwo()  
            {  
                cout << "Value of b: " << b <<endl;
            }  
    };
      
    class Three : public One   
    {  
        protected:  
            int c = 50;  
        public:  
            void getThree()  
            {  
                cout << "Value of c: " << c <<endl;  
            }  
    };  
      
      
    class Four : public Two, public Three  
    {  
        protected:  
           int d;  
           
        public:  
            void add()  
            {  
              getOne();  
              getTwo();  
              getThree();  
              cout << "Sum : " << a + b + c;  
            }  
    };  
    int main()  
    {  
        Four fr;  
        fr.add();  
        return 0;  
    }  

    Output:

    Value of a: 20
    Value of b: 30
    Value of c: 50
    Sum : 100


    Ambiguity in Inheritance

    When there is a function present with the same name in two or more base classes then during multiple inheritances or single inheritance an ambiguity can occur in such cases.

    Example: C++ example for ambiguity in multiple inheritance.

    #include <iostream>  
    using namespace std; 
    
    class One 
    {   
        public:  
            void display()  
            {  
               cout << "Class One" << endl;   
            }  
    };  
    
    class Two   
    {   
        public:  
            void display()  
            {  
                cout << "Class Two" << endl;
            }  
    };
      
    class Three : public One, public Two   
    {   
        public:  
            void print()  
            {  
                display();
            }  
    };  
      
    int main()  
    {  
        Three th;  
        th.print(); 
        
        return 0;  
    }  

    There are display() functions in both the classes of One and Two. The following error will be displayed after execution.

    error: reference to ‘display’ is ambiguous
             display();

    To overcome this problem we need to do the following changes in Class Three by using the class resolution operator (::).

    class Three : public One, public Two   
    {   
        public:  
            void print()  
            {  
                One :: display(); 
                Two :: display();
            }  
    }; 

  • C Program to calculate Simple Interest

    In this tutorial, we will write a program to find the Simple Interest in C. And the formula to calculate the Simple Interest (SI) is:

    SI = ((p * r * t) / 100))
    where,
    p = Principal
    r = Rate of Interest
    t = Time Period

    Explanation:
    The program takes the user input for Principal, Rate, and Time, calculates the result, and displays the result on the screen.


    C Program to calculate the Simple Interest

    //Program to calculate simple interest in C
    
    #include<stdio.h>
    #include<conio.h>
    
    int main()
    {
      float p, r, t;
      float SI;
      
      printf("Enter the principal: ");
      scanf("%f", &p);
      
      printf("Enter the rate: ");
      scanf("%f", &r);
      
      printf("Enter the time: ");
      scanf("%f", &t);
      
      //calculating
      SI = (p * r * t) / 100;
      
      //Display the result
      printf("\nThe simple interest is: %.3f", SI);
    
      return 0;
    }

    Output:

    Enter the principal: 34000
    Enter the rate: 30
    Enter the time: 5

    The simple interest is: 51000.00

    The above source code to calculate the Simple Interest in C is compiled and ran successfully on a windows system. Browse through C Program to learn more.


  • C Program to Print Hello World

    This is the most basic program where the program prints the hello world. Through this, you can understand the basic structure of the C program.

    This the basic program for beginners in C. Let us go through an example.

    Program to Print “Hello World” in C

    //This is the header for standard I/O
    #include<stdio.h>
    
    //This is the main function
    int main() 
    {
      printf("Hello, World!");
    
      return 0;
    }

    Output:

    Hello, World!

    Run the above program in your C compiler and you will get the above output. You may go through the Program structure in C to understand the programming format better.


  • C Program to Multiply two numbers using Addition operator

    In this tutorial, we will write a C program to multiply using the plus operator (+). You may go through the following topics in C to understand the program better.

    Multiplication of two numbers using plus arithmetic operator:
    To find the result of the product of two numbers, we need to add the first number to the second number of times

    Example:

    Input:
    First number: 5
    Second number: 3
    
    Output:
    Multiplication by addition of 5 and 3 is: 15
    
    Solution:
    Multiplication is = 5 + 5 + 5 = 15

    C Program to Multiply number using Addition operator

    //C program to multiply two numbers using plus operator
     
    #include <stdio.h>
     
    int main()
    {
        int num1, num2;
        int result = 0, i;
         
        printf("Enter the first number: ");
        scanf("%d",&num1);
        printf("Enter the second number: ");
        scanf("%d",&num2);
         
        result=0;
    
        for(i = 1; i <= num2; i++)
            result += num1;
        
    
        printf("\nResult of Multiplication of %d and %d through Addition: %d\n", num1, num2, result);
    
        return 0;
    }

    Output:

    Enter the first number: 5
    Enter the second number: 3

    Result of Multiplication of 5 and 3 through Addition: 15


  • C Program to Find the Largest of three Numbers

    In this tutorial, we will write a basic C Program to find the greatest of three numbers. You may go through the following topics in order to understand the C program.

    Algorithm to find the largest among three numbers

    1.  Start.
    2. Read num1, num2 and num3 from user.
    3. Check num > num2, if true go to step 4 else go to step 5
    4. Check num1 > num3.
      • If true, print ‘num1 is the greatest number’.
      • If false, then print ‘num3 as the greatest number’.
      • go to step 6
    5. check if num2 > num3.
      1. If true, print ‘num2 as the greatest number’.
      2. If false, print ‘num3 as the greatest number’.
    6. Stop

    C Program to find the Largest among three Numbers

    We will find the greatest of three using if..else and if…else-if statement.

    //C program to find the biggest of three numbers using if else if statement
    
    #include <stdio.h>
    int main()
    {
        int num1, num2, num3;
        
        printf("Enter three numbers to compare.\n");
        
        printf("First Number: ");
        scanf("%d", &num1);
        printf("Second Number: ");
        scanf("%d", &num2);
        printf("Third Number: ");
        scanf("%d", &num3);
        
        if (num1 > num2)
        {
            if (num1 > num3)
            {
                printf("\nLargest number: %d \n",num1);
            }
            else
            {
                printf("\nLargest number: %d \n",num3);
            }
        }
        else if (num2 > num3)
        {
            printf("\nLargest number: %d \n",num2);
        }
        else
        {
            printf("\nLargest number: %d \n",num3);
        }
        return 0;
    }

    Output:

    Enter three numbers to compare.
    First Number: 32
    Second Number: 65
    Third Number: 19

    Largest number: 65


    Using Ternary operator

    The ternary operator works like an if..else statement in C. Syntax of the ternary operator. (?:)

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

    //Using ternary Operator
    
    #include <stdio.h>
    int main()
    {
        int num1, num2, num3;
        
        printf("Enter three numbers to compare.\n");
        
        printf("First Number: ");
        scanf("%d", &num1);
        printf("First Number: ");
        scanf("%d", &num2);
        printf("First Number: ");
        scanf("%d", &num3);
        
        int greatestNum = ((num1>num2 && num1>num3) ? num1 : (num2>num3)?num2:num3);
        printf("\nLargest of three is: %d.", greatestNum);
        
        return 0;
    }

    Output:

    Enter three numbers to compare.
    First Number: 45
    Second Number: 98
    Third Number: 66

    Largest of three is: 98


  • C Program to Check Whether Number is Even or Odd (Condition and Ternary Operator)

    This is the tutorial to check the number is odd and even in C. A number divisible by 2 is said an even number otherwise the number is called an odd number.

    The concept of checking the number using the Modulus operator. First, calculate the number by modulus by 2, and if the Number mod 2 is equal to 0 then it is an even number else not.

    Flowchart for odd or even number:

    Odd_Even_flowchart

    C Program to Check Even or Odd Number

    #include <stdio.h>
    
    int main() 
    {
        int num;
        
        printf("Enter an integer: ");
        scanf("%d", &num);
    
        // condition checking
        if(num % 2 == 0)
            printf("%d is an EVEN number", num);
        else
            printf("%d is an ODD number", num);
        
        return 0;
    }

    Output:

    //Output 1
    Enter an integer: 32
    32 is an EVEN number

    //Output 2
    Enter an integer: 11
    11 is an ODD number


    C Program to Check Odd or Even Using Ternary Operator

    The ternary operator works like an if..else statement in C. So the above condition checking of the above program can be done in a single line.

    Syntax of the ternary operator. (?:)

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

    #include <stdio.h>
    
    int main() 
    {
        int num;
        
        printf("Enter an integer: ");
        scanf("%d", &num);
    
        // ternary operator
        (num % 2 == 0) ? printf("EVEN number") : printf("ODD number");
        
        return 0;
    }

    Output:

    //Output 1
    Enter an integer: 52
    EVEN number

    //Output 2 a
    Enter an integer: 7
    ODD number


  • C Program to check whether a year is a Leap year or not

    This is the tutorial on the C program to check Leap year. In order to understand the program better, you need to have knowledge of the following topics in C.

    A leap year comes after every 4 years and has 366 days that year instead of 365 days. In the leap year, an additional day is added to the February month has 29 days instead of 28 days.

    Now let us understand through mathematical logic,

    • If a year is divisible by 4 then it is leap year.
    • If a year is divisible by 400 and not divisible by 100 then it is also a leap year.
    • Example: 2000, 2004, 2008, etc are the leap years.

    C Program to Check whether a year is a leap year or not

    #include<stdio.h>  
    #include<conio.h> 
    
    void main() 
    {  
        int year;  
        
        printf("Enter a year: ");  
        scanf("%d", &year);  
        
        //checking all the condition
        if((year%4 == 0 && year%100 != 0 ) || (year%400 == 0)) 
        {  
            printf("%d is a LEAP YEAR", year);  
        } 
        else 
        {  
            printf("%d is NOT a LEAP YEAR", year);  
        }  
        
        getch();  
    }  

    Output:

    //RUN 1
    Enter a year: 1996
    1996 is a LEAP YEAR

    //RUN 2
    Enter a year: 2005
    2005 is NOT a LEAP YEAR


  • C Program to Find Transpose of a Matrix

    In this tutorial, we will write a program on how to calculate the transpose of a matrix in C program. Let us first understand the transpose of a matrix.

    Transpose of a matrix in C:

    The new matrix obtained by exchanging the rows and columns of the original matrix is called a transpose matrix. It is a common exercise that every beginner who started to learn C programming must know.

    transpose of a matrix in C

    Let us understand through the program in C.


    C program to find the transpose of a matrix

    #include <stdio.h>
    
    int main() 
    {
      int arr[10][10], transpose[10][10], m, n;
      
      printf("Enter number of rows: ");
      scanf("%d", &m);
      printf("Enter number of columns: ");
      scanf("%d",&n);
    
     
      printf("\nEnter matrix elements:\n");
      for (int i = 0; i < m; ++i)
         for (int j = 0; j < n; ++j) 
              scanf("%d", &arr[i][j]);
         
    
      // calculting transpose
      for (int i = 0; i < m; ++i)
         for (int j = 0; j < n; ++j)
             transpose[j][i] = arr[i][j];
      
      
      // printing the transpose
      printf("Transpose of entered matrix:\n");
      for (int i = 0; i < n; ++i) 
      {
          for (int j = 0; j < m; ++j) 
            printf("%d  ", transpose[i][j]);
            
        printf("\n");
      }
      
      return 0;
    }

    Output 1: matrix 3×3

    Enter number of rows: 3
    Enter number of columns: 3

    Enter matrix elements:
    1 2 3
    4 5 6
    7 8 9
    Transpose of entered matrix:
    1 4 7
    2 5 8
    3 6 9

    Output 2: matrix 2×3

    Enter number of rows: 2
    Enter number of columns: 3

    Enter matrix elements:
    1 2 3
    4 5 6
    Transpose of entered matrix:
    1 4 2
    5 3 6


  • C++ Encapsulation

    Encapsulation is defined as the wrapping up of data(variable) under a single unit. Encapsulation is an important concept of OOP in C++ that binds data and functions inside a class together that manipulate them. Data encapsulation leads to the important concept called data hiding.

    It makes sure that the ‘sensitive’ data are hidden from the user and an access specifier is used to achieve this. private specifier is used to hide sensitive data, it makes the data inaccessible from outside the class. But to modify or read those data, we need to use the getter and setter (i.e. get and set) method. It prevents from accessing the data directly.

    Example of specifiers to bind data:

    class Square
    {
       private:
          double side;  
    
    
       public:
          void setSide(int s) 
          {
            if (s >= 0)
             side = s;
          }
    };

    Let us go through an example in C++ to understand the concept of hiding data.


    Data Hiding Using the private Specifier in C++

    #include <iostream>
    using namespace std;
    
    class Rectangle 
    {
       //private members
       private:
          float length;
          float breadth;
    
       public:
    
         // Setter for length and breadth
         void setLength(float l) 
         {
           length = l;
         }
         void setBreadth(float b) 
         {
           breadth = b;
         }
    
         // Getter for length and breadth
         float getLength() 
         {
           return length;
         }
         float getBreadth() 
         {
           return breadth;
         }
        
         // area function
         float getArea() 
         {
           return length * breadth;
         }
    };
    
    //main function
    int main() 
    {
      Rectangle rect;
    
      //setting the length and breadth value
      rect.setLength(10);
      rect.setBreadth(6.5);
    
      // getting the length and breadth value
      float length = rect.getLength();
      cout << "Length: " << length << endl;
    
      float breadth = rect.getBreadth();
      cout << "Breadth: " << breadth << endl;
    
      // Area
      cout << "Area of a rectangle: " << rect.getArea();
    
      return 0;
    }

    Output:

    Length: 10
    Breadth: 6.5
    Area of a rectangle: 65

    In the above program length and breadth in Rectangle class is a private member which means they are not accessible from outside the class. So to get and set the value of length and breadth, we created a setter (pass the value) and getter (return the value). Hence the private members are not accessible directly, making it hidden.


    Benefits of Encapsulation:

    • Data- hiding in Java.
    • The class field can be made read-only or write-only.
    • It provides the class the total control over the data.