Pages

Wednesday, April 30, 2025

Check ODD or Even (Bitwise Way) in C++

#include <iostream>

using namespace std;



void oddOrEven(int num) {

    if((num & 1)) {

        cout << "even\n";

    } else {

        cout << "odd\n";

    }

}



int main()

{

    

    oddOrEven(5);

    oddOrEven(8);

    

    return 0;

}

Practice questions of Bitwise Operators in C++

 #include <iostream>

using namespace std;


int main()

{

    // Bitwise Operators

    

    // Predict output of ~4

    cout << (~4) << endl;

    

    // Predict output of 8 >> 1

    cout << (8 >> 1) << endl;

    return 0;

}

Bitwise Shift Operators in C++

#include <iostream>

using namespace std;


int main()

{

    

    //Bitwise Shift Operators - Left Shift ( << )

    // Note:- a * 2^b

    cout << (7 << 2) << endl;

    

    // Bitwise Shift Operatr - Right Shiift ( >> )

    // Note:- a/2^b

    cout << (7 >> 2) << endl;

    

    return 0;

}

One's complement in Bitwise Operators in C++

 #include <iostream>

using namespace std;


int main()

{

    //Bitwise operators - One's Complement

    cout << (~6) << endl;

    cout << (~0) << endl;    


    return 0;

}

3Sum Problem (Vectors Topic) in C++ using Two-Pointer Approach Solution by Apna college

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans; // vector declaration of ans
       
        int n = nums.size(); // i got this correct
       

        sort(nums.begin(), nums.end()); // sorts the array

        for(int i=0; i<n; i++) {
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int j = i+1, k = n-1;

            while(j<k) {
                int sum = nums[i]+nums[j]+nums[k];
                if(sum > 0) {
                    k--;
                } else if(sum < 0) {
                    j++;
                } else {
                    ans.push_back({nums[i], nums[j], nums[k]});
                    j++; k--;

                    while(j < k && nums[j] == nums[j-1]) j++;
                }
            }
        }

        return ans;
    }
};

Sunday, April 27, 2025

Set mismatch in C++ (Assignment) incld

 class Solution {

public:
    vector<int> findErrorNums(vector<int>& nums) {
        int n = nums.size(); // size of array

        vector<int> count(n+1, 0); // to store frequency

        for(int i=0; i<n; i++) { // traverse array
            count[nums[i]]++; // increase count
        }

        int duplicate = 0, missing = 0;

        for(int i=1; i<=n; i++) { // from 1 to n
            if(count[i] == 2) duplicate = i;
            if(count[i] == 0) missing = i;
        }

        return {duplicate, missing};
    }
};



I faced difficulties while working on.. 1. finding the size of array:- nums.size(); is the correct syntax.
2. to store frequency of arrays:- vector<int> count(n+1, 0).
3. Traverse Array:- (int i=0; i<n; i++) // traverses array
                       count[nums[i]]++; // increases the count of traverse

4. in Leetcode or Coding interviews, always:- return {duplicate, missing};

Saturday, April 26, 2025

2D Array Vectors in C++ (2)

 #include <iostream>

#include <vector>

using namespace std;


int main()

{

    vector<int> vec;

    

    

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

        vec.push_back(i);

    }

    

    cout << vec.size() << endl;

    cout << vec.capacity() << endl;

    return 0;

}

2D Array Vectors in C++

 #include <iostream>

#include <vector>

using namespace std;


int main()


{

    vector <vector<int>> matrix = {

        {1,2, 3}, 

        {4, 5, 6},  // can make it {4, 5}

        {7, 8, 9}   // can make it {6}

    };


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

        for(int j=0; j<matrix[i].size(); j++) {

            cout << matrix[i][j] << " ";

            

        }

        

        cout << endl;

    }

    

    return 0;

}

Pair Sum in Vectors in C++

 #include <iostream>

#include <vector>

using namespace std;


vector<int> pairSum(vector<int> arr, int target) {

    int st = 0, end = arr.size()-1;  // with vectors we can substract but with arrays we can just pass

    int currSum = 0;

    vector<int> ans;

    

    

    while(st < end) {

        currSum = arr[st] + arr[end];

        if(currSum == target) {

            ans.push_back(st);

            ans.push_back(end);

            return ans;

        } else if(currSum > target) {

            end--;

            

        } else{

            st++;

        }

    }

    

    return ans; // this case will never come anyway

    

}


int main()


{

    vector<int> vec = {2, 7, 11, 15};

    int target = 9;

    vector<int> ans = pairSum(vec, target);

    cout << ans[0] << "," << ans[1] << endl;

    

    return 0;

    

}

Vector Implementation in Memory in C++

#include <iostream>

#include <vector>

using namespace std;


int main()

{

    vector<int> vec;

    cout << "size : " << vec.size() << endl;

    cout << "capacity : " << vec.capacity() << endl;

       

    

    

    vec.push_back(4); // changes vec size to 4

    cout << "size : " << vec.size() << endl;

    cout << "capacity : " << vec.capacity() << endl; // 8 (double of 4)

    

    vec.pop_back(); // size resets

    cout << "size : " << vec.size() << endl;

    cout << "capacity : " << vec.capacity() << endl;

    return 0;

    

}

Vectors in C++

 #include <iostream>

#include <vector>

using namespace std;


int main()

{

    vector<int> vec1(10, -1);

    cout << vec1.size() << "\n";

    

    

    // to access size of invidivual vectors

    

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

        cout << vec1[i] << " ";

    }

    

    cout << endl;

    return 0;

}

Friday, April 25, 2025

2D Dynamic Arrays in C++

#include <iostream>

using namespace std;


int main()

{

    int row, cols;

    cout << "enter rows: ";

    cin >> row;

    

    cout << "enter cols: ";

    cin >> cols;

    

    int* *matrix = new int*[row];

    

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

        matrix[i] = new int[cols];

    }

    

    // data store

    int x = 1;

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

        for(int j=0; j<cols; j++) {

            matrix[i][j] = x;

            x++;

            

            cout << matrix[i][j] << " ";

        }

        

        cout << endl;

    }

    

    cout << matrix[2][2] << endl;

    cout << *( *(matrix+2) + 2) << endl;


    return 0;

}

Thursday, April 24, 2025

Memory Leaks in C++

 #include <iostream>

using namespace std;


int* func() {

    

    int *ptr = new int;

    *ptr = 1200;

    cout << "ptr points to " << *ptr << endl;

    

    return ptr;

    

}

int main() {

    int *x = func();

    cout << *x << endl;

    

    return 0;

}


Dynamic Memory Allocation - Vectors in C++

#include <iostream>

using namespace std;


void funcInt() {

    int *ptr = new int;

    *ptr = 5;

    cout << *ptr << endl;   

    delete ptr;  -> deletes dynamically memory allocated to prevent memory leaks.

}


void func() {

    int size;

    cin >> size;


    int *arr = new int[size];


    int x = 1;

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

        arr[i] = x;

        cout << arr[i] << " ";

        x++;

    }

    cout << endl;


    delete[] arr; // correctly deallocating dynamic array

}


int main() {

    funcInt();

    func();

    return 0;

}


Wednesday, April 23, 2025

Check how many lowercase vowels occured in C++

 #include <iostream>

#include <cstring>





int main()

{


#include <iostream>

using namespace std;


bool isVowel(char ch) {

    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';

}


void countLowercaseVowels(string word) {

    int vowelCount = 0;


    for (char ch : word) {

        if (isVowel(ch)) {

            vowelCount++;

        }

    }


    cout << "Number of lowercase vowels in \"" << word << "\": " << vowelCount << endl;

}


int main() {

    string input;

    cout << "Enter a word: ";

    cin >> input;


    countLowercaseVowels(input);


    return 0;

}


return 0;

}

Tuesday, April 22, 2025

String Member Functions in C++

 #include <iostream>

#include <cstring>

using namespace std;


int main()

{

    // string str = "apna college";

    string str = "java, c++ and python & c++ with c++ magic";

    

    // cout << str.length() << endl;

    // cout << str[2] << endl;

    // cout << str.at(2) << endl;

    // cout << str.substr(5, 5) << endl;

    // cout << str.find("c++", 26) << endl;

    

    int idx = str.find("c++");

    cout << idx << endl;


    return 0;

}

Char Array (for each loop) in C++

#include <iostream>

#include <cstring>

using namespace std;



int main()

{

    string str = "apna college";

    

    

    // for(int i=0; i<str.length(); i++) {

    //     cout << str[i] << "-";

        

    // } cout << "\n";

        

        for(char ch : str) {

            cout << ch << ",";

        } cout << endl;

    

    // for(char ch : str) {

    //     cout << ch << ",";

    // }

    // cout << endl;


    return 0;

}

Monday, April 21, 2025

CStrings Functions in C++ (Strcat)

 #include <iostream>

#include <cstring>

using namespace std;



int main()

{

    char str1[100] = "abc";

    char str2[100] = "xyz";

    strcat(str1, str2);

    

    cout << str1 << endl;

    cout << str2 << endl;

    return 0;

}

CStrings Functions in C++ (Strcpy)

 #include <iostream>

#include <cstring>

using namespace std;



int main()

{

    char str1[100];

    // str1 = "apna college";

    char str2[100]="hello world";

    

    strcpy(str1, str2); // strcpy(dest, src)

    

    cout << str1 << endl;

    return 0;

}

Reverse of an Array in C++

 #include <iostream>

#include <cstring>

using namespace std;


void reverse(char word[], int n) {

    int st = 0, end = n-1;

    while(st < end) {

        swap(word[st], word[end]);

        st++;

        end--;

    }

}


int main()

{

    char word[] = "code";

    reverse(word, strlen(word));

    

    cout << "reverse = " << word << endl;


    return 0;

}

Sunday, April 20, 2025

Character Conversion to Uppercase in C++

 #include <iostream>

#include <cstring>

using namespace std;


void toUpper(char word[], int n) {

    

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

        char ch = word[i];

        if(ch >= 'A' && ch <= 'Z') { // uppercase

            continue;

        }

        else { // lowercase

            word[i] = ch - 'a' + 'A';

        }

    }

}


int main() {

    char word[] = "abcde";

    toUpper(word, strlen(word));


    cout << word << endl;

    return 0;

}

Input Char Arrays in C++

 #include <iostream>

#include <cstring>

using namespace std;



int main() {

    // char word[10];

    // cin >> word; //ignore whitespace

    

    // cout << "your word was : " << word << endl;

    // cout << "length : " << strlen(word) << endl;

    

    char sentence[30];

    cin.getline(sentence, 30, '*');

    

    cout << "your word was : " << sentence << endl;

    cout << "length : " << strlen(sentence) << endl;


    return 0;

}

Character Arrays in C++

#include <iostream>

#include <cstring>

using namespace std;



int main() {

    char work[50] = {

        'h', 'e', 'l', 'l', 'o', '\0'

    };

    

    cout << strlen(work) << endl;


    return 0;

}

Saturday, April 19, 2025

Does ChatGPT actually help us GROW? Here's what I think..

 Bro, not at all — in fact, the opposite is true.

You asking questions, even after thinking for 1–2 hours, means you're doing exactly what a real programmer should do.


🧠 Here's the truth about growth as a coder:

What You're Doing What It Actually Means
Spending 1–2 hours on one problem You’re training your brain to think logically — that’s how real problem-solving develops.
Asking for help after trying You're not giving up — you're being smart and learning faster.
Wanting to understand mistakes That’s how you avoid repeating them — it’s a shortcut to mastery.
Feeling unsure if asking = weakness It’s actually a sign of humility + hunger to improve. No one grows in silence.

💡 Every great developer does this:

  • They Google stuff 24/7.

  • They read docs, watch tutorials, or ask others.

  • They get stuck, break things, fix them, repeat.

  • Even senior devs ask juniors or Stack Overflow when confused.


So, does asking slow your growth?

No. It speeds it up.

But yeah — make sure:

  • You try first (which you're already doing ✅),

  • You reflect on the fix, not just copy-paste,

  • And maybe retype the code by hand once again for practice.


You’re 17. Spending time like this now? 💯 You're going to be a beast in 1–2 years.

Keep asking, keep breaking things, keep learning. I'm here for all of it.
You’re doing better than you think, Debadatta 🚀🧠💪

Friday, April 18, 2025

My Mistakes from Matrix Pointers (2D Arrays)

 while solving a problem in coding, and i forgot one thing:- how to calculate how many times it have occured a specific value in the array in a matrix , so does it mean as my teacher said to analyze and identify our weakness did i lack "logic?, or lacked practice?, i didnt knew the concept or forgot it ?, or whatever the case is" tell me please, (my CHATGPT Prompt)



Question 1 Mistakes-

SkillStatusWhy
Logic✅ Present
You started the solution, thought in steps, and assigned variables. That's logic.

Practice🚧 Needs Improvement
You likely forgot a small technique because you haven’t repeated it enough yet. Totally normal.

Concept Knowledge✅ Basic understanding
You know enough to attempt the solution. You’re not clueless—you’re learning.

Memory/Recall❗ Momentarily weak
You likely knew it once but couldn’t remember the exact syntax or loop pattern in that moment.



🔍 So to directly answer you:

No, you didn’t lack logic.
You didn’t completely forget the concept either.
What happened is: you’re still new, and you lacked practice recalling it on the spot.

That’s it. And that’s fixable with 15–20 mins of focused revision.


Concept revision-

#include <iostream>

using namespace std;

// matrix pointers in functions - assignment questions

// goal- to find how many times 7 occured in the array 


// best approach is used in this problem - staircase search method O(n+m)


bool search(int mat[][4], int n, int m, int key) {

    int i = 0, j = m-1; 

    

    while(i < n && j >= 0) {

        if(mat[i][j] == key) {

            cout << "found at cell (" << i << "," << j << ")\n";

            return true;

        } else if(mat[i][j] < key) {

            // down

            i++;

        } else {

            // left 

            j--;

        }

    }

    

    cout << "key not found\n";

    return false;

}


int main(){

    int matrix[4][4] = {

        {10, 20, 30, 40},

        {15, 25, 35, 45},

        {27, 29, 37, 48},

        {32, 33, 39, 50}

    };

    

    search(matrix, 4, 4, 33);


    return 0;

}




Question 2 Mistakes/Learnings:-

💡 What I Lacked in My 2D Array Code (C++)

While writing a simple program to calculate the sum of the 2nd row in a 2D array, I initially made some mistakes. I later fixed them by improving my logic and focusing more on how 2D arrays actually work.

Here’s what I learned from my mistake:


❌ What I Did Wrong Initially

  • Used i for rows, thinking it would help me sum the 2nd row. But I was iterating over rows instead of columns.

  • Tried something like if (arr[i] == 1) to check if I’m on the 2nd row. This doesn’t work because:

    • arr[i] is a whole 1D array (a row), and comparing it to 1 doesn’t make sense.

  • My loop structure and logic were flawed due to misunderstanding how 2D arrays are accessed in C++.


✅ What I Did Right Later

  • Fixed the row index to 1 (i.e. arr[1][j]) and looped over columns (j) to sum the second row.

  • Kept the total variable and summing logic inside the nums function for cleaner design.

  • Focused on column-wise traversal within a fixed row, which is key when working with matrices.


📌 What I Was Lacking

AreaReflection
PracticeNeeded more hands-on with nested loops and how 2D arrays work.
LogicThe core idea was there: I wanted the 2nd row. But my implementation logic was off.
ApproachI initially approached it with row iteration instead of directly targeting the row index and iterating over columns.

🔁 Key Takeaway

To access an entire row in a 2D array:
Fix the row index, loop through columns: arr[fixed_row][j]

To access a column:
Fix the column index, loop through rows: arr[i][fixed_col]


✅ Final Code That Worked

void nums(int arr[][3], int n, int m) { int total = 0; for(int j = 0; j < m; j++) { total += arr[1][j]; } cout << "Total Sum of 2nd Row : " << total << endl; }

I’ll keep practicing more problems on 2D arrays and update my blog with what I learn, so I don't repeat the same mistakes. Small tweaks in logic and approach can make a big difference.

— Debadatta Patra


QUESTION 3:-(LEANRINGS)

❌ What You Lacked:

  1. Wrong logic – You used if(arr[i][j] == arr[j][i]) – not needed.

  2. Used int transpose like an array – but it’s just an int, not a matrix.

  3. Tried to print a matrix with cout << transpose – doesn't work like that.

  4. Tried in-place transpose on a non-square matrix – not possible, need a new matrix.


✅ What You Should Do:

  • Remove the if condition.

  • Use a new 2D array to store the transposed matrix.

  • Loop through and print the matrix properly.



⚠️ 1. Misunderstood what "transpose" actually means

You did:

cpp
if(arr[i][j] == arr[j][i])

⬇️
That’s checking if the element and its transpose are equal, which isn’t required.

✅ Fix: Transposing means swapping arr[i][j] with arr[j][i]no condition needed.


⚠️ 2. Used an undefined variable as if it were a 2D array

You wrote:

cpp
int transpose; arr[i][j] = transpose[j][i];

Issues:

  • transpose is just an int, not an array.

  • You tried to use it like a matrix → transpose[j][i] → ❌ invalid.


⚠️ 3. Wrong output method

You wrote:

cpp
cout << "transposed array : " << transpose << endl;

Problems:

  • transpose is not a matrix here — it’s just an undefined scalar.

  • Even if it were a matrix, you can't print it like that.


⚠️ 4. Tried to transpose a non-square matrix in-place

You declared a 2x3 matrix:

cpp
int arr[2][3] = { {3, 4, 5}, {6, 7, 8} };

And tried to modify arr in place, which won’t work because the transposed matrix has different dimensions: it should be 3x2.

✅ Fix: Create a new matrix to store the transpose.


✅ In Short — What You Missed:

MistakeWhy it’s wrongFix
Used if(arr[i][j] == arr[j][i])Transpose doesn’t need conditionalsJust assign directly
Used int transpose;Not a matrixDefine int transpose[m][n];
Used transpose[j][i]Used a scalar like an arrayDeclare a 2D array
Tried to do in-place transpose of 2x3 matrixCan’t do in-place for non-squareUse another matrix
Printed matrix like a variableInvalid output formatLoop over the matrix to print

Correct Code: #include <iostream>

using namespace std;




void transpose(int arr[][3], int n, int m) {

    

    // lacked this part of code

    int transposed[3][2]; // since original is 2x3, transposed will be 3x2

    

    // rows

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

        // columns

        for(int j=0; j<m; j++) {

            transposed[j][i] = arr[i][j];

        }

    }

    

    cout << "transposed array : " << endl;

    

    // lacked this part of logic

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

        for(int j=0; j<n; j++) {

            cout << transposed[i][j] << " ";

        }

        cout << endl; // for 3x2 positioning

    }

}


int main() {

    int arr[2][3] = {

        {3, 4, 5}, 

        {6, 7, 8}

    };


    transpose(arr, 2, 3);

    

    return 0;

}  

Matrix Pointers in Functions in C++

 #include <iostream>

using namespace std;

// matrix pointers in functions


void func(int mat[][4], int n, int m) {

    // cout << "0th row ptr " << mat << endl;

    // cout << "1st row ptr " << mat+1 << endl;

    // cout << "2nd row ptr " << mat+2 << endl;

    

    // cout << "0th row value " << *mat << endl;

    // cout << "1st row value " << *mat+1 << endl;

    // cout << "2nd row value " << *mat+2 << endl;

    

    cout << *(*(mat + 2) + 2) << endl;

}


void func2(int (*mat)[4], int n, int m) {

    

}


int main()

{

    int mat[4][4] = {{1,2,3,4},

                    {5, 6, 7, 8},

                    {9, 10, 11,12},

                    {13,14,15,16}};


    func(mat, 4, 4);



    return 0; 

}



OUTPUT-


11

Thursday, April 17, 2025

Search in Sorted matrix(code) in C++ (2D Arrays)

#include<iostream>
using namespace std;

bool search(int arr[][4], int n, int m, int key) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == key) {
                cout << "found at cell [" << i << "][" << j << "]" << endl;
                return true;
            }
        }
    }
    cout << "no keys are found" << endl;
    return false;
}

int main() {
    int arr[4][4] = {
        {10, 20, 30, 40},
        {22, 45, 35, 36},
        {34, 33, 64, 92},
        {23, 39, 87, 67}
    };

    search(arr, 4, 4, 64);  // rows = 4, cols = 4, key = 33

    return 0;
}


Facing some errors-
1. Not able to identify correct position of row and column.

Mistakes done while writing this code-

🧠 Key Fixes (While Keeping Your Style):

IssueFix
int arr[10] = {{...}};Changed to int arr[4][4] = {...};
int m; used but not initializedAdded int m = 4;
if (int arr[i][j] == n)Changed to if (arr[i][j] == n)
Closing ) in last rowFixed to }
search(4, 4, 33);Changed to search(arr, 4); and passed key via n parameter
else prints "no keys are found" every loopKept, but note it will print many times unless key is found early

Sunday, April 13, 2025

2D Array in C++

 #include <iostream>

using namespace std;
// 2d Array
int main() {
    int arr[3][4];
    int n = 3, m = 4;  // 3.4 = 12 values
   
        // input values
        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) {
                cin >> arr[i][j];
            }
        }

        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) {
                cout << arr[i][j] << " ";
            }
            cout << endl;
        }
   
    return 0;
}


OUTPUT-
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12


Assignment Homework in Insertion Sorting in C++ (DOUBT)

 #include <iostream>

using namespace std;


// insertion sort- assignment


void insertSort(int arr[], int n) {

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

        int curr = arr[i];  // Forgot to Declare

        int prev = i-1;  // Forgot to Declare

        while(prev >= 0 && arr[prev] > curr) {

            swap(arr[prev], arr[prev+1]);

            prev--;

        }

        arr[prev+1] = curr;

   }

}


void printArray(int arr[], int n) {

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

        cout << arr[i] << " ";

    }

    cout << endl;

}


int main() {

    int arr[10] = {3, 6, 2, 1, 8, 7, 4, 5, 3, 1};

    

    insertSort(arr, 10);

    printArray(arr, 10);

    

    return 0;

}

Assignment Homework in Selection Sort in C++

 #include <iostream>

#include <algorithm>

using namespace std;


//  algo-hw- bubblesort-1


// void bubbleSort(int arr[], int n) {

//     for(int i=0; i < n-1; i++) {

//         for(int j=0; j < n-i-1; j++) {

//             if(arr[j] > arr[j+1]){

//                 swap(arr[j], arr[j+1]);

//             }

//         }

//     }

// }


void selectionSort(int arr[], int n){

    for(int i=0; i < n-i; i++) {

        int midIdx = i;

        for(int j=i+1; j<n; j++) {

            if(arr[j] < arr[midIdx]) {

                midIdx = j;

                

            }

            swap(arr[i], arr[midIdx]);

        }

    }

}


void printArray(int arr[], int n) {

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

        cout << arr[i] << " ";

    }

    cout << endl;

}


int main() {

    int arr[10] = {3, 6, 2, 1, 8, 7, 4, 5, 3, 1};

    

    selectionSort(arr, 10);

    printArray(arr, 10);

    

    return 0;

}

Assignment Homework in Bubblesort in C++

 #include <iostream>

#include <algorithm>

using namespace std;


//  algo-hw- bubblesort-1


void bubbleSort(int arr[], int n) {

    for(int i=0; i < n-1; i++) {

        for(int j=0; j < n-i-1; j++) {

            if(arr[j] > arr[j+1]){

                swap(arr[j], arr[j+1]);

            }

        }

    }

}


void printArray(int arr[], int n) {

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

        cout << arr[i] << " ";

    }

    cout << endl;

}


int main() {

    int arr[10] = {3, 6, 2, 1, 8, 7, 4, 5, 3, 1};

    bubbleSort(arr, 10);

    printArray(arr, 10);

    

    return 0;

}

Saturday, April 12, 2025

In-built sort in C++ (Makes Life easier!) - Common Mistake to avoid! include-> ?

 #include <iostream>

#include <algorithm>
using namespace std;

void print(int arr[], int n) {
    for(int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// void insertionSort(int arr[], int n) {
//     for(int i = 1; i < n; i++) {
//         int curr = arr[i];
//         int prev = i - 1;
//         while(prev >= 0 && arr[prev] < curr) {
//             arr[prev + 1] = arr[prev]; // shift instead of swap
//             prev--;
//         }
//         arr[prev + 1] = curr;
//     }
//     print(arr, n);
// }

// void countSort(int arr[], int n) {
//     int freq[100000]; // range
//     int minVal = INT8_MAX, maxVal = INT8_MIN;
//     //1st step - O(n)
//     for(int i=0; i<n; i++) {
//         freq[arr[i]]++;
//         minVal = min(minVal, arr[i]);
//         maxVal = max(maxVal, arr[i]);
//     }
//     //2nd step - O(range) = max - min
//     for(int i=minVal, j=0; i<=maxVal; i++) {
//         while(freq[i] > 0) {
//             arr[j++] = i;
//             freq[i]--;
//         }
//     }

//     print(arr, n);
// }

IN ASC. ORDER
int main() {
    int arr[8] ={1, 4, 1, 3, 2, 4, 3, 7};
    sort(arr, arr+8);  // included in #include <algorithm>

    print(arr, 8);
    return 0;
}
OUTPUT-
1 1 2 3 3 4 4 7




IN DESC. ORDER
int main() {
    int arr[8] ={1, 4, 1, 3, 2, 4, 3, 7};
    sort(arr, arr+8, greater<int>());  // included in #include <algorithm>

    print(arr, 8);
    return 0;
}


OUTPUT-
7 4 4 3 3 2 1 1

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...