Skip to content

Repository files navigation

CPP (C++) Language

"Hello, my name is Sujit Tomar. I first learned C++ in 2021, and I'm still learning it today because I believe that continuous practice and staying updated with new knowledge are essential for growth."

CPP Boilerplate Code

#include<iostream>
#include<string>usingnamespacestd;intmain(){
return0;
}

Data Type

Summary of C++ Data Types

Data TypeDescriptionSize (Typical)Example
intInteger value (whole numbers)4 bytesint a = 10;
shortSmaller integer2 bytesshort b = 5;
longLarger integer4 or 8 byteslong c = 100000;
long longVery large integer8 byteslong long d = 100000000000LL;
unsignedNon-negative integer (used with any integer)Depends on typeunsigned int e = 25;
floatFloating-point number (decimal)4 bytesfloat f = 3.14f;
doubleDouble-precision floating-point number8 bytesdouble g = 3.14159;
long doubleExtended precision floating-point number10 or 12 byteslong double h = 2.718281828459;
charSingle character1 bytechar i = 'A';
unsigned charNon-negative character1 byteunsigned char j = 'B';
signed charSigned character1 bytesigned char k = 'C';
boolBoolean value (true or false)1 bytebool l = true;
std::stringSequence of characters (C++ string class)Depends on sizestd::string m = "Hello";
voidNo value or unknown type-void print() {}
PointerHolds memory address of a variableDepends on systemint* ptr = #

Key Differences Between long and long long

Featurelonglong double
SizeTypically 4 bytes (32-bit) or 8 bytes (64-bit) depending on the system.Always at least 8 bytes (64-bit)
RangeDepends on the system (on 32-bit systems: -2^31 to 2^31-1, on 64-bit systems: -2^63 to 2^63-1).Always from -2^63 to 2^63-1 for signed, 0 to 2^64-1 for unsigned.
PurposeUsed for larger integers than int, but may not be large enough on some systems.Used for integers requiring guaranteed 64-bit size.
GuaranteeNot guaranteed to be 64-bit on all platforms.Always guaranteed to be at least 64-bit.
When to use?Use when you need a larger range than int, but not as large as long long.Use when you need guaranteed 64-bit precision.

Example long and long long

#include<iostream>usingnamespacestd;intmain() {
long num1 = 2147483647; // maximum value for signed 32-bit long (on 32-bit systems)longlong num2 = 9223372036854775807; // maximum value for signed 64-bit long long
cout << "Value of num1 (long): " << num1 << endl;
cout << "Value of num2 (long long): " << num2 << endl;
return0;
}

Key Differences Between double and long double

Featuredoublelong double
SizeTypically 8 bytes (64 bits)Typically 8 bytes (MSVC) or 16 bytes (GCC)
PrecisionAround 15-16 decimal digitsAround 18-19 decimal digits or more
Range~ ±1.7 × 10³⁰Larger than double, depending on the system
Use CaseGeneral-purpose floating-point valuesHigher precision required (e.g., scientific calculations)
MemoryLess memory usage compared to long doubleUses more memory (if 16 bytes)

double Example

#include<iostream>usingnamespacestd;intmain() {
double num1 = 3.141592653589793;
cout << "Value of num1: " << num1 << endl;
return0;
}

long double Example

#include<iostream>usingnamespacestd;intmain() {
longdouble num2 = 3.14159265358979323846264338327950288419716939937510L;
cout << "Value of num2: " << num2 << endl;
return0;
}

Operator in CPP

  • Arithmetic Operators :- " +, -, *, /, % "
  • Assignment Operators :- " +=, -=, *=, /=, %= "
  • Relational Operators :- " > , >=, <, <= "
  • Logical Operators :- " >> && and || "
  • **Bitwise Operators :- "(AND) &, (OR) |, (XOR) ^, (NOT) ~, (Left shift) <<, (Right shift) >>"
  • Increment Operators :- " Prefix: ++x, Postfix: x++ "
  • Decrement Operators :- " Prefix: --x, Postfix: x--"

Conditionals Statement

"In C++, a conditional statement is a way to make decisions in a program. It allows the program to execute different blocks of code based on whether a certain condition is true or false. These conditions are usually based on comparing values., such as checking if a number is greater than another number or if a certain condition is met.

In simple terms, conditional statements help your program decide what to do next based on certain situations."

if Statement

syntax

if (condition) {
// code to be executed if condition is true
}

example

#include<iostream>usingnamespacestd;intmain() {
int x = 10;
if (x > 5) {
cout << "x is greater than 5" << endl;
}
return0;
}

if else Statement

syntax

if (condition) {
// Block of code that executes if condition is true
} else {
// Block of code that executes if condition is false
}

example

#include<iostream>usingnamespacestd;intmain() {
int x = 10;
if (x > 5) {
cout << "x is greater than 5" << endl;
} else {
cout << "x is 5 or less" << endl;
}
return0;
}

else if Statement

syntax

if (condition1) {
// Code block executed if condition1 is true
} elseif (condition2) {
// Code block executed if condition2 is true
} elseif (condition3) {
// Code block executed if condition3 is true
} else {
// Code block executed if none of the conditions are true
}

example

#include<iostream>usingnamespacestd;intmain() {
int x = 7;
if (x > 10) {
cout << "x is greater than 10" << endl;
} elseif (x > 5) {
cout << "x is greater than 5 but less than or equal to 10" << endl;
} elseif (x > 0) {
cout << "x is greater than 0 but less than or equal to 5" << endl;
} else {
cout << "x is less than or equal to 0" << endl;
}
return0;
}

Switch Statement

syntax

switch (expression) {
case value1:
// Code block executed if expression == value1break;
case value2:
// Code block executed if expression == value2break;
case value3:
// Code block executed if expression == value3break;
// Optionally, more cases...default:
// Code block executed if no case matches the expressionbreak;
}

example

#include<iostream>usingnamespacestd;intmain() {
int day = 3;
switch (day) {
case1:
cout << "Monday" << endl;
break;
case2:
cout << "Tuesday" << endl;
break;
case3:
cout << "Wednesday" << endl;
break;
case4:
cout << "Thursday" << endl;
break;
case5:
cout << "Friday" << endl;
break;
case6:
cout << "Saturday" << endl;
break;
case7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl;
break;
}
return0;
}

Tarnary Operator

syntax

 condition ? value_if_true : value_if_false;

example

#include<iostream>usingnamespacestd;intmain() {
int age = 20;
string result = (age >= 18) ? "Adult" : "Minor";
cout << "You are an " << result << "." << endl;
return0;
}

Loop in cpp

In C++, there are several types of loops that allow you to repeat a block of code multiple times based on certain conditions. The main types of loops are:

for loop

The for loop is typically used when you know beforehand how many times you want to repeat a block of code.

syntax

for (initialization; condition; increment/decrement) {
// Code to be executed
}

example

#include<iostream>usingnamespacestd;intmain() {
for (int i = 1; i <= 5; i++) {
cout << "i = " << i << endl;
}
return0;
}

output

i = 1
i = 2
i = 3
i = 4
i = 5

while loop

The while loop is used when you want to repeat a block of code an unknown number of times, as long as a condition is true. It checks the condition before executing the loop body.

syntax

while (condition) {
// Code to be executed
}

example

#include<iostream>usingnamespacestd;intmain() {
int i = 1;
while (i <= 5) {
cout << "i = " << i << endl;
i++;
}
return0;
}

output

i = 1
i = 2
i = 3
i = 4
i = 5

do-while loop

The do-while loop is similar to the while loop, but it checks the condition after executing the loop body. This guarantees that the loop body is executed at least once.

syntax

do {
// Code to be executed
} while (condition);

example

#include<iostream>usingnamespacestd;intmain() {
int i = 1;
do {
cout << "i = " << i << endl;
i++;
} while (i <= 5);
return0;
}

output

i = 1
i = 2
i = 3
i = 4
i = 5

Range Base for loop with std::vector

example

#include<iostream>
#include<vector>usingnamespacestd;intmain() {
vector<int> vec = {10, 20, 30, 40, 50};
for (int val : vec) {
cout << "Value: " << val << endl;
}
return0;
}

output

Value: 10
Value: 20
Value: 30
Value: 40
Value: 50

Function in cpp

In C++, a function is a block of code that performs a specific task. Functions help in breaking down the code into smaller, reusable pieces, improving modularity and readability.

syntax

return_type function_name(parameter_list)
{
// function body// perform operationsreturn value; // optional, depending on the return_type
}

example

#include<iostream>usingnamespacestd;// Function to add two integers and return the resultintadd(int a, int b) {
return a + b; // return the sum of a and b
}
intmain() {
int result = add(5, 3); // calling the function with arguments 5 and 3
cout << "The sum is: " << result << endl;
return0;
}

output

 The sum is: 8

Type of Function

In C++, functions can be categorized into different types based on their return types, parameters, and other features. The major types of functions in C++ are:

Standard Functions (or Built-in Functions)

Example
#include<iostream>
#include<cmath>// for math functionsintmain() {
double x = 16.0;
double result = sqrt(x); // sqrt is a standard function to compute square root
std::cout << "Square root of " << x << " is: " << result << std::endl;
return0;
}
output
 Square root of 16 is: 4

User-defined Functions

Function with No Arguments
synax
voidfunctionName() {
// Code
}
example
#include<iostream>voidgreet() {
std::cout << "Hello, welcome to C++!" << std::endl;
}
intmain() {
greet(); // Calling the functionreturn0;
}
output
Hello, welcome to C++!
Function with Arguments
syntax
return_type functionName(parameter1, parameter2, ...) {
// Code
}
example
#include<iostream>intadd(int a, int b) {
return a + b;
}
intmain() {
int sum = add(5, 3); // Calling the function with arguments
std::cout << "Sum: " << sum << std::endl;
return0;
}
output
Sum: 8
Function with Return Value
syntax
return_type functionName(parameters) {
// Codereturn value;
}
example
#include<iostream>floatdivide(float a, float b) {
return a / b;
}
intmain() {
float result = divide(10.0, 2.0); // Calling the function with arguments
std::cout << "Division Result: " << result << std::endl;
return0;
}
output
Division Result: 5
Functions with default arguments
syntax
return_type functionName(parameter1, parameter2 = default_value) {
// Code
}
example
#include<iostream>intmultiply(int a, int b = 2) {
return a * b;
}
intmain() {
std::cout << multiply(4, 5) << std::endl; // Uses both arguments
std::cout << multiply(4) << std::endl; // Uses default value for breturn0;
}
output
208

Inline Functions

An inline function is a function where the compiler replaces the function call with the actual code of the function, thereby potentially improving performance by avoiding the overhead of function calls. Inline functions are typically small, and the keyword inline is used to define them.

syntax
inline return_type functionName(parameters) {
// Code
}
Example
#include<iostream>inlineintsquare(int x) {
return x * x;
}
intmain() {
std::cout << "Square of 5: " << square(5) << std::endl;
return0;
}
output
Square of 5: 25

Recursive Functions

A recursive function is a function that calls itself. Recursion is often used for problems that can be broken down into smaller subproblems, such as calculating factorials or Fibonacci numbers.

syntax
return_type functionName(parameters) {
if (base_condition) {
return base_value;
}
returnfunctionName(new_parameters); // Recursive call
}
example
#include<iostream>intfactorial(int n) {
if (n == 0) // Base conditionreturn1;
elsereturn n * factorial(n - 1); // Recursive call
}
intmain() {
int num = 5;
std::cout << "Factorial of " << num << " is: " << factorial(num) << std::endl;
return0;
}
output
Factorial of 5 is: 120

Friend Functions

A friend function is a function that is not a member of a class but has access to the class's private and protected members. This is useful when you need to perform operations that involve more than one class but need access to the private data.

syntax
classMyClass {
private:int data;
public:MyClass(int val) : data(val) {}
friendvoiddisplayData(MyClass obj); // Friend function declaration
};
voiddisplayData(MyClass obj) {
std::cout << "Data: " << obj.data << std::endl; // Accessing private member
}
intmain() {
MyClass obj(10);
displayData(obj); // Calling the friend functionreturn0;
}
output
Data: 10

Virtual Functions

A virtual function is a function that is declared in the base class and overridden in the derived class. It allows you to use polymorphism, where the function that gets called depends on the type of the object, not the reference.

syntax
classBase {
public:virtualvoidshow() {
std::cout << "Base class show function" << std::endl;
}
};
classDerived : publicBase {
public:voidshow() override {
std::cout << "Derived class show function" << std::endl;
}
};
intmain() {
Base* ptr;
Derived obj;
ptr = &obj;
ptr->show(); // Will call Derived class's show()return0;
}
output
Derived classshow function

update soon for more content " Thank You "
Sujit Tomar

About

This repository is a collection of C++ programs and exercises designed to strengthen your understanding of C++ fundamentals, object-oriented programming, and problem-solving skills. It’s ideal for students, beginners, and those preparing for technical interviews or competitive programming.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages