Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

C++ Abstract Class and Pure Virtual Function Example

C++ Abstract Class and Pure Virtual Function Example

✅ C++ Program: Abstract Class and Pure Virtual Functions

#include <iostream>
using namespace std;

// Abstract class
class Animal {
public:
    // Pure virtual function
    virtual void sound() = 0;
};

// Derived class Dog
class Dog : public Animal {
public:
    void sound() override {
        cout << "Dog barks ๐Ÿถ\n";
    }
};

// Derived class Cat
class Cat : public Animal {
public:
    void sound() override {
        cout << "Cat meows ๐Ÿฑ\n";
    }
};

int main() {
    // Animal a;   ❌ ERROR: object of abstract class not allowed

    Animal *ptr;   // ✅ Abstract class pointer

    Dog d;
    Cat c;

    ptr = &d;
    ptr->sound();   // Calls Dog’s version

    ptr = &c;
    ptr->sound();   // Calls Cat’s version
}
  

๐Ÿ“˜ Explanation:

This program demonstrates the use of abstract classes and pure virtual functions in C++. Key points:

  • Animal is an abstract class because it has a pure virtual function sound().
  • You cannot create objects of abstract classes.
  • You can create pointers of abstract class type and point them to derived objects.
  • Runtime polymorphism ensures the correct function is called based on the object assigned.

๐Ÿงพ Sample Output:

Dog barks ๐Ÿถ
Cat meows ๐Ÿฑ
  

๐Ÿ”‘ Keywords:

C++ abstract class, pure virtual function, runtime polymorphism, OOPs in C++, C++ class hierarchy

๐Ÿ“Œ Hashtags:

#CPlusPlus #AbstractClass #Polymorphism #OOP #CppInterview #VirtualFunctions

๐Ÿ” Search Description:

This C++ program demonstrates abstract classes and pure virtual functions using Animal, Dog, and Cat classes. Explains runtime polymorphism with sample output.

Comments

Popular Posts

๐ŸŒ™