A basic C++ program includes headers, uses the standard namespace, and defines the main
function as the entry point.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
A basic C++ program includes headers, uses the standard namespace, and defines the main
function as the entry point.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
int a = 10;
float b = 5.5;
double c = 3.14;
char d = 'A';
bool e = true;
int age = 30;
const float PI = 3.1415;
int x;
cout << "Enter a number: ";
cin >> x;
cout << "You entered: " << x;
Arithmetic operators perform basic mathematical operations:
int a = 10, b = 3;
int sum = a + b;
int diff = a - b;
int prod = a * b;
int quot = a / b;
int mod = a % b;
Relational operators compare two values and return a boolean result:
bool eq = (a == b);
bool neq = (a != b);
bool gt = (a > b);
bool lt = (a < b);
bool ge = (a >= b);
bool le = (a <= b);
Logical operators are used to combine or invert boolean expressions:
bool and_op = (a > 0) && (b < 5);
bool or_op = (a > 0) || (b < 0);
bool not_op = !(a == b);
Bitwise operators operate on individual bits of integer types:
int and_bit = a & b;
int or_bit = a | b;
int xor_bit = a ^ b;
int not_bit = ~a;
int left_shift = a << 1;
int right_shift = a >> 1;
Assignment operators assign and update values:
int x = 5;
x += 3;
x -= 2;
x *= 4;
x /= 2;
x %= 3;
Increment and decrement operators increase or decrease a value by 1:
int i = 0;
i++;
++i;
i--;
--i;
Conditional (ternary) operator provides shorthand for if-else
:
int max = (a > b) ? a : b;
Scope resolution operator accesses global or class members:
::std::cout << "Hello";
Pointer and reference operators access memory and refer to variables:
int y = 10;
int* ptr = &y;
int& ref = y;
std::cout << *ptr << " " << ref;
Simple if condition:
int x = 5;
if (x > 0) {
std::cout << "x is positive";
}
if-else condition:
int x = -3;
if (x >= 0) {
std::cout << "x is non-negative";
} else {
std::cout << "x is negative";
}
if-else if-else chain for multiple conditions:
int x = 0;
if (x > 0) {
std::cout << "Positive";
} else if (x == 0) {
std::cout << "Zero";
} else {
std::cout << "Negative";
}
switch statement for handling multiple discrete values:
int x = 2;
switch (x) {
case 1:
std::cout << "One";
break;
case 2:
std::cout << "Two";
break;
default:
std::cout << "Other";
}
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
int j = 0;
while (j < 5) {
cout << j++ << " ";
}
do {
cout << j-- << " ";
} while (j > 0);
int add(int a, int b) {
return a + b;
}
Function overloading allows multiple functions with the same name but different parameter types or counts.
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
void greet(string name = "Guest") {
cout << "Hello, " << name << endl;
}
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
Basic pointer usage for storing and accessing the address of a variable:
int x = 10;
int* ptr = &x;
cout << *ptr; // Output: 10
A reference is an alias for an existing variable. Changing the reference updates the original value.
int x = 5;
int& ref = x;
ref = 10;
cout << x; // prints 10
Declare and initialize a fixed-size array:
int arr[3] = {1, 2, 3};
Access elements using indexing:
cout << arr[0];
Iterate through array elements using a for
loop:
for (int i = 0; i < 3; i++) {
cout << arr[i] << " ";
}
Update a value in the array:
arr[1] = 10;
Calculate the size of an array:
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Size: " << size;
Initialize all elements with zeros:
int arr[5] = {0};
Use range-based for
loop (C++11+):
for (int x : arr) {
cout << x << " ";
}
C-style string initialization and output:
#include <cstdio>
char name[] = "C-style";
printf("%s
", name);
Initializing and printing a std::string
:
#include <iostream>
#include <string>
using namespace std;
string modern = "C++ string";
cout << modern << endl;
Getting the length of a std::string
:
cout << modern.length() << endl;
Concatenating two strings:
string first = "Hello, ";
string second = "world!";
string result = first + second;
cout << result << endl;
Accessing characters in a string:
string word = "example";
cout << word[0] << " " << word.at(1) << endl;
Substring extraction:
string text = "abcdef";
string sub = text.substr(1, 3); // "bcd"
cout << sub << endl;
Finding a substring:
string text = "find the word";
size_t pos = text.find("word");
cout << pos << endl;
Comparing strings:
string a = "apple";
string b = "banana";
if (a < b) {
cout << "apple comes first" << endl;
}
Converting between C-style and std::string
:
string str = "sample";
const char* cstr = str.c_str();
Structures allow grouping of different data types into a single unit.
struct Person {
std::string name;
int age;
};
Person p = {"Alice", 30};
std::cout << p.name << " is " << p.age << " years old.";
A union is a user-defined type where all members share the same memory location. Only one member can hold a value at any given time.
union Data {
int i;
float f;
};
int main() {
Data d;
d.i = 10;
printf("d.i = %d
", d.i);
return 0;
}
Enums define a set of named integer constants for better code readability and maintainability:
enum Color { RED, GREEN, BLUE };
Color c = GREEN;
Allocate and deallocate a single integer using new
and delete
:
int* p = new int;
*p = 100;
delete p;
Allocate and deallocate a dynamic array using new[]
and delete[]
:
int* arr = new int[5];
arr[0] = 10;
delete[] arr;
class Animal {
public:
void speak() {
cout << "Sound";
}
};
Animal a;
a.speak();
class MyClass {
public:
MyClass() {
cout << "Constructor";
}
~MyClass() {
cout << "Destructor";
}
};
class Test {
private:
int secret;
public:
void set(int s) { secret = s; }
};
class Animal {
public:
void speak() { cout << "Animal"; }
};
class Dog : public Animal {};
class Base {
public:
virtual void show() { cout << "Base"; }
};
class Derived : public Base {
public:
void show() override { cout << "Derived"; }
};
class Shape {
public:
virtual void draw() = 0; // pure virtual
};
class Complex {
int real, imag;
public:
Complex(int r, int i) : real(r), imag(i) {}
Complex operator + (const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
};
class Box {
int width;
friend void printWidth(Box);
};
namespace ns {
void func() { cout << "Namespace"; }
}
ns::func();
try {
throw 20;
} catch (int e) {
cout << "Exception: " << e;
}
Includes containers, algorithms, and iterators. Examples: vector, map, set, queue, stack.
#include <vector>
vector<int> v = {1, 2, 3};
v.push_back(4);
for (int x : v) cout << x << " ";
#include <map>
map<string, int> m;
m["age"] = 30;
cout << m["age"];
#include <set>
set<int> s;
s.insert(1);
s.insert(2);
for (int x : s) cout << x;
#include <queue>
queue<int> q;
q.push(10);
q.pop();
#include <algorithm>
vector<int> v = {3, 1, 2};
sort(v.begin(), v.end());
template <typename T>
T add(T a, T b) {
return a + b;
}
auto sum = [](int a, int b) { return a + b; };
cout << sum(3, 4);
#include <fstream>
ofstream out("file.txt");
out << "Hello";
out.close();
double d = 3.5;
int i = static_cast<int>(d);
#define PI 3.14
#include <iostream>
class Example {
mutable int x;
public:
void set(int val) const {
x = val; // allowed
}
};
inline int square(int x) {
return x * x;
}
#include <memory>
auto ptr = std::make_shared<int>(10);
vector<int> a = {1, 2};
vector<int> b = std::move(a);