Author: admin

  • 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.

  • C++ Interface (Abstract classes)

    The interface is implemented using an abstract class in C++, hence the word interface and abstract class are used interchangeably.

    Abstraction classes are the way to achieve abstraction and abstraction is a technique in programming to hide the internal details and only show the necessary functionalities.

    The classes with at least one pure virtual function are said to be abstract classes. A pure virtual function is has a signature as “0” and of course with a virtual keyword itself as shown below.

    virtual void fun() = 0;

    And the above function can be called an abstract function as it has no body. The purpose of an abstract class is to serve as an interface and provide a base class from which other classes can inherit. Also, the instance of an abstract class cannot be created.

    Let us understand through an example in C++ for abstract classes.


    C++ Abstract class example

    In the program below, we have three classes Animal (parent class), Cat, and Dog (derived class). The sound() function for each animal (dog and cat) is different but they have the same function name, so the function sound() is made pure virtual function in the parent class, Animal.

    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
         //Pure Virtual Function
         virtual void sound() = 0;
    
         //Parent member Function
         void eat()
         {
           cout << "Animals eat.";
         }
    };
    
    //Cat class inherits Animal
    class Cat: public Animal
    {
       public:
         void sound()
         {
            cout << "Meow" << endl;
         }
    };
    
    //Dog class inherits Animal
    class Dog: public Animal
    {
       public:
         void sound()
         {
           cout << "Woof" << endl;
         }
    };
    
    //main function
    int main()
    {
       Dog d;
       Cat c;
    
       d.sound();
       c.sound();
       d.eat();
    
       return 0;
    }

    Output:

    Woof
    Meow
    Animals eat.


  • C Program to Find Inverse of a Matrix

    In this tutorial, you will learn to write a program to find the inverse of a matrix in C. Let us first start by understanding how to find the inverse of a matrix and the requirements to find it.

    In order to find the inverse of a matrix,

    • The matrix must be a square matrix.
    • Determinant needs to be calculated and should not equal to zero (0).
    • Then find the adjoint of a matrix and
    • Lastly, multiply 1/determinant by adjoint to get the inverse of a matrix.

    Adjoint of a matrix

    The adjoint of a matrix is obtained by taking the transpose of the cofactor matrix of a given square matrix. it is also called the Adjugate matrix. For matrix A, it is denoted by adj A.

    Determinant of a matrix:

    It is calculated in the following way for the square matrices.

    The formula to find inverse of matrix:

    matrix inverse formula

    C Program to Find Inverse of a Matrix

    #include<stdio.h>
    #include<math.h>
    
    //function prototype that are being created
    void cofactor(float [][25], float);
    float determinant(float [][25], float);
    void transpose(float [][25], float [][25], float);
    
    int main()
    {
      float a[25][25], n, d;
      int i, j;
      
      printf("Enter the order of the Matrix: ");
      scanf("%f", &n);
      printf("Enter the elements of a matrix: \n");
      for (i = 0;i < n; i++)
        {
         for (j = 0;j < n; j++)
           {
            scanf("%f", &a[i][j]);
            }
        }
        
      d = determinant(a, n);
      if (d == 0)
       printf("Since the determinant is zerp (0), therefor inverse is not possible.");
      else
       cofactor(a, n);
    }
     
    // function for the calculation of determinant
    float determinant(float a[25][25], float k)
    {
      float s = 1, det = 0, b[25][25];
      int i, j, m, n, c;
      if (k == 1)
        {
         return (a[0][0]);
        }
      else
        {
         det = 0;
         for (c = 0; c < k; c++)
           {
            m = 0;
            n = 0;
            for (i = 0;i < k; i++)
              {
                for (j = 0 ;j < k; j++)
                  {
                    b[i][j] = 0;
                    if (i != 0 && j != c)
                     {
                       b[m][n] = a[i][j];
                       if (n < (k - 2))
                        n++;
                       else
                        {
                         n = 0;
                         m++;
                         }
                       }
                   }
                 }
              det = det + s * (a[0][c] * determinant(b, k - 1));
              s = -1 * s;
              }
        }
     
        return (det);
    }
    
    
    // function for cofactor calculation
    void cofactor(float num[25][25], float f)
    {
     float b[25][25], fac[25][25];
     int p, q, m, n, i, j;
     for (q = 0;q < f; q++)
     {
       for (p = 0;p < f; p++)
        {
         m = 0;
         n = 0;
         for (i = 0;i < f; i++)
         {
           for (j = 0;j < f; j++)
            {
              if (i != q && j != p)
              {
                b[m][n] = num[i][j];
                if (n < (f - 2))
                 n++;
                else
                 {
                   n = 0;
                   m++;
                   }
                }
            }
          }
          fac[q][p] = pow(-1, q + p) * determinant(b, f - 1);
        }
      }
      transpose(num, fac, f);
    }
    
    
    ///function to find the transpose of a matrix
    void transpose(float num[25][25], float fac[25][25], float r)
    {
      int i, j;
      float b[25][25], inverse[25][25], d;
     
      for (i = 0;i < r; i++)
        {
         for (j = 0;j < r; j++)
           {
             b[i][j] = fac[j][i];
            }
        }
        
      d = determinant(num, r);
      for (i = 0;i < r; i++)
        {
         for (j = 0;j < r; j++)
           {
            inverse[i][j] = b[i][j] / d;
            }
        }
        
       printf("\nThe inverse of matrix: \n");
       for (i = 0;i < r; i++)
        {
         for (j = 0;j < r; j++)
           {
             printf("\t%f", inverse[i][j]);
            }
        printf("\n");
         }
    }

    Output:

    Inverse of a matrix in C

  • C Program to Find Sum of Diagonal elements in a Matrix

    In this tutorial, we will learn how to write C Program to find the Sum of Diagonals of Matrix. as the matrix contains two diagonals, we will consider one as the main and another as the opposite.

    Note that the number of rows and number of columns of a matrix must be equal that is it should be 2×2 or 3×3, etc. In other words, the matrix must be a square matrix.

    We will look through the C program and find the sum of the main & opposite diagonal elements of an MxN Matrix. For example:

    Consider a matrix of 2×2 matrix,
    2    3
    6    5
    Output:
    Sum of the main diagonals = 2+5 = 7
    Sum of the opposite diagonals = 3+6 = 9


    C Program to find the sum of the diagonal elements in a matrix

    #include <stdio.h>
    
    void main()
    {
       int arr[10][10];
       int i, j, m, n, sum1 = 0, sum2 = 0;
    
       printf("Enter the order of the matix: ");
       scanf("%d %d", &m, &n);
    
       //Checking the condition to see if m is equal to n
       if (m == n)
       {
          printf("Enter the elements for the matrix: \n");
          for (i = 0; i < m; ++i)
          {
             for (j = 0; j < n; ++j)
             {
                scanf("%d", &arr[i][j]);
             }
          }
    
          // Adding the diagonals
          for (i = 0; i < m; ++i)
          {
             sum1 = sum1 + arr[i][i];
             sum2 = sum2 + arr[i][m - i - 1];
          }
    
          printf("\nThe sum of the main diagonal: %d\n", sum1);
          printf("The sum of the opposite diagonal: %d\n", sum2);
    
       }
       else
          printf("The order entered is not square matrix.");
    
    }

    Output:

    sum of the diagonals of matrix in C

    As you can see in the program that if..else statement has been used to check if the order entered is a square matrix or not (m == n).


  • C++ Data Abstraction

    Data abstraction is the process of hiding the details but only displaying the relevant information to the users. This is one of the main advantages of using abstraction.

    It is a programming way or a technique through which we can separate the interface with the implementation details.

    Take a real-life example:
    Suppose a person is typing with the help of a keyboard on his/her computer. That person knows that pressing any alphabet on the keyboard, displays that alphabet on the screen of the monitor but he/she doesn’t know how the internal mechanism is working to display the alphabet.
    Therefore, hiding the internal mechanism and showing only its output is an abstraction in this example.

    C++ also provides a great level of abstraction such as the function pow() we use in a program to calculate the power of some number is internally implemented. Although we do not know how it is implemented. We just use it by calling pow() without knowing its algorithm.

    There is another example such as private and public modifiers or sort()function that we use in a program.

    In C++, abstraction can be achieved in two ways.

    • Abstraction using classes
    • Abstraction in header files.

    Abstraction using Classes:

    Classes are used o achieve abstraction in C++. A class grouped the class members that is data members and member function into a single unit using access specifiers. A class can decide which members are relevant to show to the outside world and which to hide.

    Abstraction in Header files:

    Another way to achieve abstraction is through header files. For example, consider the use of function pow() in a program to calculate the power of some number that is present in math.h header file, and this function is internally implemented. Although we do not know how it is implemented. We just use it by calling pow() without knowing its algorithm.

    Access Specifiers for abstraction:

    Access specifiers are the main way to implement abstraction and enforce the restriction on class members in C++.

    • private: The members declared private are only accessible to the class They are not allowed to access outside the class, hence making it secure.
    • public: The members declared public can be accessed from anywhere in the program.

    Let us understand through a C++ example for abstraction using the above two specifiers.

    Example of C++ data abstraction using classes

    //C++ program to demonstrate the abstraction
    
    #include <iostream>
    using namespace std;
    
    class Average
    {
       // delaring private members 
       private:
          int num1, num2, avg;
    
       // public members 
       public_colon
       void set(int x, int y)
       {
          num1 = x;
          num2 = y;
       }
    
       void display()
       {
          avg = (num1 + num2) / 2;
          cout << "Average: " << avg << endl;
       }
    };
    
    int main()
    {
       Average ag;
    
       ag.set(10, 10);
       ag.display();
    
       return 0;
    }

    Output:

    Average: 10

    As you can see in the above program the private variables num1, num2 and avg cannot be accessed outside the class. Only the public member functions are allowed to access.


    Advantage of data abstraction

    • When you need to modify the code in the future, you only need to modify the higher-level class and no need to modify the lower-level class.
    • It also avoids code duplication increases the reusability of the code.
    • Since the abstraction separates the interface and implementation, the internal changes can be easily made without affecting the user-level code.
    • The abstracting of the data itself increases the security as no user can access the internal hidden mechanism.

  • C++ Virtual Function

    Virtual function in C++ is a member function in the base class that we redefined in a derived class. With the use of a virtual function, we ensure that the function is overridden.

    A virtual function lets the compiler know to perform dynamic linkage or late binding on the function (that is the called function needs to be resolved at run time).

    A keyword ‘virtual‘ is used preceding with the function to be overridden. A virtual function cannot be a static member nor we can have a virtual constructor.

    Let us understand through an example, we will first see a program without the use of virtual keywords and next with the use of virtual.


    C++ Program Overriding a non-virtual function

    // C++ program for function overriding without virtual function
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       void display()
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal *a;
       Dog d;
       
       a = &d;
       a->display();
    
       return 0;
    }

    Output:

    I am Animal

    As you can see in the above program that we created a pointer object for the base class and the function is the same in both of the classes which are to be overridden. But even though the object of the base class points to the derived class (a = &d;), when we call it through an object a, we still get the display() function of the base class.

    Therefore, here we need a virtual function in order to get access to the member of the derived class which we will see in the program below.


    C++ Program Overriding using a virtual function

    // C++ program for function overriding with virtual function
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       virtual void display() //virtual function
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal *a;
       Dog d;
       
       a = &d;
       a->display();
    
       return 0;
    }

    Output:

    I am a Dog

    As you can see above is the same first program but with a virtual display() function. And now the result is different, the base object a which is pointed to the derived class gives the display() function of the derived class indicating the virtual function of the base class is overridden by the derived class.


  • C++ Function Overriding

    Function overriding allows us to define a function at a derived class that is already present in a base class. And that base is said to be overridden. Both derived and base class has the member function with the same name, same return type, and same arguments list.

    And the decision made to call the required function is done at the run time. Hence, it is used to achieve the Runtime polymorphism.

    Let us understand through an example of function overriding using C++. It involves inheritance in a program given below.

    Example of Function Overriding in C++

    // C++ program for function overriding
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       void display()
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal anim = Animal();
       anim.display();	//parent class object 
    
       Dog dg = Dog();
       dg.display();	// derived class object
    
       return 0;
    }

    Output:

    I am Animal
    I am a Dog