C++ Cheatsheet – GeeksforGeeks


It is a C++ programming cheat sheet. It’s helpful for rookies and intermediates trying to be taught or revise the ideas of C++ programming. Whereas studying a brand new language, it feels annoying to change pages and discover totally different web sites for various ideas which are simply comprehensible. You may be taught C++ ideas very simply utilizing this cheat sheet.

C++ Cheatsheet

C++ is a high-level programming language. It was developed in 1983 by Bjarne Stroustrup at Bell Labs. It’s used for growing varied purposes.

Let’s create our first C++ program

C++

#embody <iostream>

utilizing namespace std;

int essential() {

  cout << "Hi there World!";

  return 0;

}

It’s okay if you don’t perceive the above code. We’ll focus on the fundamental construction of a C++ code additional.

Fundamental Syntax of a Code in C++

// Header recordsdata
#embody<bits/stdc++.h>
// std namespace accommodates varied normal library elements
utilizing namespace std;
// essential() operate is the place to begin of program execution
int essential()
{
    // That is the part the place we write code statements
    return 0;
}

Enter and Output in C++

1. Enter from person: We will take enter from the person utilizing cin from the iostream library.

Syntax

int var;
cin >> var;

2. Output on the console: We will print output on the console utilizing cout from the iostream library.

Syntax

cout << “Hi there World”;
high-level

New Traces

We will use n character or endl to insert a brand new line.

Syntax

cout << "Hi there World! n";
cout << "Hi there World!" << endl;

Feedback in C++

Feedback can be utilized for offering a proof of the code that makes it simpler for others to know the performance of the code.

Any assertion after the feedback won’t be executed by the compiler. So feedback may also be used to quickly disable (remark out) the execution of some particular statements with out deleting the statements.

Varieties of Feedback:

1. Single-lined

We use two ahead slashes // to point the single-line remark.

Syntax

// It is a remark
cout << "GeeksforGeeks";

2. Multi-lined

We use  /* to start out a multi-line remark and */ to finish it.

Syntax

/* That is multi-lined remark.
The under assertion will print GeeksforGeeks.*/
cout << "GeeksforGeeks";

Conditional Statements in C++

Conditional statements permit us to manage the circulation of this system primarily based on sure situations. It helps us to run a particular part of code primarily based on a situation.

1. The if assertion

If assertion executes a block of code if and provided that the given situation is true.

Syntax

if (situation) {
    // Code to be executed if the situation is true
}

2. Nested if assertion

Syntax

if (condition1) {
    // Code to be executed if condition1 is true
    if (condition2) {
        // Code to be executed if condition1 and condition2 are true
    }
}

3. The if-else assertion

If the situation contained in the if assertion is true, then the code contained in the if block will get executed, in any other case code contained in the else block will get executed.

Syntax

if (situation) {
    // Code to be executed if the situation is true
} 
else {
    // Code to be executed if the situation is fake
}

4. The else-if assertion

The else if assertion lets you examine for a number of situations sequentially.

Syntax

if (condition1) {
    // Code to be executed if condition1 is true
} 
else if (condition2) {
    // Code to be executed if condition1 is fake and condition2 is true
} 
else {
    // Code to be executed if all situations are false
}

5. Brief-hand if else ( Ternary Operator)

Brief-hand if else also referred to as the Ternary operator (?:) works identical to if-else statements that can be utilized to scale back the variety of strains of code.

Syntax

(situation) ? expression1 : expression2;

If the situation is true, expression1 can be evaluated and it’ll change into the results of the expression. In any other case, if the situation is fake, expression2 can be evaluated and it’ll change into the consequence.

6. Change assertion

The swap assertion evaluates the expression and compares the worth of the expression with the circumstances. If the expression matches the worth of any of the circumstances, the code related to that case can be executed.

Break and default key phrases are typically used with swap and circumstances.

Break and Default

Break: The break key phrase is used to exit the swap assertion when one of many circumstances matches.

Default: Default key phrase is non-compulsory in swap statements and the code contained in the default block is executed when not one of the circumstances matches the worth of the expression.

Syntax

swap (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 doesn't match any case
        break;
}

Variables in C++

A variable is a storage location having a reputation that may maintain a price of a particular information kind.

  • A variable will be of any information kind.
  • Variables have to be declared earlier than they can be utilized.
  • A number of variables may also be declared at one time.
  • The identify of a variable can comprise alphabets, digits, and an underscore however the identify of a variable should begin with an alphabet or an underscore.

Identifiers: All variables in a program have to be given distinctive names that are generally known as the identifiers so every variable will be recognized uniquely.

Constants: Constants are the fastened values that stay unchanged through the execution of this system.

Syntax to Declare a variable

// Declaring a single variable
data_type variable_name;
// Declaring a number of variables
data_type variable1_name, variable2_name, variable3_name;

Information Varieties in C++

Information varieties are the kind of information {that a} variable can retailer in a program.

1. Integer

  • It’s used to retailer integers.
  • Integers take 4 bytes of reminiscence.

Syntax

int var = 123;

2. Character

  • It’s used to retailer characters.
  • It takes 1 bytes of reminiscence.

Syntax

char var="a";

3. Floating Level

  • It’s used for storing single-precision floating-point numbers.
  • It takes 4 bytes of reminiscence.

Syntax

float num = 1.23;

4. Double

  • It’s used to retailer double-precision floating level numbers.
  • It takes 8 bytes of reminiscence.

Syntax

double num = 1.2345;

5. Boolean

  • It’s used to retailer logical values that may be both true or false.

Syntax

boolean b = false;

6. String

  • A string is a set of characters surrounded by double quotes. The string information kind is used to retailer phrases or sentences.
  • The string information kind is a part of the Normal Library and is outlined within the <string> header file.
  • We now have to incorporate <string> header file for utilizing string class.

Syntax

string str = "GeeksforGeeks";

Loop in C++

Loops are used to repeatedly execute a block of code a number of occasions.

Varieties of Loops

1. For Loop

For loop helps us to execute a block of code a set variety of occasions.

Syntax

for (initialization expr; check expr; replace expr)
{    
     // physique of the loop
     // statements we wish to execute
}

2. Whereas Loop

Whereas loop repeatedly executes a block of code until the given situation is true.

Syntax

whereas (situation)
{
   // statements
 
   update_condition;
}

3. Do-Whereas Loop

Do-while loop additionally executes the block of code until the situation is true however the distinction between some time and a do-while loop is that the do-while executes the code as soon as with out checking the situation and the check situation is examined on the finish of the loop physique.

Syntax

do {
    // Code to be repeated
} whereas (situation);

Arrays in C++

An array is an information construction that permits us to retailer a set variety of components of the identical information kind in contiguous reminiscence areas.

Syntax to Declare an Array

dataType arrayName[arraySize];

Instance

C++

#embody <iostream>

#embody <string>

utilizing namespace std;

int essential() {

    

    

    string fruits[] = {"Apple", "Banana", "Orange", "Grapes"};

  

    

    for (int i = 0; i < 4; i++) {

        cout << "Fruit at index " << i << ": " << fruits[i] << endl;

    }

  

    return 0;

}

Output

Fruit at index 0: Apple
Fruit at index 1: Banana
Fruit at index 2: Orange
Fruit at index 3: Grapes

Multi-Dimensional Arrays in C++

Multi-dimensional arrays are generally known as arrays of arrays that retailer related forms of information in tabular type.

Syntax

data_type array_name[size1][size2]....[sizeN];

data_type: Sort of knowledge to be saved within the array.
array_name: Title of the array.
size1, size2,…, sizeN: Measurement of every dimension.

2-dimensional arrays are essentially the most generally used multi-dimensional arrays in C++.

Instance

C++

#embody <iostream>

utilizing namespace std;

int essential()

{

    

    int arr[3][4] = { { 1, 2, 3, 4 },

                      { 5, 6, 7, 8 },

                      { 9, 10, 11, 12 } };

  

    

    

    cout << "Factor at arr[0][0]: " << arr[0][0] << endl;

    

    cout << "Factor at arr[1][2]: " << arr[1][2] << endl;

  

    

    

    arr[2][3] = 20;

    cout << "Modified ingredient at arr[2][3]: " << arr[2][3]

         << endl;

  

    

    for (int i = 0; i < 3; i++) {

        for (int j = 0; j < 4; j++) {

            cout << arr[i][j] << " ";

        }

        cout << endl;

    }

  

    return 0;

}

Output

Factor at arr[0][0]: 1
Factor at arr[1][2]: 7
Modified ingredient at arr[2][3]: 20
1 2 3 4 
5 6 7 8 
9 10 11 20 

Vectors in C++

Vectors are a dynamic array-like information construction that shops components of the identical information kind in a contiguous trend that may resize itself routinely not like arrays which imply vectors can develop when a component is inserted or shrink when a component is deleted.

  • Vectors are current in C++ Normal Template Library (STL).
  • We now have to #embody <vector> header file in our C++ program to make use of vectors.

Syntax to declare a Vector

vector<data_type> vectorName;

Generally used Vector Features

  • push_back() – It’s used to insert the weather on the finish of the vector.
  • pop_back() – It’s used to pop or take away components from the top of the vector.
  • clear() – It’s used to take away all the weather of the vector.
  • empty() – It’s used to examine if the vector is empty.
  • at(i) – It’s used to entry the ingredient on the specified index ‘i’.
  • entrance() – It’s used to entry the primary ingredient of the vector.
  • again() – It’s used to entry the final ingredient of the vector.
  • erase() – It’s used to take away a component at a specified place.

Instance

C++

#embody <iostream>

#embody <vector>

utilizing namespace std;

int essential()

{

    

    vector<int> numbers;

  

    

    numbers.push_back(10);

    numbers.push_back(20);

    numbers.push_back(30);

  

    

    

    cout << "Factor at index 0: " << numbers.at(0) << endl;

    

    cout << "Factor at index 1: " << numbers.at(1) << endl;

  

    

    

    cout << "First ingredient: " << numbers.entrance() << endl;

    

    cout << "Final ingredient: " << numbers.again() << endl;

  

    

    

    numbers.pop_back();

  

    

    

    numbers.erase(numbers.start() + 1);

  

    

    if (numbers.empty()) {

        cout << "Vector is empty" << endl;

    }

    else {

        cout << "Vector will not be empty" << endl;

    }

  

    

    

    numbers.clear();

  

    if (numbers.empty()) {

        cout << "Vector is empty" << endl;

    }

    else {

        cout << "Vector will not be empty" << endl;

    }

  

    return 0;

}

Output

Factor at index 0: 10
Factor at index 1: 20
First ingredient: 10
Final ingredient: 30
Vector will not be empty
Vector is empty

References and Pointers

References

References present an alias for an present variable. We will manipulate the unique worth utilizing the reference variable. The reference variable is asserted utilizing & operator.

Instance

int originalVariable = 12;
// A reference variable to originalVariable
int& referenceVariable = originalVariable;

referenceVariable is reference to originalVariable.

Pointers

A pointer is a variable that shops the reminiscence handle of one other variable. It may be created utilizing the * operator and the handle of one other variable will be assigned utilizing the address-of operator &.

Instance

int i = 3; 
// A pointer to variable i or "shops the handle of i"
int *ptr = &i;

Features

Features are the reusable block of a set of statements that performs a particular process. Features can be utilized to prepare the logic of this system.

Syntax for operate declaration

return_type function_name(parameters);

Syntax for operate definition

return_type function_name(parameters) {
    // operate physique
    // code to be executed
    // return assertion (if relevant)
}

return_type: It’s the information kind of the worth {that a} operate returns.
function_name: It’s the identify of the operate.
parameters: parameters are the enter values supplied when the operate is known as. parameters are non-compulsory.

Instance

Program so as to add two numbers.

C++

#embody<bits/stdc++.h>

utilizing namespace std;

  

int sum(int a, int b);

  

int sum(int a, int b) {

    return a + b;

}

  

int essential()

{

    

    int consequence = sum(3, 4);

      cout << consequence;

}

Rationalization: The operate sum takes two integers as parameters and returns the sum of the 2 numbers. The return kind of the operate is int. The parameters of the operate are two integers which are 3 and 4. The returned worth 7 is saved within the variable consequence.

String Features in C++

There are a number of string features current in Normal Template Library in C++ which are used to carry out operations on strings. A few of the generally used string features are:

1. size() Operate

Returns the size of a string.

Instance

string str = "GeeksforGeeks";
cout << "The size of the string is: " << str.size();

2. substr() Operate

It’s used to extract a substring from a given string.

Syntax

string substr (size_t pos, size_t len) const;

pos: Place of the primary character to be copied.
len: Size of the sub-string.
size_t: It’s an unsigned integral kind.

Instance

C++

#embody <iostream>

#embody <string>

utilizing namespace std;

int essential()

{

    string str = "GeeksforGeeks";

  

    

    

    string sub = str.substr(1, 5);

  

    cout << "Substring: " << sub << endl;

  

    return 0;

}

3. append() Operate

Appends a string on the finish of the given string.

Instance

C++

#embody <iostream>

#embody <string>

utilizing namespace std;

int essential() {

    string str = "Geeksfor";

  

    str.append("Geeks");

  

    cout << "Appended string: " << str << endl;

  

    return 0;

}

Output

Appended string: GeeksforGeeks

4. evaluate() Operate

It’s used to match two strings lexicographically.

Instance

C++

#embody <iostream>

#embody <string>

utilizing namespace std;

int essential() {

    string str1 = "Geeks";

    string str2 = "for";

    string str3 = "Geeks";

      

    int result1 = str1.evaluate(str2);

    cout << "Comparability consequence: " << result1 << endl;

  

    int result2 = str1.evaluate(str3);

    cout << "Comparability consequence: " << result2 << endl;

      

    return 0;

}

Output

Comparability consequence: -31
Comparability consequence: 0

5. empty() Operate

It’s used to examine if a string is empty.

Instance

C++

#embody <iostream>

#embody <string>

utilizing namespace std;

int essential() {

    string str1 = "GeeksforGeeks";

    string str2 = "";

  

    if (str1.empty()) {

        cout << "str1 is empty" << endl;

    } else {

        cout << "str1 will not be empty" << endl;

    }

  

    if (str2.empty()) {

        cout << "str2 is empty" << endl;

    } else {

        cout << "str2 will not be empty" << endl;

    }

  

    return 0;

}

Output

str1 will not be empty
str2 is empty

Math Features in C++

Operate

Description

Instance

min(x, y) Returns the minimal worth of x and y. cout << min(10, 20);
max(x, y) Returns the minimal worth of x and y. cout << max(10, 20);
sqrt(x) Returns the sq. root of x. cout << sqrt(25);
ceil(x) It rounds up the worth x to its nearest integer. double ceilX = ceil(3.14159);
ground(x) It rounds the worth of x downwards to the closest integer. double floorX = ground(3.14159);
pow(x,n) It returns the worth x raised to the facility of y double consequence = pow(3.0, 2.0);

Object-Oriented Programming in C++

Object-oriented programming typically means storing information within the type of courses and objects.

Class and Objects

Class: A category is a user-defined information kind that accommodates its information members and member features. A category is a blueprint for objects having related attributes and habits.

Objects: An object is an occasion or a variable of the category.

Pillars of OOPS

1. Encapsulation

Encapsulation is wrapping up the information and strategies collectively inside a single entity. In C++, courses are used for encapsulation.

2. Abstraction

Exhibiting solely the required particulars and hiding the interior particulars is named abstraction.

3. Polymorphism

Offering totally different functionalities to the features or operators of the identical identify is named Polymorphism.

Varieties of Polymorphism

  • Compile-time Polymorphism
  • Runtime Polymorphism

Compile-time Polymorphism will be achieved utilizing:

  • Operator overloading
  • Operate overloading

Runtime Polymorphism will be achieved utilizing:

  • Operate overriding
  • Digital Features

4. Inheritance

Deriving the properties of a category ( Mum or dad class ) to a different class ( Youngster class ) is named Inheritance. It’s used for code reusabilty.

Varieties of Inheritance:

  • Single Inheritance: When a derived class inherits the properties of a single base class, it is named Single Inheritance.
  • A number of Inheritance: When a derived class inherits the properties of a number of base courses, it is named A number of Inheritance.
  • Multilevel Inheritance: When a derived class inherits the properties of one other derived class, it is named Multilevel Inheritance.
  • Hierarchical Inheritance: When a couple of derived class inherits the properties of a single base class, it is named Hierarchical Inheritance.
  • Hybrid (Digital) Inheritance: After we mix a couple of kind of inheritance, it is named Hybrid (Digital) Inheritance. Instance: Combining Multilevel and Hierarchical inheritance.

File Dealing with in C++

File dealing with means studying information from a file and manipulating the information of a file.

File Dealing with Operations in C++

1. Open a file

We will use open() member operate of ofstream class to open a file.

2. Learn a file

We will use getline() member operate of ifstream class to learn a file.

3. Write to a file

We will use << operator to jot down to a file after opening a file with the thing of ofstream class.

Instance

C++

#embody <fstream>

#embody <iostream>

#embody <string>

  

utilizing namespace std;

  

int essential()

{

    ofstream outputFile("instance.txt");

  

    

    outputFile.open("instance.txt");

    if (outputFile.is_open()) {

  

        

        outputFile << "Hi there, World!" << endl;

        outputFile << 42 << endl;

        outputFile.shut();

    }

    else {

  

        

        cout << "Error opening the file for writing."

             << endl;

        return 1;

    }

  

    

    ifstream inputFile("instance.txt");

    if (inputFile.is_open()) {

        string line;

        whereas (getline(inputFile, line)) {

            

            cout << line << endl;

        }

        

        inputFile.shut();

    }

    else {

  

        

        cout << "Error opening the file for studying."

             << endl;

        return 1;

    }

  

    return 0;

}

This C++ cheat sheet can function a reference information for programmers that gives fast entry to ideas of C++.

Leave a Reply

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