C++ Programming Notes with Syntax
and Examples
1. Basics of C++
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
2. Data Types & Variables
int a = 5;
float b = 3.14;
char c = 'A';
bool flag = true;
3. Input/Output
int x;
cin >> x; // Input
cout << "Value: " << x; // Output
4. Operators
int a = 10, b = 3;
cout << a + b; // Arithmetic
cout << (a == b); // Relational
a += 5; // Assignment
5. Conditional Statements
if (a > b) {
cout << "a is greater";
} else {
cout << "b is greater";
}
6. Loops
// For Loop
for (int i = 0; i < 5; i++) {
cout << i;
}
// While Loop
int i = 0;
while (i < 5) {
cout << i;
i++;
}
// Do-While Loop
int i = 0;
do {
cout << i;
i++;
} while (i < 5);
7. Arrays
int arr[5] = {1, 2, 3, 4, 5};
cout << arr[2]; // Output: 3
8. Functions
int add(int x, int y) {
return x + y;
}
int main() {
cout << add(5, 3);
}
9. Pointers
int a = 10;
int* p = &a;
cout << *p; // Output: 10
10. Strings
string s = "Hello";
cout << s.length();
11. OOP - Class & Object
class Car {
public:
string brand;
void honk() {
cout << "Beep!";
}
};
int main() {
Car obj;
obj.brand = "Ford";
obj.honk();
}
OOP - Constructor
class Car {
public:
Car() {
cout << "Constructor called!";
}
};
OOP - Inheritance
class Animal {
public:
void sound() {
cout << "Animal sound";
}
};
class Dog : public Animal {};
int main() {
Dog d;
d.sound();
}
12. File Handling
#include <fstream>
ofstream fout("file.txt");
fout << "Writing to file";
fout.close();
13. STL - Vector
#include <vector>
vector<int> v = {1, 2, 3};
v.push_back(4);
STL - Map
#include <map>
map<string, int> age;
age["Alice"] = 25;