in

Cheat Sheet for C++ – DEV Community




Basics

Basic syntax and functions from the C++ programming language.



1. Boilerplate

#include <iostream>
using namespace std;
int main() {
cout << "Hi, I am Bhagya Mudgal";
return 0;
}
Enter fullscreen mode

Exit fullscreen mode



2. cout <<

It prints output on the screen.

cout << "This is C++ Programming";
Enter fullscreen mode

Exit fullscreen mode



3. cin >>

It takes input from the user.

cin >> variable_name;
Enter fullscreen mode

Exit fullscreen mode



Data types

The data type is the type of data.



1. char

Typically a one byte. It is an character type.

char variable_name;
Enter fullscreen mode

Exit fullscreen mode



2. int

Size depends on compiler, 2 bytes in 32-bit compiler and 4 bytes in 54-bit compiler.

int variable_name;
Enter fullscreen mode

Exit fullscreen mode



3. float

A single-precision floating-point value.

float variable_name;
Enter fullscreen mode

Exit fullscreen mode



4. double

A double-precision floating-point value.

double variable_name;
Enter fullscreen mode

Exit fullscreen mode



5. void

Represents the absence of the type.

void
Enter fullscreen mode

Exit fullscreen mode



6. bool

Represent Boolean value i.e. either true or false.

bool
Enter fullscreen mode

Exit fullscreen mode



Escape Sequences

In computer science, an escape sequence is a combination of characters that has a meaning other than the literal characters contained therein.



1. Alarm or beep

It produces a beep sound.

a
Enter fullscreen mode

Exit fullscreen mode



2. Backspace

It adds a backspace.

b
Enter fullscreen mode

Exit fullscreen mode



3. Newline

Newline Character.

n
Enter fullscreen mode

Exit fullscreen mode



4. Carriage return

r
Enter fullscreen mode

Exit fullscreen mode



5. Tab

It gives a tab space.

t
Enter fullscreen mode

Exit fullscreen mode



6. Backslash

It adds a backslash.


Enter fullscreen mode

Exit fullscreen mode



7. Single quote

It adds a single quotation mark.

'
Enter fullscreen mode

Exit fullscreen mode



8. Question mark

It adds a question mark.

?
Enter fullscreen mode

Exit fullscreen mode



9. Octal Number

It represents the value of an octal number.

nnn
Enter fullscreen mode

Exit fullscreen mode



10. Hexadecimal Number

It represents the value of a hexadecimal number.

xhh
Enter fullscreen mode

Exit fullscreen mode



11. Null

The null character is usually used to terminate a string.

0
Enter fullscreen mode

Exit fullscreen mode



Comments

A comment is a code that is not executed by the compiler, and the programmer uses it to explain the code where needed.



1. Single line comment

// It's a single line comment
Enter fullscreen mode

Exit fullscreen mode



2. Multi-line comment

/* It's a 
multi-line
comment
*/
Enter fullscreen mode

Exit fullscreen mode



Strings

It is a collection of characters surrounded by double quotes.



1. Declaring String

// Include the string library
#include <string>
// String variable
string variable1 = "Hello World";
Enter fullscreen mode

Exit fullscreen mode



2. append() function

It is used to concatenate two strings

string firstName = "Bhagya ";
string lastName = "Mudgal";
string fullName = firstName.append(lastName);
cout << fullName; // Output: BhagyaMudgal
Enter fullscreen mode

Exit fullscreen mode



3. length() function

It returns the length of the string

string variable = "Bhagya Mudgal";
cout << "The length of the string is: " << variable.length();
// Output: The length of the string is: 13
Enter fullscreen mode

Exit fullscreen mode



4. Accessing and changing string characters

string variable = "Hello World";
variable[1] = 'i';
cout << variable; // Output: Hillo World
Enter fullscreen mode

Exit fullscreen mode



Maths

C++ provides some built-in math functions that help the programmer to perform mathematical operations efficiently.

To use functions these functions first include cmath in your program.

#include <cmath>
Enter fullscreen mode

Exit fullscreen mode



1. max() function

It returns the larger value among the given two values.

cout << max(25, 150); // Output: 150
Enter fullscreen mode

Exit fullscreen mode



2. min() function

It returns the smaller value among the given two values.

cout << min(75, 150); // Output: 75
Enter fullscreen mode

Exit fullscreen mode



3. sqrt() function

It returns the square root of the given number.

cout << sqrt(25); // Output: 5
Enter fullscreen mode

Exit fullscreen mode



4. ceil() function

It returns the value of x rounded up to its nearest integer.

int x=2.5;
ceil(x); // Output: 3
Enter fullscreen mode

Exit fullscreen mode



5. floor() function

It returns the value of x rounded down to its nearest integer.

int x=2.5;
floor(x); // Output: 2
Enter fullscreen mode

Exit fullscreen mode



6. pow() function

It returns the value of x to the power of y.

int x=5, y=2;
pow(x, y); // Output: 25
Enter fullscreen mode

Exit fullscreen mode



Control Statements

Conditional statements are used to perform operations based on some condition.



1. if Statement

if (condition) {
// This block of code will get executed, if the condition is True
}
Enter fullscreen mode

Exit fullscreen mode



2. if-else Statement

if (condition) {
// If condition is True then this block will get executed
} else {
// If condition is False then this block will get executed
}
Enter fullscreen mode

Exit fullscreen mode



3. if-else if Statement

if (condition) {
// Statements;
}
else if (condition){
// Statements;
}
else{
// Statements
}
Enter fullscreen mode

Exit fullscreen mode



4. Ternary Operator

It is shorthand of an if-else statement.

variable = (condition) ? expressionTrue : expressionFalse;
Enter fullscreen mode

Exit fullscreen mode



5. Switch Case Statement

It allows a variable to be tested for equality against a list of values (cases).

switch (expression)
{
case constant-expression: statement1;
                          statement2;
                          break;

case constant-expression: statement;
                          break;

default: statement;
         break;
}
Enter fullscreen mode

Exit fullscreen mode



Iterative Statements known as Loops

Iterative statements facilitate programmers to execute any block of code lines repeatedly and can be controlled as per conditions added by the programmer.



1. while Loop

It iterates the block of code as long as a specified condition is True

while (/* condition */)
{
/* code block to be executed */
}
Enter fullscreen mode

Exit fullscreen mode



2. do-while loop

It is an exit controlled loop. It is very similar to the while loop with one difference, i.e., the body of the do-while loop is executed at least once even if the condition is False

do
{
/* code */
} while (/* condition */);
Enter fullscreen mode

Exit fullscreen mode



3. for loop

It is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.

for (int i = 0; i < count; i++)
{
/* code */
}
Enter fullscreen mode

Exit fullscreen mode



4. Break Statement

break keyword inside the loop is used to terminate the loop.

break;
Enter fullscreen mode

Exit fullscreen mode



5. Continue Statement

continue keyword skips the rest of the current iteration of the loop and returns to the starting point of the loop.

continue;
Enter fullscreen mode

Exit fullscreen mode



References

Reference is an alias for an already existing variable. Once it is initialized to a variable, it cannot be changed to refer to another variable. So, it’s a const pointer.



Creating References

string var1 = "Value1"; // var1 variable
string &var2 = var1; // reference to var1
Enter fullscreen mode

Exit fullscreen mode



Pointers

Pointer is a variable that holds the memory address of another variable.



Declaration

datatype *var_name;
var_name = &variable2;
Enter fullscreen mode

Exit fullscreen mode



Functions

Functions are used to divide an extensive program into smaller pieces. It can be called multiple times to provide reusability and modularity to the program.



1. Function Definition

return_type function_name(data_type parameter...){
//code to be executed 
}
Enter fullscreen mode

Exit fullscreen mode



2. Function Call

function_name(arguments);
Enter fullscreen mode

Exit fullscreen mode



Recursion

Recursion is when a function calls a copy of itself to work on a minor problem. And the function that calls itself is known as the Recursive function.

void recurse()
{
... .. ...
recurse();
... .. ...
}
Enter fullscreen mode

Exit fullscreen mode



Object-Oriented Programming

It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world entities.



1. class

A class in C++ is a user-defined type or data structure declared with keyword class that has data and functions as its members whose access is governed by the three access specifiers private, protected or public. By default access to members of a C++ class is private.

class Class_name {
public: // Access specifier
// fields
// functions
// blocks
};
Enter fullscreen mode

Exit fullscreen mode



2. object

It is an instance of a class.

Class_name ObjectName;
Enter fullscreen mode

Exit fullscreen mode



3. Constructors

It is a special method that is called automatically as soon as the object is created.

class className { // The class
public: // Access specifier
className() { // Constructor
cout << "Code With Harry";
}
};
int main() {
className obj_name;
return 0;
}
Enter fullscreen mode

Exit fullscreen mode



4. Encapsulation

Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

#include<iostream>
using namespace std;
class ExampleEncap{
private:
/* Since we have marked these data members private, 
* any entity outside this class cannot access these 
* data members directly, they have to use getter and 
* setter functions. 
*/
int num;
char ch;
public:
/* Getter functions to get the value of data members. 
* Since these functions are public, they can be accessed 
* outside the class, thus provide the access to data members 
* through them 
*/
int getNum() const {
return num;
}
char getCh() const {
return ch;
}
/* Setter functions, they are called for assigning the values 
* to the private data members. 
*/
void setNum(int num) {
this->num = num;
}
void setCh(char ch) {
this->ch = ch;
}
};
int main(){
ExampleEncap obj;
obj.setNum(100);
obj.setCh('A');
cout<<obj.getNum()<<endl;
cout<<obj.getCh()<<endl;
return 0;
}
Enter fullscreen mode

Exit fullscreen mode



File Handling

File handling refers to reading or writing data from files. C++ provides some functions that allow us to manipulate data in the files.



1. Creating and writing to a text file

#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "File Handling in C++";
// Close the file
MyFile.close();
}
Enter fullscreen mode

Exit fullscreen mode



2. Reading a file

getline() function allows us to read the file line by line

getline();
Enter fullscreen mode

Exit fullscreen mode



3. Opening a File

open() method opens a file in the C++ program.

void open(const char* file_name,ios::openmode mode);
Enter fullscreen mode

Exit fullscreen mode



openmodes:

Opens the file to read(default for ifstream).

fs.open ("test.txt", std::fstream::in);
Enter fullscreen mode

Exit fullscreen mode

Opens the file to write(default for ofstream).

fs.open ("test.txt", std::fstream::out);
Enter fullscreen mode

Exit fullscreen mode

Opens the file in binary mode.

fs.open ("test.txt", std::fstream::binary);
Enter fullscreen mode

Exit fullscreen mode

Opens the file and appends all the outputs at the end.

fs.open ("test.txt", std::fstream::app);
Enter fullscreen mode

Exit fullscreen mode

Opens the file and moves the control to the end of the file.

fs.open ("test.txt", std::fstream::ate);
Enter fullscreen mode

Exit fullscreen mode

Removes the data in the existing file.

fs.open ("test.txt", std::fstream::trunc);
Enter fullscreen mode

Exit fullscreen mode

Opens the file only if it already exists.

fs.open ("test.txt", std::fstream::nocreate);
Enter fullscreen mode

Exit fullscreen mode

Opens the file only if it does not already exist.

fs.open ("test.txt", std::fstream::noreplace);
Enter fullscreen mode

Exit fullscreen mode



4. Closing a file

close() method closes the file.

myfile.close();
Enter fullscreen mode

Exit fullscreen mode



Exception Handling

An exception is an unusual condition that results in an interruption in the flow of the program.



try and catch block

A basic try-catch block in python. When the try block throws an error, the control goes to the catch block.

try {
// code to try
throw exception; // If a problem arises, then throw an exception
}
catch () {
// Block of code to handle errors
Enter fullscreen mode

Exit fullscreen mode


I hope this C++ Cheat Sheet will help you and save your time.

Feel free to connect with me on LinkedIn.

You can follow me on Instagram.

To know more about me and my projects visit my Portfolio.

If you enjoyed this post, you can support me and Buy Me A Coffee. It encourages me to write more informational and useful content in the future.



Source: https://dev.to/bhagyamudgal/cheat-sheet-for-c-ljg

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

GIPHY App Key not set. Please check settings

A collection of React components that conform to Marshmallow’s Design System

Custom bot I’ve made to host events on my personal Discord server