Blog

  • C Program to find Cosine value

    In this tutorial, we will write a C Program to find Cosine series. Let us first by understanding what is cosine series.

    Cosine Series:

    It is a series used to find the value of cos(x), where x is the angle in degree which is converted to Radian.

    Formula:

    cosine formula

    For Cos(x) series:

    Cos(x) = 1 – (x*2 / 2!) + (x*4 / 4!) – (x*6 / 6!)……

    Let us understand through a C program to calculate the value of cos(x).

    Example

    Input-:
    x = 4, n = 3
    Output-:
    0.997563

    Input-:
    x = 8, n = 2
    Output-:
    0.990266


    C Program to find Cosine series

    #include <stdio.h>
    
    const double PI = 3.142;
    
    int main()
    {
       float x;
       int n;
       float result = 1;
       float s = 1, fact = 1, p = 1;
    
       printf("Enter x value: ");
       scanf("%f", &x);
    
       printf("Enter n value: ");
       scanf("%d", &n);
    
       //Converting degrees to radians
       x = x *(PI / 180.0);
    
       for (int i = 1; i < n; i++)
       {
          s = s *-1;
          fact = fact *(2 *i - 1) *(2 *i);
          p = p *x * x;
          result = result + s *p / fact;
       }
    
       printf("Result: %lf\n", result);
       return 0;
    }

    Output:

    Enter x value: 10
    Enter n value: 3
    Result: 0.984804


  • C++ Overloading (Operator and Function)

    C++ allows us to overload methods, constructor and indexed properties. The function or operator define with the same name but with different types of parameters s called overloading. C++ has two types of overloading and they are:

    • Function overloading
    • Operator overloading

    C++ Function overloading

    Function overloading is a feature of object-oriented programming where multiple functions having the same name differs by their parameters, then these functions are said to be overloaded. When we call those functions, we need to make sure to enter the proper number of arguments along with the proper data type.

    Example: Below are the sample of functions with same name but different arguments.

    // same name different arguments
    int func() { }
    int func(int n) { }
    float func(double d) { }
    int func(int n, double d) { }

    Error example: Now see the example below, the functions defined below have the same name, same number type, and the same number of arguments. In such cases, the compiler will through an error.

    // Compiler throws error
    int func(float num1) { }
    double func(float num2){ }

    The advantage of function overloading is that we do not need to write different names for the functions that perform the same task, increasing the readability of the program. Polymorphism is achieved by function overloading.

    Let us go through an example in C++ for function overloading.

    C++ program for function overloading with different types and different number of parameters

    // C++ program for function overloading
    
    #include <iostream>
    using namespace std;
    
    class OverloadProgram
    {
       public:
       int total(int num1, int num2)
       {
          return num1 + num2;
       }
    
       int total(int num1, int num2, float num3)
       {
          return num1 + num2 + num3;
       }
    };
    
    int main()
    {
       OverloadProgram obj;
    
       //calling first display function
       cout << "Result 1: " << obj.total(50, 40) << endl;
    
       //calling second display function
       cout << "Result 2: " << obj.total(7, 15, 5) << endl;
    
       return 0;
    }

    Output:

    Result 1: 90
    Result 2: 27

    C++ Operator Overloading

    Operator overloading means performing different operations with the same operator. We can overload most of the built-in operators that are available in C++. We can also change the user-defined type as well such as objects and structures.

    The keyword ‘operator‘ is used to overload an operator. Compile-time polymorphism is achieved through operator overloading. It has a return type and parameter list.

    Example: Consider an operator ‘+‘, it is used to add the two numbers but it is also used with string to concatenate two strings. So the ‘+‘ operator when placed between number operands, addition operation is done but when placed between string operands, it concatenates them.

    Syntax: syntax for operator overloading in C++.

    class class_name
    {
        ... .. ...
        public
           return_type operator symbol (arguments_list) {
               //code
           } 
    };

    In the above syntax,

    • return_type is the type that is returned by the function
    • symbol refers to the operator that is to be overloaded such as +, <, -, >, etc.

    However there are few operator that cannot be overloaded and they are:

    • sizeof operator
    • Scope operator (::)
    • ternary operator(?:)
    • member pointer selector(*)

    Let us go through an example in C++ for operator overloading.

    C++ Program for operator overloading

    // Overload ++ program
    
    #include <iostream>
    using namespace std;
    
    class TestOperator
    {
       private:
          int number;
    
       public:
    
         // Constructor
         TestOperator(): number(9) {}
    
         // ++ overloaded
         void operator++()
         {
           ++number; // pre increment by 1
         }
    
         void display()
         {
           cout << "The Count: " << number << endl;
         }
    };
    
    int main()
    {
       TestOperator op;
    
       // Calling the void operator++ ()function
       ++op;
    
       //calling display function
       op.display();
       return 0;
    }

    Output:

    The Count: 10

    Another example for operator overloading in C++.

    // C++ program for operator overloading
    #include <iostream>
    using namespace std;
    
    class Message
    {
      string str;
      public_colon
      Message(string i)
      {
        str = i;
      }
    
      void operator+(Message);
      void display();
    };
    
    void Message::operator+(Message a)
    {
      string msg = str + a.str;
      cout << "The result: " << msg;
    
    }
    
    int main()
    {
      Message m1("Hi, Welcome ");
      Message m2("Home");
    
      m1 + m2;
    
      return 0;
    }

    Output:

    //Output:
    The result: Hi, Welcome Home

    The advantage of operator overloading is that we can perform different operations on the same operand.


  • LRU Page Replacement Algorithm in C

    In this tutorial, we will look at C program for LRU Page Replacement Algorithm.

    Least Recently Used (LRU) Page Replacement algorithm

    It is an algorithm whose concept is based on the pages used in an instruction. The pages that are vigorously utilized in past instruction are probably going to be utilized intensely in the next instruction and the pages with used less are likely to be used less in the future. When a new page refereed is not present in the memory, a page fault occurs.

    Whenever a page fault occurs, the page that is least used is removed from the memory frames.

    Let us see an implementation of lru page replacement in c.

    C program to implement LRU page replacement algorithm

    //C program for LRU replacement algorithm implementation
    
    #include <stdio.h>
    
    //user-defined function
    int findLRU(int time[], int n)
    {
       int i, minimum = time[0], pos = 0;
    
       for (i = 1; i < n; ++i)
       {
          if (time[i] < minimum)
          {
             minimum = time[i];
             pos = i;
          }
       }
    
       return pos;
    }
    
    //main function
    int main()
    {
       int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j, pos, faults = 0;
       printf("Enter number of frames: ");
       scanf("%d", &no_of_frames);
    
       printf("Enter number of pages: ");
       scanf("%d", &no_of_pages);
    
       printf("Enter reference string: ");
    
       for (i = 0; i < no_of_pages; ++i)
       {
          scanf("%d", &pages[i]);
       }
    
       for (i = 0; i < no_of_frames; ++i)
       {
          frames[i] = -1;
       }
    
       for (i = 0; i < no_of_pages; ++i)
       {
          flag1 = flag2 = 0;
    
          for (j = 0; j < no_of_frames; ++j)
          {
             if (frames[j] == pages[i])
             {
                counter++;
                time[j] = counter;
                flag1 = flag2 = 1;
                break;
             }
          }
    
          if (flag1 == 0)
          {
             for (j = 0; j < no_of_frames; ++j)
             {
                if (frames[j] == -1)
                {
                   counter++;
                   faults++;
                   frames[j] = pages[i];
                   time[j] = counter;
                   flag2 = 1;
                   break;
                }
             }
          }
    
          if (flag2 == 0)
          {
             pos = findLRU(time, no_of_frames);
             counter++;
             faults++;
             frames[pos] = pages[i];
             time[pos] = counter;
          }
    
          printf("\n");
    
          for (j = 0; j < no_of_frames; ++j)
          {
             printf("%d\t", frames[j]);
          }
       }
    
       printf("\nTotal Page Faults = %d", faults);
    
       return 0;
    }

    Output:

    lru replacement algorithm

  • C Program to Compare two Strings using strcmp()

    In this tutorial, we will Compare Strings Using strcmp() function in C. But if you want to learn more about String you may go through the following topic in C.

    strcmp() function is used to compare two string to each other and returns an integer value.

    The syntax for strcmp() in c:

    strcmp(first_string, second_string);

    • returns 0: if both the string are equal.
    • returns negative integer: if string1 < string2
    • returns positive integer: if string1 > string2

    The header file string.h defines the strcmp() function.

    Let us understand through an example of strcmp function in C programming.


    String comparison using strcmp() function in C

    //C Program to Compare Two Strings using strcmp()
    
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char str1[20], str2[20];
        int result;
        
        printf("Enter a first string: ");
        gets(str1);
        printf("Enter a second string: ");
        gets(str2);
        
        //use of strcmp
        result = strcmp(str1, str2);
        
        
        //displaying the result
        if (result == 0)
            printf("Strings are same");
        else
            printf("Strings are not same");
        return 0;
    }

    Output:

    Enter a first string: This is simple2code
    Enter a second string: This is simple2code
    Strings are same

    str1 and str2 takes the input for the two strings from the user and the result variable stores the value after comparison of two strings. And the final result is displayed accordingly.


  • C++ Polymorphism

    Polymorphism means having many forms. The word “poly” means many and “morphs” means forms, which means it is the way of performing some task in many ways. That means a single function or an operator functioning in many ways. It is one of the major concepts of Object-oriented programming.

    Take a real-life example: A woman can be a mother or daughter and a teacher in a class, that is she posses a different behaviour at different times or situations. Similarly, a class in a program has a method and the subclass have the same method but with a different task to perform related to the first method. This is called polymorphism.

    In C++, we have two types of polymorphism and they are:

    • Compile-time Polymorphism or Static (or early) Polymorphism.
    • Runtime Polymorphism or Dynamic (or late) Polymorphism.

    1. Compile time Polymorphism

    In this type of program, the flow of control is decided at compile time itself. It is achieved by function overloading and operator overloading. It is also known as static or early binding.

    Function Overloading:

    The multiple functions having the same name but with different parameters, then these functions are said to be overloaded. When we call those functions, we need to make sure to enter the proper number of arguments along with the proper data type.

    Example: C++ example of function overloading.

    // C++ program for function overloading
    
    #include <iostream>
    using namespace std;
    
    class OverloadProgram
    {
       public:
       int total(int num1, int num2)
       {
          return num1 + num2;
       }
    
       int total(int num1, int num2, float num3)
       {
          return num1 + num2 + num3;
       }
    };
    
    int main()
    {
       OverloadProgram obj;
    
       //calling first display function
       cout << "Result 1: " << obj.total(50, 40) << endl;
    
       //calling second display function
       cout << "Result 2: " << obj.total(7, 15, 5) << endl;
    
       return 0;
    }

    Output:

    Result 1: 90
    Result 2: 27

    Operator Overloading:

    To achieve Compile time Polymorphism, operator overloading is also used. Operator overloading means performing different operations with the same operator. The keyword ‘operator‘ is used to overload an operator.

    Example: Consider an operator ‘+‘, it is used to add the two numbers but it is also used with string to concatenate two strings. So the ‘+‘ operator when placed between number operands, addition operation is done but when placed between string operands, it concatenates them.

    Let us understand through an example: C++ program for operator overloading.

    // C++ program for operator overloading
    
    #include <iostream>
    using namespace std;
    
    class Message
    {
      string str;
      public:
        Message(string i)
        {
          str = i;
        }
    
      void operator+(Message);
      void display();
    };
    
    void Message::operator+(Message a)
    {
      string msg = str + a.str;
      cout << "The result: " << msg;
    
    }
    
    int main()
    {
      Message m1("Hi, Welcome ");
      Message m2("Home");
    
      m1 + m2;
    
      return 0;
    }

    Output:

    //Output:
    The result: Hi, Welcome Home

    2. Run time Polymorphism

    In run time polymorphism, the program is called at the time of execution that is at rum time. It is also known as the late binding or dynamic binding.

    This type of polymorphism is achieved by Method Overriding. We use virtual functions and pointers to achieve this.

    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.

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

    Example: C++ example of function overriding.

    // 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

    Differences between Compile time and Run time Polymorphism

    Compile-time polymorphismRun time polymorphism
    In this type of program, the flow of control is decided at compile time itself.The program is called at the time of execution that is at rum time
    It is achieved by function overloading and operator overloadingIt is achieved by function overriding and virtual function.
    Also called static or early binding.Also called late binding or dynamic binding.
    Here, the methods have the same name but with a different number of parameters or the type of parameters.Here, the methods have the same name, the same number of parameters, or the type of parameters.
    As it happens at compile-time, therefore provides a fast execution.As it happens at run-time, therefore provides a slow execution.

  • C++ Copy Constructor

    A copy constructor in C++ is used to create a copy of an already existed object. It is also used to Initialize one object from another of the same type.

    There are two types of copy constructor:

    • Default Copy constructor
    • User-Defined constructor

    Default Copy constructor:

    The default copy constructor is defined by the compiler when the user do not define a copy constructor.

    Syntax for Default Copy constructor:

    ClassName (const class_name &old_object_name)
    {
      ......
    }

    let us go through the program in C++.

    C++ Program of the copy constructor

    // C++ program for copy constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class  Rectangle {
    
      public:
           float length;
           float breadth;
           Rectangle(float l, float b)   // constructor
           { 
             length = l;
             breadth = b;
           }
           
           Rectangle(const Rectangle &obj) // copy constructor
           {
            length = obj.length;
            breadth = obj.breadth;
           }
           
           void displayArea()
           {
             float area = length * breadth;
             
             //display
             cout << "Area: " << area << endl;
           }
    };
    
    int main() 
    {
        Rectangle rect1(6, 4); //parameterized constructor
        Rectangle rect2(rect1); //copy constructor
        
        
        rect2.displayArea(); //calling through the copy constructor
        
        return 0;
    }

    Output:

    Area: 24

    Shallow Copy Constructor

    A shallow copy is a process where the copy of an object is created by copying all the member’s data exactly as it is. Default copy constructor produces the shallow copy constructor.

    Both the objects that are the original and copy point at the same memory. Since, both the object points to the same memory location, changes made by one will be reflected on other. Now since we only need to make a replica of the original object, shallow does not fully fill this purpose.

    Let us understand through an example in C++.

    // C++ program for the shallow constructor
    
    #include <iostream>
    using namespace std;
      
    
    class Rectangle 
    {
      private:
        int length;
        int *breadth;
      
      public:
        Rectangle() 
        {
            breadth = new int;
        }
    
        // Function for dimension set
        void setDimensions(int l, int b)
        {
           length = l;
           *breadth = b;
        }
      
        //display method
        void display()
        {
           cout << "Length: " << length << endl;
           cout << "Breadth: " << *breadth << endl;
        }
    };
      
    int main()
    {
        // Object of Rectangle
        Rectangle rect1;
        rect1.setDimensions(10, 5); //set data
      
        //copying rect1 at the time of initialization
        Rectangle rect2 = rect1;
        rect2.display();
      
        return 0;
    }

    Output:

    Length: 10
    Breadth: 5
    Shallow Copy constructor

    Since the pointer breadth of both the objects (original and copied) points to the same memory location, freeing one of the memory will free the other one too. So this is solved by the Deep Constructor.


    Deep Copy Constructor

    A deep copy constructor is used to overcome the problem caused by the Shallow constructor. In the deep constructor, it is like having a copy of a project but both the original and copied project are kept in separate files, that is the changes made in one of the files will not affect the other.

    A deep copy will allocate separate memory space for copied file. A user-defined copy constructor is used for the Deep copy constructor and assign dynamic memory as well if required.

    Let us understand through an example in C++.

    // C++ program for the Deep constructor
    
    #include <iostream>
    using namespace std;
      
    
    class Rectangle 
    {
      private:
        int length;
        int *breadth;
      
      public:
        Rectangle() 
        {
            breadth = new int;
        }
        
        Rectangle (Rectangle &rec)
        {
            length = rec.length;
            breadth = new int;
            *breadth = *(rec.breadth);
        }
        
        // Function for dimension set
        void setDimensions(int l, int b)
        {
           length = l;
           *breadth = b;
        }
      
        //display method
        void display()
        {
           cout << "Length: " << length << endl;
           cout << "Breadth: " << *breadth << endl;
        }
        
        //destructor
        ~Rectangle()
        {
           delete breadth;
        }
    };
      
    int main()
    {
        // Object of Rectangle
        Rectangle rect1;
        rect1.setDimensions(10, 5); //set data
      
        //copying rect1 at the time of initialization
        Rectangle rect2 = rect1;
        rect2.display();
      
        return 0;
    }

    Output:

    Length: 10
    Breadth: 5
    Deep copy constructor

    As you can see in the program above, we use destructor to destroy the dynamically allocated memory.


  • C++ Destructor

    As the name indicates, a C++ destructor destroys the object of a class as soon as the scope of an object ends. It is opposite to a constructor. When an object goes out of the scope, the compiler automatically calls the destructor function.

    Also, the destructor has the exact same name as the class, the difference is, it is prefixed with a tilde sign (~). And the destructor cannot have parameters nor modifiers.

    The syntax for C++ destructor:

    class Square
    {
        public:
         // destructor
         ~Square() 
         {
           // statement
         }   
    };

    let us see an example of a destructor in C++.


    C++ example for the Constructor and Destructor call

    // C++ program for destructor and constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class  Square 
    {
       public:
        // constructor
        Square() {
            cout << "Constructor Invoked." << endl;
        }
        //Destructor
        ~Square() {
            cout << "Destructor Invoked." << endl;
        }
    };
    
    int main() {
    
        // creating an objects of Square class
        Square sq1;
        Square sq2;
    
        return 0;
    }

    Output:

    Constructor Invoked.
    Constructor Invoked.
    Destructor Invoked.
    Destructor Invoked.


  • C++ Constructor

    In C++, a constructor is a special type of method that is called automatically when an instance of the class (object) is created. The compiler calls the constructor and is used to initialize the data members of a newly created object.

    The constructor has the same name as its class. Also, it doe not have any return type not even void.

    Let us first look at the syntax of constructor in c++

    class A
    {
      public:
         int x;
    
         // constructor
         A()
         {
           // object initialization
         }
    };

    Types of Constructor in C++

    1. Default constructor
    2. Parameterized constructor

    C++ Default constructor

    The constructor with no arguments is called a default constructor.

    Let us look into the example of the C++ default Constructor.

    // C++ program for default constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class Square
    {
       private:
          float side;
    
       public:
         // constructor
         Square()
         {
           side = 12.4;
    
           cout << "Side: " << side << endl;
         }
    };
    
    int main()
    {
       // creating an objects of Square class
       Square sq1;
    
       return 0;
    }

    Output:

    Side: 12.4

    Note: Default Constructor is used if the user does not define a constructor then the compiler creates a default constructor and initializes the member variables to its default values.


    C++ Parameterized Constructor

    A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign an initial value to an object at the time of its creation.

    Let us look into the example of the C++ Parameterized Constructor.

    // C++ program for Parameterized constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class Rectangle
    {
       public:
           float length;
           float breadth;
           Rectangle(float l, float b)	// constructor
           {
              length = l;
              breadth = b;
           }
           void CalArea()
           {
              float area = length * breadth;
        
             	//display
              cout << "Area: " << area << endl;
           }
    };
    
    int main()
    {
       // creating an objects of Rectangle class
       Rectangle rect1(6, 4);
       Rectangle rect2(3.5, 2.8);
    
       rect1.CalArea();
       rect2.CalArea();
    
       return 0;
    }

    Output:

    Area: 24
    Area: 9.8


  • Algorithm and Flowchart to find Factorial of a number

    This is the tutorial we will write an algorithm to find the factorial of a number, we will also learn to draw a flowchart to find Factorial of a number. You may go through the topic below to learn more about algorithms.

    Let us start with a flowchart for factorial numbers.

    Flowchart to calculate the factorial of a number

    flowchart for factorial of a number

    The above flowchart diagram is to find the factorial number.


    Algorithm of factorial of a number

    Step 1: Start
    Step 2: Read a number n
    Step 2: Initialize variables:
    i = 1, fact = 1
    Step 3:  if i <= n go to step 4 otherwise go to step 7
    Step 4: Calculate
    fact = fact * i
    Step 5: Increment the i by 1 (i=i+1) and go to step 3
    Step 6: Print fact
    Step 7: Stop

    If you want to understand through code, you may follow the below link:


  • C++ Classes and Objects

    C++ is an Object-Oriented Programming Language and classes and objects are the fundamental components of OOP’s. Everything in C++ is linked with classes and objects. The main purpose of C++ is to introduce the OOPs concept in the C programming language which itself is a powerful language.

    Objects are real-life entity and classes are the blueprint for creating an object. For example: consider a class for a car, it has color, some weight, size, etc, these are its attributes and drive, gear, brake, etc are its behaviour.

    These attributes and behaviour in a program are variables and functions in a class, also called the class members.

    C++ Class

    A class is a user-defined blueprint or prototype for creating Objects. It is a logical entity. We can say that classes are categories, and objects are items within each of those categories.

    It contains fields, methods, constructors, etc. These members of a class can be accessed and used by creating an instance of that class.

    Defining Class:

    The definition of the class starts with the keyword class followed by a class name. The body of the class is enclosed within the curly braces and ends with a semicolon. All the members of the class are declared within the body of the class as shown below.

    Syntax for class:

    class Rectangle
    {
       public:            //access specifiers
          float length;   // Length of a rectangle
          float breadth;  // Breadth of a rectangle
    
    };

    Explanation:
    The class keyword is used to create a class followed by a class name ‘Rectangle‘. the public is one of the access specifiers that are used with the class members to determine their scope that is their visibility outside of the class. There are two public variables length and breadth (attributes). And at the end of braces, a semicolon is provided to end the class.


    C++ Objects

    Objects are real-world entities that have states and behavior. Example. bike, Lamp, pen, table, etc. An object is an instance of a class. It can be physical and logical.

    All the class members are accessed by creating an object of that class. Objects are created at runtime so is called runtime entity.

    • State: It is represented by attributes of an object that is the data value.
    • Behaviour: It represents the functionality that is the behaviour of an object. Example withdraw, deposit, etc.
    //creating an object of class Rectangle
    Rectangle rect;

    Here the type is of Rectangle type rect is a reference variable that refers to the instance of a Rectangle class.

    Let us understand class and objects in C++ through an example.

    Example of C++ Class and Object

    #include <iostream>
    using namespace std;
    
    class StudentDetail   //class
    {
       public:    // Access specifier
          int stID;
          string stName;
    };
    
    int main()
    {
       // Create an instance (object) of StudentDetail
       StudentDetail stObj;
    
       // Accessing members with dot operator
       stObj.stID = 32;
       stObj.stName = "Steve Rogers";
    
       // Displaying
       cout << stObj.stID << endl;
       cout << stObj.stName;
    
       return 0;
    }

    Output:

    32
    Steve Rogers


    Example: C++ multiple objects with methods

    #include <iostream>
    using namespace std;
    
    //Car class
    class Car
    {
       public:
           string brand;
           int year;
    
       void carInfo(string br, int y)
       {
          brand = br;
          year = y;
       }
    
       void display()
       {
          cout << brand << "  " << year << endl;
       }
    };
    
    int main()
    {
       // Create two objects of Car class
       Car obj1;
       Car obj2;
    
       obj1.carInfo("BMW", 1999);
       obj1.display();
    
       obj2.carInfo("Ford", 1969);
       obj2.display();
    
       return 0;
    }

    Output:

    BMW 1999
    Ford 1969

    We created two objects (obj1, obj2) and call the methods present in the Car class with two separate objects by passing different values.