Pages

Saturday, May 31, 2025

Friends Pairing using Recursion in C++

 #include<iostream>

#include<string>
using namespace std;

int friendsPairing(int n) {
    if(n == 1 || n == 2) {
        return n;
    }

    // // single
    // friendsPairing(n-1);

    // // pair
    // (n-1) * friendsPairing(n-2)
    return friendsPairing(n-1) + (n-1) * friendsPairing(n-2);
}

int main() {
    cout << friendsPairing(4) << endl; // 10
return 0;

}

Remove Duplicates using Recursion in C++

 #include<iostream>

#include<vector>
#include<cmath>
using namespace std;

void removeDuplicates(string str, string ans, int i, int map[26]) {
    // Base case
    if(i == str.size()) {
        cout << "ans: " << ans << endl;
    return;
    }

    int mapIdx = (int)(str[i] - 'a');

    if(map[mapIdx]) { // duplicate
            removeDuplicates(str, ans, i+1, map);


    } else {// not duplicate
    map[mapIdx] = true;
    removeDuplicates(str, ans+str[i], i+1, map);
    }
}

int main() {
    string str = "appnnacollege";
    string ans = "";
    int map[26] = {false};



    removeDuplicates(str, ans,0, map);
return 0;

}

Friday, May 30, 2025

Book Library Management (University Question)

 #include <iostream>

#include <string>
#include <vector>
using namespace std;

// Library Book Management System

class Book {
private:
    string title;
    string author;

public:
    Book(string t, string a) {
        title = t;
        author = a;
    }
   

    // Constructor :
    string getTitle() {
        return title;
    }

    string getAuthor() {
        return author;
    }


    void showDetails() {
        cout << "Book: " << title << "\nAuthor: " << author << endl;
    }
};

class Library {
private:
    vector<Book> books;


public:


    // Add a book
    void addBook(string title, string author) {
        books.push_back(Book(title, author));
        cout << "Book added successfully.\n";
    }

    // Remove a book
    void removeBook(string title) {
        for(auto it = books.begin(); it <= books.end(); it++) {
            if(it->getTitle() == title) {
                books.erase(it);
                cout << "Book removed successfully.\n";
                return;
            }
        }

        cout << "Book not found.\n";
    }    

    // Show All Books
    void showAllBooks() {
        if(books.empty()){
            cout << "Library is empty.\n";
            return;
        }

        cout << "\nBooks in Library: \n";
        for(auto& book : books) {
            book.showDetails();

        }
    }


};

int main() {
    Library lib;

    lib.addBook("Book S1", "Deb");
    lib.addBook("Book S2", "Deb");
    lib.addBook("Book S3", "Deb");

    lib.showAllBooks();

    lib.removeBook("Book S2");

    lib.showAllBooks();


    return 0;

}

C. Create a C++ program that uses a function template to find the maximum value between two values of any data type.

#include <iostream>

using namespace std;


template<typename T>

T maxVal(T a, T b) {

    return (a>b) ? a : b;

    /*

    if (a > b) {

        return a;

    } else {

        return b;

    }

    */

    /*

    OR 

    return (a > b) ? a : b is same as if 

    (a > b)

    return a;

    else

    return b;

    */

}


int main() {

    int val1, val2;

    cout << "enter first value : ";

    cin >> val1;

    cout << "\nenter second value : ";

    cin >> val2;

    int findMax = maxVal(val1, val2);

    cout << findMax << " is the max value " << endl;

    return 0;

}

Thursday, May 29, 2025

A. Create a C++ program that demonstrates function overloading.

 #include <iostream>

#include <string>

#include <vector>

using namespace std;



// Function overloading - example



class Print {

public:

    void show(int x) {

        cout << "int : "<< x << endl;

    }





    void show(string str) {

        cout << "str: " << str << endl;

    }





    void show(string str2) { // <--- This is the problem ( can't put two functions
under a class when it comes to function overloading....

        cout << "str2: " << str2 << endl;

    }

};





int main() {

    Print ob1;



    ob1.show(45);

    ob1.show("apna college");

    ob1.show("Debadatta Patra");



    return 0;

}

D. Create a C++ class template named Pair that represents a pair of values. (University Topic of OOPs)

#include <iostream>

#include <string>

#include <vector>

using namespace std;


// D. Create a C++ class template named Pair that represents a pair of values. 


template <typename T>


class Pair {

private:

    T A1;

    T A2;

    

public:

    Pair(T val1,T val2) {

        A1 = val1;  // initialize first ehe private variable then the Public variable

        A2 = val2;


    }

    

    // display

    void display() {

        cout << "value A: " << A1 << " \nvalue B: " << A2 << endl;

    }

};





int main() {

    int x, y;

    cout << "enter first value : ";

    cin >> x;

        

    cout << "enter second value : ";

    cin >> y;

    

    Pair<int> class1(x, y);

    

    class1.display();

    

    return 0;

}

Merge Sort in C++ (university dsa topic)

 #include <iostream>

#include <vector>
using namespace std;

void merge(vector<int> &arr, int st, int mid , int end){  // O(n)
    vector<int> temp;
    int i = st, j = mid+1;


    // left to right half traversal
    while(i <= mid && j <= end) {
        if(arr[i] <= arr[j]) {
            temp.push_back(arr[i]);
            i++;a
        } else {
            temp.push_back(arr[j]);
            j++;
        }
    }


    while(i <= mid) {
        temp.push_back(arr[i]);
        i++;
    }


    while(j <= end) {
        temp.push_back(arr[j]);
        j++;
    }


   
    for(int idx=0; idx<temp.size(); idx++) {
        arr[idx+st] = temp[idx];
    }
}


void mergeSort(vector<int> &arr, int st, int end) {
    if(st < end) {
        int mid = st + (end-st)/2;

        mergeSort(arr, st,mid); // left half
        mergeSort(arr, mid+1, mid); // right half

        merge(arr, st, mid ,end);
    }
}

int main() {
    vector<int> arr = {12, 31, 35, 8, 32, 17};

    mergeSort(arr, 0, arr.size()-1); // arr.size()-1 => array ka last index)

    for(int val : arr) {
        cout << val << " ";
    }

    cout << endl;

    return 0;
}

Tuesday, May 27, 2025

Binary Search in C++ (University Topic)

#include <iostream>
using namespace std;

int binarySearch(int arr[], int size, int element) {

    int low, mid, high;
    low = 0;
    high = size-1;  // high last element thats why


    // Start searching
    while(low<=high) {

        mid = (low+high)/2;
        if(arr[mid]==element) {

            return mid;

    }
        if(arr[mid]<element) {
            low = mid+1;

        }
        else {
            high = mid-1;

        }
    }
    // Searching end

    return -1;

}


int main() {
    // Unsorted array for linear search
    // int arr[] = {1,2,3,4,5,5,6,432,432,4,2342,34};
    // int size = sizeof(arr)/sizeof(int);
    // Sorted array for binary search
    int arr[] = {1,3,5,56,64,73,123,225,444};
    int size = sizeof(arr)/sizeof(int);
    int element = 56;
    int searchIndex = binarySearch(arr, size, element);
    cout << "The element " << element << " was found at index " << searchIndex << endl;

    return 0;
}

Linear Search in C++ (University Topic)

 #include <iostream>

using namespace std;


int linearSearch(int arr[], int size, int element) {

    for(int i=0; i<size; i++) {

        if(arr[i]==element) {

         return i;   

        }

    }

    

    

    return -1;

}




int main() {

    int arr[] = {10, 23,45,56,43,53};

    int size = sizeof(arr)/sizeof(int);

    int element = 56;

    int searchResult = linearSearch(arr, size, element);

    

    cout << "The element " << element << " is at index " << searchResult << endl;

    


    return 0;

}

Tiling problem using Recursion in C++

 #include <iostream>

#include <vector>
using namespace std;

int tilingProblem(int n) { // 2xn
    if(n==0 || n==1) {
        return 1;
    }

    //vertical
    int ans1 = tilingProblem(n-1); // 2x(n-1)

    // horizontal
    int ans2 = tilingProblem(n-2); // 2x(n-2)

    return ans1+ans2;
}

int main() {

    int n = 3;

    cout << tilingProblem(4) << endl;

    return 0;
}


OUTPUT:
5

Monday, May 26, 2025

X to the Power N(Code) using Recursion in C++

 #include <iostream>

#include <vector>
using namespace std;

int pow(int x, int n) { // O(logn)
    if(n==0) {
        return 1;
    }

    int halfPow = pow(x, n/2);
    int halfPowSquare = halfPow * halfPow;


    if(n%2 != 0) {
        //odd
        return x * halfPowSquare;
    }
    return halfPowSquare;
}

int main() {
    cout << pow(2, 10) << endl;

    return 0;
}


OUTPUT:
1024

Last Occurence using Recursion in C++

 #include <iostream>

#include <vector>
using namespace std;

int lastOccur(vector<int> arr, int tar, int i) {
    if(i == arr.size()) {
        return -1;
    }

    int idxFound = lastOccur(arr, tar, i+1);
    if(idxFound == -1 && arr[i] == tar) {
        return i;
    }

    return idxFound;
}

int main() {
    vector<int> arr = {1, 2, 3, 3, 3, 4};
    cout << lastOccur(arr, 45, 0) << endl;  // 4
    return 0;
}

Friday, May 23, 2025

First Occurence using Recursion in C++

 #include <iostream>

#include <vector>
using namespace std;

int firstOccur(vector<int> arr, int i, int target) {
    if(i==arr.size()) {
        return -1;
    }


    if(arr[i] == target)
    {
        return i;
    }


    return firstOccur(arr, i+1, target);
}

int main() {
    vector<int> arr = {1, 2, 3, 3, 3, 4};
    cout << firstOccur(arr, 0, 4);
    return 0;
}

Check if Array Sorted using Recursion in C++

#include <iostream>
using namespace std;

bool isSorted(int arr[],int n, int i) {
    if(i == n-1) {
        return true;
    }

    if(arr[i] > arr[i+1]) {
        return false;
    }

    return isSorted(arr, n, i+1);

}


int main() {
    int arr1[5] = {1,2,3,4,5}; // sorted : 1
    int arr2[5] = {1,2,4,3,5}; // unsorted : 0


    cout << isSorted(arr2, 5, 0) << endl;
    return 0;
}

OUTPUT:
0

Nth Fibonacci (Code) Using Recursion in C++

 #include <iostream>

using namespace std;

int fibonacci(int n) {
    if(n == 0 || n == 1) {
        return n; // 0, 1
    }

    return fibonacci(n-1)+fibonacci(n-2);
}

int main() {
    cout << fibonacci(3) << endl;

    return 0;
}


OUTPUT:
2

Sum of N natural numbers using Recursion in C++

 #include <iostream>

using namespace std;


// sum of N natural numbers

int sum(int n) {
    if(n==1) {
        return 1;
    }

    return n+sum(n-1);
}

int main() {
   
    cout << sum(5) << endl;
    return 0;
}

Stack Overflow in C++

 #include <iostream>

using namespace std;


// stack overflow
void func() {
    cout << "function called..kaam\n";
    func();
}

int main() {
    func();
    return 0;
}

Thursday, May 22, 2025

Number in Decreasing order in Recursion in C++

 #include <iostream>

using namespace std;


// to print in decreasing order , n = 5
void print(int n) {
    if(n==0) {
        return;

    }
    cout << n << " "; // kaam
    print(n-1); // faith, next call
}

int main() {
    print(5);
    return 0;
}


OUTPUT:
5 4 3 2 1

Factorial in Recursion Memory in C++

 #include <iostream>

using namespace std;


// factorial
int factorial(int n) {
    if(n==0) { // base case - where solution is known (smallest problem)
        return 1;
    }


    return n * factorial(n-1);  // 6 * 5 * 4!
}

int main() {
    int ans = factorial(4); // initialize the answer
    cout << ans << endl; // display result
    return 0;
}

What is recursion? in C++

 Recursion:

A function that repeatedly calls itself.


CODE:

#include<iostream>

using namespace std;

// recursive function -> recursion..

void func() {
cout << "function call...work\n";

func(); // calls itself 

}


int main() {
func();

return 0;

}


OUTPUT:-

function call..work


function call..work


function call..work


function call..work


function call..work

...

.

..

infinite times, until a base case is declared(Smallest problem, where solution is known)..

Sunday, May 18, 2025

Object-Oriented Programming: Creating a Student Class from Person Base Class (Assignment Question 3)

 #include <iostream>

using namespace std;

class Person {
public:

    string name; // mistakes -> char name();
    int age; // mistakes -> int age();
};

class Student : public Person {
public:
     void displayStudentInfo(string id) {
        cout << "(" << name << "\", " << age << " ,\"" << id << "\")";  // in order to put double quotations please put \ then " so-> \" this is how it will work
        }
       
};



int main() {
    Student student;
    student.name = "\"Deb";
    student.age = 17;
    student.displayStudentInfo("S12345");

    return 0;
}

OUTPUT:
("Deb", 17 ,"S12345")

Bank Account Assigment Question in OOPs

 #include <iostream>

using namespace std;

class BankAccount {
private:
    int accNumber;
    float balance;

public:
    // Constructor
    BankAccount(int accNum, double bal) {
        accNumber = accNum;
        balance = bal;
    }

    // Deposit money
    void deposit(double amount) {
        balance += amount;
        cout << "Deposited: " << amount << endl;
    }

    // Withdraw money
    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: " << amount << endl;
        } else {
            cout << "You have insufficient balance." << endl;
        }
    }

    // Get current balance
    void getBal() {
        cout << "Your account balance: " << balance << endl;
    }
};

int main() {
    BankAccount raju(123456789, 1000.00);  // Account with ₹1000

    raju.deposit(200);     // Deposit ₹200
    raju.withdraw(500);    // Withdraw ₹500
    raju.getBal();         // Check balance

    return 0;
}


OUTPUT:
Deposited: 200 Withdrawn: 500 Your account balance: 700

Complex Number Class with Subtraction Operator Overloading in OOPs (Assignment Question 1)

 #include <iostream>

using namespace std;



// Complex Number Substraction Code using Operator Overloading


class Complex {

private: 

    int real, img;


public:    

    Complex(int r, int i) {

        real = r;

        img = i;

        

    }

    

    void showNum() {

        cout << real << " - " << img << "i\n";

    }

    

    

    // Operator Overloading 

    void operator-(Complex &c2) {  // &c2 is value of reference..

    

        int resReal = this->real - c2.real; // result of real

        int resImg = this->img - c2.img; // result of image

        Complex c3(resReal, resImg); // taking both objects of resReal , resImg.

        c3.showNum(); // display the result

    }

    

};




int main()

{   

    Complex c1(2, 4);

    Complex c2(1, 2);

    

    c1.showNum();

    c2.showNum();

    

    c1-c2;

    

    return 0;

}

Friday, May 16, 2025

Predicting the output of friend function and class in OOPs - 02

 #include <iostream>

using namespace std;

class Base
{
public:
    virtual void print() {
        cout << "Base\n";
    }
};

class Derived : public Base {
public:
    void print() {
        cout << "Derived\n";
    }


};
int main() {
    Base *b = new Derived();
    b->print();

    delete b;
    return 0;
}

Predicting the output of Friend class and function problem 1 in OOPs

 #include <iostream>

using namespace std;

class Parent {
public:
    Parent() {
        cout << "constructor of parent\n";
    }
    // destructor of Parent class
    ~Parent() {
        cout << "destructor of parent\n";
    }
};

class Child : public Parent {
public:
    Child() {
        cout << "constructor of child\n";
       
    }
     
    //Destructor of Child
    ~Child() {
        cout << "destructor of child\n";
    }


};

int main() {
    Child ch1;

    return 0;
}


OUTPUT:
constructor of parent
constructor of child
destructor of child
destructor of parent

Friend functions & class in OOPs

 #include <iostream>

using namespace std;

class A {
    string secret = "secret data";
    friend class B;
    friend void revealSecret(A &obj);
};

class B {  // becomes a friend class of A
public:
    void showSecret(A &obj) {
        cout << obj.secret << endl;
    }
};

void revealSecret(A &obj) {
    cout << obj.secret << endl;

}

int main() {
    A a1;
    B b1;

    // b1.showSecret(a1);
    revealSecret(a1);

    return 0;
}

Sunday, May 11, 2025

Static keyword : Static Object in OOPs

#include <iostream>
using namespace std;

class Example {
public:
    Example() {
        cout << "constructor..\n";
    }

    ~Example() {
        cout << "destructor..\n";
    }
};


int main() {
    int a = 0;
    if(a == 0) {
        static Example eg1;
    }

    cout << "code ending..\n";


    return 0;

} 


output:

constructor..

code ending..

destructor..

Static Keyword - Static Variable in OOPs (02)

 #include <iostream>

using namespace std;

class Example {
public:
    static int x; // remember to do it const, only way makes it work

};

int Example::x = 0;  // now main func, will share this same object of x.

int main() {
    Example eg1;
    Example eg2;
    Example eg3;
   
    cout << eg1.x++ << endl; // 0
    cout << eg2.x++ << endl; // 1
    cout << eg3.x++ << endl; // 2


    return 0;
}

Static Keyword - Static Variables in OOPs

 #include <iostream>

using namespace std;

void counter() {
    static int count = 0; // Static Variable

    count++;
    cout << "count : " << count << endl;
};

int main() {
    counter();
    counter();
    counter();

    return 0;
}

output:
count : 1
count : 2
count : 3

Pure Virtual Function in OOPs

 #include <iostream>

using namespace std;

// abstract class
class Shape {
public:
    virtual void draw() = 0; //abstract fnx, pure-virtual fnx
};

class Circle : public Shape {
public:
    void draw() {
        cout << "draw circle\n";
    }
};

class Square : public Shape {
public:
    void draw() {
        cout << "draw square\n";
    }
};

int main() {

    Circle c1;
    c1.draw();

    Square sq1;
    sq1.draw();


    return 0;
}

output:
draw circle
draw square

Inorder Traversal (uni topic) in c++

 #include <iostream> using namespace std; struct Node { int data; Node* left; Node* right; }; void inorder(Node* root) {  // major mi...