This is a C++ programming cheat sheet. It is useful for beginners and intermediates looking to learn or revise the concepts of C++ programming. While learning a new language, it feels annoying to switch pages and find different websites for different concepts that are easily understandable. You can learn C++ concepts very easily using this cheat sheet.

C++ is a high-level programming language. It was developed in 1983 by Bjarne Stroustrup at Bell Labs. It is used for developing various applications.
Basic Structure of C++ Programs
C++
// Header files
#include<bits/stdc++.h>
// std namespace contains
// various standard library components
using namespace std;
// main function is the starting
//point of program execution
int main() {
// This is the section where
// we write code statements
return 0;
}
Comments in C++ are used for providing an explanation of the code that makes it easier for others to understand the functionality of the code. They are not executed by the compiler. Comments can also be used to temporarily disable specific statements of code without deleting them.
There are two types of comments:
1. Single-lined
We use two forward slashes // to indicate the single-line comment. For example,
C++
2. Multi-lined
We use /* to start a multi-line comment and */ to end it. For example,
C++
/* This is multi-lined comment.
The below statement will print GeeksforGeeks.*/
Variables
In C++, a variable is a container used to store data values:
- Variables must be declared before they can be used.
- Multiple variables can also be declared at one time.
- The name of a variable can contain alphabets, digits, and an underscore but the name of a variable must start with an alphabet or an underscore.
Identifiers: All variables in a program must be given unique names which are known as the identifiers so each variable can be identified uniquely.
Constants: Constants are the fixed values that remain unchanged during the execution of the program.
Syntax
C++
// Declaring a single variable
data_type var_name;
// Declaring multiple variables
data_type var1_name, var2_name, var3_name;
Data Types
Data types are the type of data that a variable can store in a program.
1. Integer
- It is used to store integers.
- Integers take 4 bytes of memory.
Example
C++
2. Character
- It is used to store characters.
- It takes 1 bytes of memory.
Example
C++
3. Floating Point
- It is used for storing single-precision floating-point numbers.
- It takes 4 bytes of memory.
Example
C++
4. Double
- It is used to store double-precision floating point numbers.
- It takes 8 bytes of memory.
Example
C++
5. Boolean
- It is used to store logical values that can be either true or false.
Example
C++
6. String
- A string is a collection of characters surrounded by double quotes. The string data type is used to store words or sentences.
- The string data type is part of the Standard Library and is defined in the <string> header file.
- We have to include <string> header file for using string class.
Example
C++
string str = "GeeksforGeeks";
1. Input from user: We can take input from the user using cin from the iostream library. For example,
C++
2. Output on the console: We can print output on the console using cout from the iostream library. For example,
C++
New Lines
We can use \n character or endl to insert a new line. For example,
C++
cout << "Hello World! \n";
cout << "Hello World!" << endl;
Conditional Statements
Conditional statements allow us to control the flow of the program based on certain conditions. It helps us to run a specific section of code based on a condition.
1. The if statement
If statement executes a block of code if and only if the given condition is true.
Syntax
C++
if (condition) {
// Code to be executed if the condition is true
}
2. Nested if statement
Syntax
C++
if (condition1) {
// Code to be executed
if (condition2) {
// Code to be executed
}
}
3. The if-else statement
In if-else statement, condition inside the if statement is true, then the code inside the if block will get executed, otherwise code inside the else block will get executed.
Syntax
C++
if (condition) {
// Code to be executed
// if the condition is true
} else {
// Code to be executed
// if the condition is false
}
4. The else-if statement
The else if statement allows you to check for multiple conditions sequentially.
Syntax
C++
if (condition1) {
// Code to be executed
// if condition1 is true
} else if (condition2) {
// Code to be executed if
// condition1 is false and
// condition2 is true
} else {
// Code to be executed if
// all conditions are false
}
5. Shorthand if else (Ternary Operator)
Shorthand if else also known as the Ternary operator (?:) works just like if-else statements that can be used to reduce the number of lines of code.
Syntax
C++
(condition) ? expression1 : expression2;
Condition inside round brackets () is true, expression1 will be evaluated and it will become the result of the expression. Otherwise, if the condition is false, expression2 will be evaluated and it will become the result.
6. Switch statement
The switch statement evaluates the expression and compares the value of the expression with the cases. If the expression matches the value of any of the cases, the code associated with that case will be executed.
7. Break and Default
The break keyword is used to exit the switch statement when one of the cases matches, while the default keyword, which is optional, executes when none of the cases match the value of the expression.
Syntax
C++
switch (expression) {
case value1:
// Code to be executed if
// expression matches value1
break;
case value2:
// Code to be executed if
// expression matches value2
break;
// ...
default:
// Code to be executed if
// expression does not match any case
break;
}
Note: Default keywords is used with switch statements.
Loops
Loops are used to repeatedly execute a block of code multiple times.
Types of Loops
1. For Loop
For loop helps us to execute a block of code a fixed number of times.
Syntax:
C++
for (initialization expr; test expr; update expr) {
// body of the for loop
}
2. While Loop
While loop repeatedly executes a block of code till the given condition is true.
Syntax
C++
while (condition) {
// statements
update_condition;
}
3. Do-While Loop
Do-while loop also executes the block of code till the condition is true but the difference between a while and a do-while loop is that the do-while executes the code once without checking the condition and the test condition is tested at the end of the loop body.
Syntax
C++
do {
// Body of do-while loop
} while (condition);
Arrays
An array is a data structure that allows us to store a fixed number of elements of the same data type in contiguous memory locations.
Syntax:
C++
dataType array_name[size];
where,
- data_type: Type of data to be stored in the array.
- array_name: Name of the array.
- size: Size of array.
Example
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
// Declare and initialize an array of strings
string fruits[] = {"Apple", "Banana", "Orange", "Grapes"};
// Access and print each element of the array
for (int i = 0; i < 4; i++) {
cout << "Fruit at index " << i << ": " << fruits[i] << endl;
}
return 0;
}
OutputFruit at index 0: Apple
Fruit at index 1: Banana
Fruit at index 2: Orange
Fruit at index 3: Grapes
Multi-Dimensional Arrays
Multi-dimensional arrays are known as arrays of arrays that store similar types of data in tabular form.
Syntax:
C++
data_type array_name[size1][size2]....[sizeN];
where size1, size2,…, sizeN are size of each dimension.
2-Dimensional arrays are the most commonly used multi-dimensional arrays in C++.
Example
C++
#include <iostream>
using namespace std;
int main()
{
// Declaration and initialization of a 2D array
int arr[3][4] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
// Accessing elements in the 2D array
// Output: 1
cout << "Element at arr[0][0]: " << arr[0][0] << endl;
// Output: 7
cout << "Element at arr[1][2]: " << arr[1][2] << endl;
// Changing the value of an element
// Output: 20
arr[2][3] = 20;
cout << "Modified element at arr[2][3]: " << arr[2][3]
<< endl;
// Nested loops for iterating through the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
OutputElement at arr[0][0]: 1
Element at arr[1][2]: 7
Modified element at arr[2][3]: 20
1 2 3 4
5 6 7 8
9 10 11 20
Vectors
Vectors are a dynamic array-like data structure that stores elements of the same data type in a contiguous fashion that can resize itself automatically unlike arrays which mean vectors can grow when an element is inserted or shrink when an element is deleted.
- Vectors are present in C++ Standard Template Library (STL).
- We have to #include <vector> header file in our C++ program to use vectors.
Syntax:
C++
vector<data_type> vector_name;
Commonly used Vector Functions
- push_back() - It is used to insert the elements at the end of the vector.
- pop_back() - It is used to pop or remove elements from the end of the vector.
- clear() - It is used to remove all the elements of the vector.
- empty() - It is used to check if the vector is empty.
- at(i) - It is used to access the element at the specified index 'i'.
- front() - It is used to access the first element of the vector.
- back() - It is used to access the last element of the vector.
- erase() - It is used to remove an element at a specified position.
Example:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create an empty vector
vector<int> numbers;
// push_back()
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Accessing elements using at()
// Output: 10
cout << "Element at index 0: " << numbers.at(0) << endl;
// Output: 20
cout << "Element at index 1: " << numbers.at(1) << endl;
// front() and back()
// Output: 10
cout << "First element: " << numbers.front() << endl;
// Output: 30
cout << "Last element: " << numbers.back() << endl;
// pop_back()
// Remove the last element
numbers.pop_back();
// erase()
// Remove the element at index 1
numbers.erase(numbers.begin() + 1);
// empty()
if (numbers.empty()) {
cout << "Vector is empty" << endl;
}
else {
cout << "Vector is not empty" << endl;
}
// clear()
// Remove all elements
numbers.clear();
if (numbers.empty()) {
cout << "Vector is empty" << endl;
}
else {
cout << "Vector is not empty" << endl;
}
return 0;
}
OutputElement at index 0: 10
Element at index 1: 20
First element: 10
Last element: 30
Vector is not empty
Vector is empty
References and Pointers
References
References provide an alias for an existing variable. We can manipulate the original value using the reference variable. The reference variable is declared using & operator.
Example
C++
int var= 12;
// A reference variable to var
int& ref= var;
where, ref is a reference to var variable.
Pointers
A pointer is a variable that stores the memory address of another variable. It can be created using the * operator and the address of another variable can be assigned using the address-of operator &.
Example
C++
int i = 3;
// A pointer to variable i or "stores the address of i"
int *ptr = &i;
Functions
Functions are the reusable block of a set of statements that performs a specific task. Functions can be used to organize the logic of the program.
Syntax for function declaration
C++
return_type function_name(parameters);
Syntax for function definition
C++
return_type function_name(parameters) {
// function body
// code to be executed
// return statement (if applicable)
}
- return_type: It is the data type of the value that a function returns.
- function_name: It is the name of the function.
- parameters: parameters are the input values provided when the function is called. parameters are optional.
Example
Program to add two numbers.
C++
#include<bits/stdc++.h>
using namespace std;
// Function declaration
int sum(int a, int b);
// Function definition
int sum(int a, int b) {
return a + b;
}
int main()
{
// Function call
int result = sum(3, 4);
cout << result;
}
Explanation: The function sum takes two integers as parameters and returns the sum of the two numbers. The return type of the function is int. The parameters of the function are two integers that are 3 and 4. The returned value 7 is stored in the variable result.
String Functions
There are several string functions present in Standard Template Library in C++ that are used to perform operations on strings. Some of the commonly used string functions are:
1. length() Function
Returns the length of a string.
Example
C++
string str = "GeeksforGeeks";
cout << "String length: " << str.length();
2. substr() Function
It is used to extract a substring from a given string.
Syntax
C++
string substr (size_t pos, size_t len) const;
- pos: Position of the first character to be copied
- len: Length of the sub-string.
- size_t: It is an unsigned integral type.
Example
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "GeeksforGeeks";
// Extracts a substring starting from
// index 1 with a length of 5
string sub = str.substr(1, 5);
cout << "Substring: " << sub << endl;
return 0;
}
3. append() Function
Appends a string at the end of the given string.
Example
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Geeksfor";
str.append("Geeks");
cout << "Appended string: " << str << endl;
return 0;
}
OutputAppended string: GeeksforGeeks
4. compare() Function
It is used to compare two strings lexicographically.
Example
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Geeks";
string str2 = "for";
string str3 = "Geeks";
int result1 = str1.compare(str2);
cout << "Comparison result: " << result1 << endl;
int result2 = str1.compare(str3);
cout << "Comparison result: " << result2 << endl;
return 0;
}
OutputComparison result: -31
Comparison result: 0
5. empty() Function
It is used to check if a string is empty.
Example
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
string str1 = "GeeksforGeeks";
string str2 = "";
if (str1.empty())
cout << "str1 is empty" << endl;
else
cout << "str1 is not empty" << endl;
if (str2.empty())
cout << "str2 is empty" << endl;
else
cout << "str2 is not empty" << endl;
return 0;
}
Outputstr1 is not empty
str2 is empty
Math Functions
Function | Description | Example |
---|
min(x, y) | Returns the minimum value of x and y. | cout << min(10, 20); |
---|
max(x, y) | Returns the maximum value of x and y. | cout << max(10, 20); |
---|
sqrt(x) | Returns the square root of x. | cout << sqrt(25); |
---|
ceil(x) | It rounds up the value x to its nearest integer. | double ceilX = ceil(3.14159); |
---|
floor(x) | It rounds the value of x downwards to the nearest integer. | double floorX = floor(3.14159); |
---|
pow(x,n) | It returns the value x raised to the power of y | double result = pow(3.0, 2.0); |
---|
Object-Oriented Programming
Object-oriented programming generally means storing data in the form of classes and objects.
Class and Objects
- Class: A class is a user-defined data type that contains its data members and member functions. A class is a blueprint for objects having similar attributes and behavior.
- Objects: An object is an instance or a variable of the class.
Pillars of OOPs
1. Encapsulation
Encapsulation is wrapping up the data and methods together within a single entity. In C++, classes are used for encapsulation.
2. Abstraction
Showing only the necessary details and hiding the internal details is known as abstraction.
4. Inheritance
Deriving the properties of a class ( Parent class ) to another class ( Child class ) is known as Inheritance. It is used for code reusabilty.
Types of Inheritance:
- Single Inheritance: When a derived class inherits the properties of a single base class, it is known as Single Inheritance.
- Multiple Inheritance: When a derived class inherits the properties of multiple base classes, it is known as Multiple Inheritance.
- Multilevel Inheritance: When a derived class inherits the properties of another derived class, it is known as Multilevel Inheritance.
- Hierarchical Inheritance: When more than one derived class inherits the properties of a single base class, it is known as Hierarchical Inheritance.
- Hybrid (Virtual) Inheritance: When we combine more than one type of inheritance, it is known as Hybrid (Virtual) Inheritance. Example: Combining Multilevel and Hierarchical inheritance.
3. Polymorphism
Providing different functionalities to the functions or operators of the same name is known as Polymorphism.
C++ provides two types of polymorphism:
4. Inheritance
Deriving the properties of a class (Parent class) to another class (Child class) is known as Inheritance. It is used for code reusability.
Types of Inheritance:
- Single Inheritance: When a derived class inherits the properties of a single base class, it is known as Single Inheritance.
- Multiple Inheritance: When a derived class inherits the properties of multiple base classes, it is known as Multiple Inheritance.
- Multilevel Inheritance: When a derived class inherits the properties of another derived class, it is known as Multilevel Inheritance.
- Hierarchical Inheritance: When more than one derived class inherits the properties of a single base class, it is known as Hierarchical Inheritance.
- Hybrid (Virtual) Inheritance: When we combine more than one type of inheritance, it is known as Hybrid (Virtual) Inheritance. Example: Combining Multilevel and Hierarchical inheritance.
File Handling
File handling means reading data from a file and manipulating the data of a file.
File Handling Operations
1. Open a file: We can use open() member function of ofstream class to open a file.
2. Read a file: We can use getline() member function of ifstream class to read a file.
3. Write to a file: We can use << operator to write to a file after opening a file with the object of ofstream class.
Example:
C++
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ofstream outputFile("example.txt");
// Open the file for writing
outputFile.open("example.txt");
if (outputFile.is_open()) {
// Write data to the file
outputFile << "Hello, World!" << endl;
outputFile << 42 << endl;
outputFile.close(); // Close the file
}
else {
// Failed to open the file
cout << "Error opening the file for writing."
<< endl;
return 1;
}
// Reading from a file
ifstream inputFile("example.txt");
if (inputFile.is_open()) {
string line;
while (getline(inputFile, line)) {
// Print each line
cout << line << endl;
}
// Close the file
inputFile.close();
}
else {
// Failed to open the file
cout << "Error opening the file for reading."
<< endl;
return 1;
}
return 0;
}
This C++ cheat sheet can serve as a reference guide for programmers that provides quick access to concepts of C++.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
C++ Overview
Introduction to C++ Programming LanguageC++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an enhancement of the C language to add object-oriented paradigm. It is considered as a middle-level language as it combines features of both high-level and low-level languages. It has high level language featur
3 min read
Features of C++C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including:Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopul
5 min read
History of C++The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development EnvironmentC++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using Online IDEIDE stands for an integrated development environment. IDE is a software application that provides facilities to
8 min read
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
C++ Basics
Understanding First C++ ProgramThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
C++ Basic SyntaxSyntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language.The C++ language also has its syntax for the functionalities it provides. Different statements have different
4 min read
C++ CommentsComments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work.Ex
3 min read
Tokens in CIn C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ KeywordsKeywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
2 min read
Difference between Keyword and Identifier in CIn C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language.The below table illustrates the primary diff
3 min read
C++ Variables and Constants
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Constants in CIn C programming, const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various type
4 min read
Scope of Variables in C++In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with.Let's take a look at an example:C++#include <iostream> using namespace std; //
7 min read
Storage Classes in C++ with ExamplesC++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
6 min read
Static Keyword in C++The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
5 min read
C++ Data Types and Literals
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
Literals in CIn C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality.In C++, there are four different derived data types:Table of Cont
4 min read
User Defined Data Types in C++User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types:Table of ContentClassStructu
4 min read
Data Type Ranges and Their Macros in C++Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
3 min read
C++ Type ModifiersIn C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store.C++ have 4 type modifiers which are as follows:Table of Contentsigned Modifierunsigned Mod
4 min read
Type Conversion in C++Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
4 min read
Casting Operators in C++The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
5 min read
C++ Operators
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
C++ Arithmetic OperatorsArithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in CIn C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Bitwise Operators in CIn C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Assignment Operators in CIn C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error.Let's take a look at an example:C#include
4 min read
C++ sizeof OperatorThe sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions.Let's take a look at an example:C++#include <iostream> using namespace std; int ma
3 min read
Scope Resolution Operator in C++In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example:C++#include <iostream> int main() { // Accessing cout from std namespace using scope // r
4 min read
C++ Input/Output
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
7 min read
C++ if StatementThe C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int
3 min read
C++ if else StatementThe if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
3 min read
C++ if else if LadderIn C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
Switch Statement in C++In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is a simpler alternative to the long if-else-if ladder.SyntaxC++switch (expression) { case value_1: // code to be executed. break; case v
5 min read
Jump statements in C++Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S
4 min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
for Loop in C++In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h
6 min read
Range-Based for Loop in C++In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take
3 min read
C++ While LoopIn C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while LoopIn C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++A Function is a reusable block of code designed to perform a specific task. It helps break large programs into smaller, logical parts. Functions make code cleaner, easier to understand, and more maintainable.Just like in other languages, C++ functions can take inputs (called parameters), execute a b
8 min read
return Statement in C++In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in CIn C, passing values to a function means providing data to the function when it is called so that the function can use or manipulate that data. Here:Formal Parameters: Variables used in parameter list in a function declaration/definition as placeholders. Also called only parameters.Actual Parameters
3 min read
Difference Between Call by Value and Call by Reference in CFunctions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing.Call By Valu
4 min read
Default Arguments in C++A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value.Example:C++#include <i
5 min read
Inline Functions in C++In C++, inline functions provide a way to optimize the performance of the program by reducing the overhead related to a function call. When a function is specified as inline the whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of us
6 min read
Lambda Expression in C++C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused. Therefore, they do not require a name. They are mostly used in STL algorithms as callback functions.Example:C++#include <iostream> using namespace std; i
4 min read
C++ Pointers and References
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ PointersA pointer is a special variable that holds the memory address of another variable, rather than storing a direct value itself. Pointers allow programs to access and manipulate data in memory efficiently, making them a key feature for system-level programming and dynamic memory management. When we acc
8 min read
Dangling, Void , Null and Wild Pointers in CIn C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in CPointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++Consider the following C++ program that shows problem with NULL (need of nullptr) CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Overloaded fun
3 min read
References in C++In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly.Example:C++#include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // printing v
5 min read
Can References Refer to Invalid Location in C++?Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?Let's first understand what Passing by Pointer and Passing by Reference in C++ mean:Passing by
5 min read
When do we pass arguments by pointer?In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read