DSA 100 Days of Learning

 DSA

LANGUAGE OPTED - C++

                      DAY-1                    



1. Check Even and Odd:-

if (num & 1)

 cout << "Odd"

else

cout << "Even";

  • Even numbers have a least significant bit (LSB) of 0.
  • Odd numbers have an LSB of 1.

Example:

  • For num = 6:
    • Binary of 6 is 0110.
    • 6 & 1 results in 0110 & 0001 which equals 0000 (0 in decimal).
    • Since the result is 0, the else block executes, indicating that 6 is even

2. Functions in C++ :-

In C++, it's a good practice to define functions before the main() function. However, if you define a function after the main() function, you need to declare it before main().

#include <iostream>
using namespace std;

void printLine(); 

int main() {
    printLine(); // Function call
    return 0;
}

void printLine() {
    cout << "Have a good day!";
}

3. Vector STL in C++ :-

a) Sum of array. Array size declared by user at run-time :-

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

// Function to print the elements of the vector
void print(const vector<int>& x) {
    cout << "The array is: ";
    for (auto it : x) {
        cout << it << " ";
    }
    cout << endl;
}

int main() {
    vector<int> a;
    int sum = 0, n;

    // Input the size of the vector
    cout << "Enter the size of the array/VECTOR: ";
    cin >> n;

    // Input the elements of the vector
    cout << "Enter the elements: ";
    for (int i = 0; i < n; ++i) {
        int x;
        cin >> x;
        a.push_back(x);
    }

    // Print the elements of the vector
    print(a);

    // Calculate the sum of the elements
    for (const auto& val : a) {
        sum += val;
    }

    // Output the sum of the elements
    cout << "The sum of the array is: " << sum << endl;
    a.clear();
    return 0;
}

Pass by Reference:  void print(const vector<int>& x) instead of void print(vector<int>x) 

  • When you pass the vector by reference, no copy is made.
  • Instead, the function receives a reference to the original vector.
  • Adding const ensures that the function does not modify the vector, providing both safety and clarity.
  • This is much more efficient, as it avoids the overhead of copying the entire vector





Comments