if(a >= b && a >= c)
cout << a;
else if(b >= a && b >= c)
cout << b;
else
cout << c;
cout << max(a, max(b, c));
cout << max({a, b, c});
Note: max() needs #include <algorithm>.
if(a >= b && a >= c)
cout << a;
else if(b >= a && b >= c)
cout << b;
else
cout << c;
cout << max(a, max(b, c));
cout << max({a, b, c});
Note: max() needs #include <algorithm>.
Formula: (n * (n + 1)) / 2
int n = 100;
cout << (n * (n + 1)) / 2; // 5050
Note: If N is big, use long long (n * (n + 1) can overflow int).
long long n = 100000;
cout << (n * (n + 1)) / 2; // 5000050000
int n = 100, sum = 0;
for(int i = 1; i <= n; i++)
sum += i;
cout << sum;
int sum(int n){
if(n == 0) return 0;
return n + sum(n - 1);
}
Viva te 'swap without 3rd variable' khub jigges kore. Real code e std::swap use korbe.
int a = 10, b = 20;
int temp = b;
b = a;
a = temp;
a = a + b;
b = a - b;
a = a - b;
a = a ^ b;
b = a ^ b;
a = a ^ b;
int a = 10, b = 20;
swap(a, b);
Note: swap() needs #include <utility> and #include <algorithm>.
Note:
0 and 1 are not prime numbers.
2 is the smallest prime number.
A prime number is a number that can be divided only by 1 and itself.
bool isPrime(int n){
if(n < 2) return false;
for(int i = 2; i < n; i++){
if(n % i == 0) return false;
}
return true;
}
#include <iostream>
using namespace std;
int main() {
int n = 5;
bool prime = true;
if (n < 2)
prime = false;
// i*i means i × i.
// We check only up to √n.
// Example: n = 5
// i = 2 → 2×2 = 4 <= 5 → check 5 % 2
// i = 3 → 3×3 = 9 > 5 → stop
//
// We don't need to check after √n,
// because the factors after √n are already covered.
//
// Advantage: Fewer checks and faster execution.
// Time Complexity: O(√n)
// Space Complexity: O(1)
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
prime = false;
break;
}
}
if (prime)
cout << "Prime";
else
cout << "Not Prime";
return 0;
}
Note:
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two or more numbers is the largest number that divides all of them exactly (with no remainder).
It is found using the Euclidean Algorithm, which is very important for interviews.
int a = 12, b = 18;
while(b != 0){
int temp = b;
b = a % b;
a = temp;
}
cout << a; // 6
int gcd(int a, int b){
if(b == 0) return a;
return gcd(b, a % b);
}
cout << gcd(12, 18); // <numeric>, C++17
cout << __gcd(12, 18);
Note: gcd() needs #include <numeric>.
int gcd(int a, int b){
while(b != 0){
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main(){
int arr[] = {12, 18, 24, 30, 36};
int len = sizeof(arr) / sizeof(arr[0]);
int result = arr[0];
for(int i = 1; i < len; i++){
result = gcd(result, arr[i]);
}
cout << result; // 6
}
Note:
LCM (Least Common Multiple) is the smallest number that is a multiple of both numbers.
Example: LCM of 12 and 18 is 36.
Formula: LCM(a, b) = (a × b) / GCD(a, b)
int lcm(int a, int b){
int x = a, y = b;
while(y != 0){
int temp = y;
y = x % y;
x = temp;
}
int gcd = x;
return (a / gcd) * b;
}
int main(){
cout << lcm(12, 18); // 36
}
int gcd(int a, int b){
while(b != 0){
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int lcm(int a, int b){
return (a / gcd(a, b)) * b;
}
int main(){
int arr[] = {5, 10, 15, 30};
int len = sizeof(arr) / sizeof(arr[0]);
int result = arr[0];
for(int i = 1; i < len; i++){
result = lcm(result, arr[i]);
}
cout << "LCM " << result; // 30
}
Note:
Let number = abcd and total digits = n.
If aⁿ + bⁿ + cⁿ + dⁿ = original number, then it is an Armstrong number.
Example 1: 153 → 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Example 2: 1634 → 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634
int main() {
int n = 1634;
int len = to_string(n).length();
int temp = n;
int sum = 0;
while(temp != 0){
int digit = temp % 10;
int power = 1;
for(int i = 0; i < len; i++){
power = power * digit;
}
sum = sum + power;
temp = temp / 10;
}
if(sum == n) cout << "Armstrong";
else cout << "Not Armstrong";
}
int digit = temp % 10;
sum += (int)round(pow(digit, len));
Note: pow() returns a double, so a direct int cast can give a wrong answer (for example 124.99999 becomes 124). Use round() to be safe.
Definition:
A perfect number is a number whose sum of all divisors (excluding the number itself) is equal to the number.
Example: 6 = 1 + 2 + 3
int n = 28, sum = 0;
for(int i = 1; i <= n / 2; i++){
if(n % i == 0) sum += i;
}
if(sum == n) cout << "Perfect";
else cout << "Not Perfect";
Definition:
Two strings are anagrams if they have the same characters (same count) but in a different order.
Example: listen / silent
string a = "listen", b = "silent";
sort(a.begin(), a.end());
sort(b.begin(), b.end());
cout << (a == b ? "Anagram" : "Not Anagram");
Note: sort() needs #include <algorithm>.
A number is even if it is divisible by 2 (n % 2 == 0), otherwise it is odd.
int n = 7;
if(n % 2 == 0) cout << "Even";
else cout << "Odd";
// The last bit of an odd number is always 1
if(n & 1) cout << "Odd";
else cout << "Even";
Rule: a year is a leap year if it is divisible by 400, or divisible by 4 but not by 100.
Example: 2000 and 2024 are leap years; 1900 is not.
int y = 2024;
if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
cout << "Leap Year";
else
cout << "Not Leap Year";
Formula: n! = n × (n-1) × ... × 1, and 0! = 1.
Example: 5! = 120
int n = 5;
long long fact = 1;
for(int i = 1; i <= n; i++)
fact *= i;
cout << fact; // 120
long long fact(int n){
if(n <= 1) return 1;
return n * fact(n - 1);
}
Note: 20! is the largest factorial that fits in long long.
Each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13 ...
Formula: F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1
int n = 10, a = 0, b = 1;
for(int i = 0; i < n; i++){
cout << a << " ";
int next = a + b;
a = b;
b = next;
}
// 0 1 1 2 3 5 8 13 21 34
int fib(int n){
if(n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
long long memo[100];
long long fib(int n){
if(n <= 1) return n;
if(memo[n]) return memo[n];
return memo[n] = fib(n - 1) + fib(n - 2);
}
Take the last digit with % 10, add it to the result, then drop it with / 10.
int n = 1234, rev = 0;
while(n != 0){
int digit = n % 10;
rev = rev * 10 + digit;
n /= 10;
}
cout << rev; // 4321
A number is a palindrome if it reads the same backwards. Example: 121, 1331
int n = 121, temp = n, rev = 0;
while(temp != 0){
rev = rev * 10 + temp % 10;
temp /= 10;
}
cout << (rev == n ? "Palindrome" : "Not Palindrome");
string s = "madam";
bool ok = true;
for(int i = 0, j = s.size() - 1; i < j; i++, j--)
if(s[i] != s[j]) { ok = false; break; }
cout << (ok ? "Palindrome" : "Not Palindrome");
string s = "hello";
reverse(s.begin(), s.end());
cout << s; // olleh
string s = "hello";
int i = 0, j = s.size() - 1;
while(i < j){
swap(s[i], s[j]);
i++; j--;
}
Note: reverse() needs #include <algorithm>.
string s = "Programming";
int count = 0;
for(char c : s){
c = tolower(c);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
cout << count; // 3
int n = 1234, sum = 0;
while(n > 0){
sum += n % 10;
n /= 10;
}
cout << sum; // 10
Divide by 2 repeatedly and read the remainders from bottom to top. Example: 13 = 1101
int n = 13;
string bin = "";
while(n > 0){
bin = char('0' + n % 2) + bin;
n /= 2;
}
cout << bin; // 1101
#include <bitset>
cout << bitset<8>(13); // 00001101
string b = "1101";
int dec = 0;
for(char c : b)
dec = dec * 2 + (c - '0');
cout << dec; // 13
int arr[] = {12, 35, 1, 10, 34, 1};
int first = INT_MIN, second = INT_MIN;
for(int x : arr){
if(x > first){
second = first;
first = x;
} else if(x > second && x != first){
second = x;
}
}
cout << second; // 34
vector<int> v = {1, 2, 2, 3, 4, 4, 5};
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
// 1 2 3 4 5
set<int> s(v.begin(), v.end()); // keeps one of each, sorted
Every C++ program starts running from main(). Header files bring in library code, and using namespace std; lets us write cout instead of std::cout.
#include <iostream> // header for input / output
using namespace std; // use names from std without std::
int main() { // execution starts here
int age;
cout << "Enter age: ";
cin >> age; // input
cout << "Age is " << age << endl; // output
return 0; // 0 = program ended successfully
}
>> (extraction), cout uses << (insertion).endl adds a new line and flushes the buffer; "\n" only adds a new line (faster).| Type | Size (typical) | Range / Use |
|---|---|---|
| bool | 1 byte | true / false |
| char | 1 byte | -128 to 127, one character |
| int | 4 bytes | about ±2.1 × 109 |
| long long | 8 bytes | about ±9.2 × 1018 |
| float | 4 bytes | ~7 decimal digits |
| double | 8 bytes | ~15 decimal digits |
| string | varies | text (std::string) |
cout << sizeof(int) << endl; // 4
cout << sizeof(long long) << endl; // 8
cout << INT_MAX << endl; // 2147483647 (needs <climits>)
Type casting: (double)a / b or static_cast<double>(a) / b gives a decimal result; a / b with two ints drops the fraction.
A pointer stores the memory address of another variable. & gives an address, * reads the value at an address (dereference).
p holds the address of x, so *p gives the value of x
int x = 10;
int *p = &x; // p stores the address of x
cout << p; // address, e.g. 0x7ffe10
cout << *p; // 10
*p = 20; // changes x through the pointer
cout << x; // 20
int *q = nullptr; // points nowhere (always initialise pointers)
int arr[] = {10, 20, 30};
int *p = arr; // array name = address of first element
cout << *(p + 1); // 20 (pointer arithmetic)
A reference is another name (alias) for an existing variable.
int x = 10;
int &r = x; // r is another name for x
r = 50;
cout << x; // 50
| Reference | Pointer |
|---|---|
| Must be initialised when declared | Can be declared without a value |
| Cannot be null | Can be nullptr |
| Cannot be changed to refer to another variable | Can point to another address later |
| No special syntax to access (r) | Needs * to access (*p) |
Call by value passes a copy, so changes inside the function do not affect the caller. Call by reference passes the variable itself.
void byValue(int a) { a = 100; }
void byReference(int &a) { a = 100; }
void byPointer(int *a) { *a = 100; }
int main() {
int x = 1;
byValue(x); cout << x; // 1 (copy changed)
byReference(x); cout << x; // 100
x = 1;
byPointer(&x); cout << x; // 100
}
Tip: pass large objects as const T& to avoid copying and to stop accidental changes.
Several functions with the same name but different parameter lists (number or type). The compiler picks the right one at compile time (compile-time polymorphism).
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
add(2, 3); // 5
add(2.5, 1.5); // 4.0
add(1, 2, 3); // 6
Note: a different return type alone is not enough to overload.
new allocates memory on the heap at run time; delete frees it. Forgetting delete causes a memory leak.
Local variables live on the stack, new allocates on the heap
int *p = new int(5); // single int on heap
delete p;
int n = 5;
int *arr = new int[n]; // array on heap
delete[] arr; // use delete[] for arrays
// Modern C++: smart pointers free memory automatically
unique_ptr<int> u = make_unique<int>(10); // needs <memory>
The Standard Template Library gives ready-made containers and algorithms.
vector<int> v = {3, 1, 2};
v.push_back(4); // add at end
sort(v.begin(), v.end()); // 1 2 3 4
cout << v.size(); // 4
for (int x : v) cout << x << " ";
map<string, int> age; // sorted by key
age["Rahim"] = 25;
age["Karim"] = 30;
for (auto &[name, a] : age)
cout << name << " " << a << endl;
if (age.count("Rahim")) cout << "found";
set<int> s = {5, 1, 5, 3}; // unique and sorted: 1 3 5
s.insert(2);
cout << s.count(5); // 1 = present
| Container | Lookup | Notes |
|---|---|---|
| vector | O(1) by index | Contiguous, push_back amortised O(1) |
| map / set | O(log n) | Red-black tree, keeps keys sorted |
| unordered_map / set | O(1) average | Hash table, no order |
| stack / queue | top/front O(1) | Adapters for LIFO / FIFO |
| priority_queue | top O(1), push O(log n) | Max-heap by default |
string s = "Hello World";
s.length(); // 11
s.substr(0, 5); // "Hello"
s.find("World"); // 6 (string::npos if not found)
s += "!"; // append
s.replace(0, 5, "Hi"); // "Hi World!"
toupper(s[0]); // single char to upper case
stoi("123"); // string → int
to_string(456); // int → string
getline(cin, s); // read a full line with spaces
const member function cannot modify the object.void counter() {
static int count = 0; // initialised only once
count++;
cout << count << " ";
}
// counter(); counter(); counter(); → 1 2 3
Templates let one function or class work with any data type (generic programming). The STL is built on templates.
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
getMax(3, 7); // 7
getMax(2.5, 1.5); // 2.5
getMax<char>('a', 'z');
Errors are thrown with throw and caught with try / catch, so the program does not crash.
int divide(int a, int b) {
if (b == 0) throw runtime_error("Division by zero");
return a / b;
}
try {
cout << divide(10, 0);
} catch (const exception &e) {
cout << "Error: " << e.what();
}
OOP (Object Oriented Programming) organises a program around objects that hold data (attributes) and behaviour (methods) together.
Class is the blueprint; object is a real instance created from it. Example: class Car → objects myCar, yourCar.
Encapsulation, Abstraction, Inheritance, Polymorphism
class Car {
public:
string brand; // attribute
int speed;
void drive() { // method
cout << brand << " is driving at " << speed << " km/h\n";
}
};
int main() {
Car c1; // object
c1.brand = "Toyota";
c1.speed = 80;
c1.drive();
}
A constructor has the same name as the class, no return type, and runs automatically when an object is created. A destructor (~ClassName) runs when the object is destroyed.
Student(const Student &s).class Student {
string name;
int roll;
public:
Student() : name("Unknown"), roll(0) {} // default
Student(string n, int r) : name(n), roll(r) {} // parameterised
Student(const Student &s) : name(s.name), roll(s.roll) {} // copy
~Student() { cout << name << " destroyed\n"; } // destructor
};
Student a; // default
Student b("Rahim", 7); // parameterised
Student c = b; // copy
Wrapping data and methods into a single unit (class) and hiding the data with private. Outside code uses public getters and setters, which can validate values.
class BankAccount {
private:
double balance = 0; // hidden
public:
void deposit(double amount) {
if (amount > 0) balance += amount; // validation
}
double getBalance() const { return balance; }
};
BankAccount acc;
acc.deposit(500);
// acc.balance = 1000000; // error: balance is private
cout << acc.getBalance(); // 500
| Specifier | Same class | Child class | Outside |
|---|---|---|---|
| public | ✔ | ✔ | ✔ |
| protected | ✔ | ✔ | ✘ |
| private | ✔ | ✘ | ✘ |
Note: in C++ class members are private by default; struct members are public by default.
A child (derived) class gets the members of a parent (base) class, so code is reused. It models an is-a relationship: a Dog is an Animal.
Single, multilevel, multiple and hierarchical inheritance
class Animal {
public:
void eat() { cout << "Eating\n"; }
};
class Dog : public Animal { // Dog inherits Animal
public:
void bark() { cout << "Barking\n"; }
};
Dog d;
d.eat(); // from Animal
d.bark(); // own method
Polymorphism means one name, many forms.
| Compile-time (static) | Run-time (dynamic) |
|---|---|
| Function overloading, operator overloading | Function overriding with virtual functions |
| Decided by the compiler | Decided while running (via vtable) |
| Faster | More flexible |
class Shape {
public:
virtual double area() { return 0; } // virtual = can be overridden
virtual ~Shape() {}
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() override { return 3.1416 * r * r; }
};
class Square : public Shape {
double a;
public:
Square(double a) : a(a) {}
double area() override { return a * a; }
};
Shape *s1 = new Circle(2);
Shape *s2 = new Square(3);
cout << s1->area(); // 12.56 → Circle's area()
cout << s2->area(); // 9 → Square's area()
Abstraction shows only the essential features and hides the details. Example: you press the brake without knowing how the brake system works.
In C++ a class with at least one pure virtual function (= 0) is an abstract class. It cannot be instantiated; child classes must implement the function.
class Payment { // abstract class
public:
virtual void pay(double amount) = 0; // pure virtual
};
class Bkash : public Payment {
public:
void pay(double amount) override { cout << "Paid " << amount << " by bKash\n"; }
};
// Payment p; // error: cannot create an abstract object
Payment *p = new Bkash();
p->pay(500);
| Abstract class | Interface |
|---|---|
| Can have both abstract and normal methods | Only method declarations (Java 8+ also allows default methods) |
| Can have fields / state and constructors | Only constants, no constructor |
| A class extends only one abstract class (Java/C#) | A class can implement many interfaces |
| Used for closely related classes (is-a) | Used for a capability (can-do), e.g. Comparable |
C++ has no interface keyword: a class with only pure virtual functions acts as an interface.
interface Flyable { void fly(); }
interface Swimmable { void swim(); }
class Duck implements Flyable, Swimmable {
public void fly() { System.out.println("Duck flies"); }
public void swim() { System.out.println("Duck swims"); }
}
this).class Student {
string name;
static int count; // shared
public:
Student(string name) {
this->name = name; // this-> separates member from parameter
count++;
}
static int total() { return count; }
};
int Student::count = 0; // define outside the class
Student a("A"), b("B");
cout << Student::total(); // 2
A friend function is not a member but can access private members. It is often used for operator overloading such as <<.
class Complex {
int re, im;
public:
Complex(int r = 0, int i = 0) : re(r), im(i) {}
Complex operator+(const Complex &o) const { // member operator
return Complex(re + o.re, im + o.im);
}
friend ostream& operator<<(ostream &out, const Complex &c) {
return out << c.re << " + " << c.im << "i";
}
};
Complex a(2, 3), b(1, 4);
cout << a + b; // 3 + 7i
| Letter | Principle | Meaning |
|---|---|---|
| S | Single Responsibility | A class should have only one reason to change. |
| O | Open / Closed | Open for extension, closed for modification (add new classes, do not edit old ones). |
| L | Liskov Substitution | A child object must work wherever the parent is expected. |
| I | Interface Segregation | Many small interfaces are better than one big one. |
| D | Dependency Inversion | Depend on abstractions (interfaces), not on concrete classes. |
A data structure is a way of organising and storing data so it can be used efficiently.
| Linear | Non-linear |
|---|---|
| Elements in a sequence | Elements in a hierarchy or network |
| Array, Linked List, Stack, Queue | Tree, Graph, Heap |
Static (fixed size, e.g. array) vs dynamic (grows at run time, e.g. linked list, vector).
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Linked List | O(n) | O(n) | O(1) at head | O(1) at head |
| Stack / Queue | O(n) | O(n) | O(1) | O(1) |
| Hash Table | — | O(1) avg | O(1) avg | O(1) avg |
| BST (balanced) | O(log n) | O(log n) | O(log n) | O(log n) |
| Heap | top O(1) | O(n) | O(log n) | O(log n) |
An array stores elements of the same type in contiguous memory. Access by index is O(1); inserting or deleting in the middle needs shifting, O(n).
Index-based access is O(1) because the address can be calculated
int arr[5] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]); // length = 5
// insert 99 at index 2 (shift right)
int a[6] = {10, 20, 30, 40, 50};
for (int i = 5; i > 2; i--) a[i] = a[i - 1];
a[2] = 99; // 10 20 99 30 40 50
int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2D array
A linked list is a chain of nodes; each node holds data and a pointer to the next node. Size can grow at run time and insert/delete at the head is O(1), but there is no random access.
head → 10 → 20 → 30 → 40 → NULL
struct Node {
int data;
Node *next;
Node(int d) : data(d), next(nullptr) {}
};
void insertHead(Node *&head, int x) {
Node *n = new Node(x);
n->next = head;
head = n;
}
void print(Node *head) {
for (Node *cur = head; cur; cur = cur->next)
cout << cur->data << " ";
}
Node* reverse(Node *head) { // very common interview question
Node *prev = nullptr;
while (head) {
Node *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
A stack is LIFO (Last In, First Out). Operations: push, pop, top/peek, isEmpty, all O(1).
Uses: function call stack, undo, browser back button, expression evaluation, balanced parentheses, DFS.
Stack removes the newest item, queue removes the oldest
bool isBalanced(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') st.push(c);
else {
if (st.empty()) return false;
char t = st.top(); st.pop();
if ((c == ')' && t != '(') || (c == '}' && t != '{') || (c == ']' && t != '['))
return false;
}
}
return st.empty();
}
// isBalanced("{[()]}") → true, isBalanced("(]") → false
int st[100], top = -1;
void push(int x) { if (top < 99) st[++top] = x; } // overflow check
int pop() { return top >= 0 ? st[top--] : -1; } // underflow check
A queue is FIFO (First In, First Out): insert at the rear (enqueue), remove from the front (dequeue).
rear = (rear + 1) % size.Uses: CPU scheduling, printer queue, BFS, buffering.
queue<int> q;
q.push(10); q.push(20); q.push(30);
cout << q.front(); // 10
q.pop(); // removes 10
cout << q.size(); // 2