Learn C++ Programming Basic To Advanced | C++ Cheatsheet 2022

Basic Syntax Of C++ Programming

C++’s basic structure is as follows. Almost every time you write C++ code, you’ll have to use this structure. It has the main function, which is where the program execution starts.

#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
 // This is where you write your code
   return 0;
}

When writing code in C++, always put a semicolon at the end of each line to show that the line is over. You must also add the closing bracket to the main function to end it. If you don’t, you’ll get errors when you try to compile the code.

  • Line 1: “#include <iostream>,” tells the computer to use the header file library, which helps you deal with input and output objects like “cout.” C++ programs use header files to add specific features.
  • Line 2: “using namespace std” lets you use names from the standard library for objects and variables.
  • Line 3: Blank line. C++ doesn’t care about the spaces in the code.
  • “int main()” on Line 4 is a function. Any code that is inside the curly brackets will be run.
  • Line 5: The insertion operator () and the object cout are used to print the output text.
  • Line 6: return 0 tells the main function to stop.

Comments

In C++, the text that comes after the comments is ignored by the compiler.
There are two kinds of comments that can be made in C++:

//: Specifies the comment on a single line.

/*…. */: tells what the multi-line comment is.

Data Types

Data types say what kind of data variable it is. The compiler decides where to put the memory based on the types of data. Here are the types of data in C++:

Data Types in C++

Built-in or primitive data types are pre-defined data types that can be used directly. These include Integer, Character, Boolean, Floating Point, Double Floating Point, Valueless or Void, and Wide Character.

Derived data types: The function, array, pointer, and reference data types all come from the primitive data types.

User-defined data types: Class, structure, union, enumeration, and Typedef are all terms that are defined by users.

🔹Built-In Data Types in Brief:

  • Char
char variable_name= 'c';

This stores characters such as ‘A’, ‘a, ‘1’ etc. It takes 1 byte of the system’s memory.

  • Integer
int variable_name = 123;

This is the most commonly used data type. It is used to store integers and takes 4 bytes of memory.

  • Float
float pi = 3.14;

It stores single-precision floating-point numerals.

  • Double
double root_three = 1.71;

It stores double-precision floating-point numbers. It takes 8 bytes of memory.

  • Boolean
boolean b = false;

A boolean variable can either be true or false;

  • String
string str = "Hello";

In C++, the string is a collection of characters, enclosed by double quotes “ ”. It is analogous to a character array. The string is not a built-in data type. Don’t forget to include this line at the top of your code before using string class – #include <cstring>.

Scope of Variables in C++

1. Local Variables

These variables are declared within a function or block of code. Their scope is only limited to that function or block and cannot be accessed by any other statement outside that block. 

For example:

#include <iostream>
usingnamespacestd;

intmain () {
// Local variable:
int a, b;
int c;

// initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return0;
}

2. Global Variables

Global variables are accessible to any function, method, or block of the program. Usually, it is defined outside all the functions. The value of the global variable is the same throughout the program. 

For example:

#include <iostream>
usingnamespacestd;

// Global variable:
int g;

intmain () {
// Local variable:
int a, b;

// initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return0;
}

User Inputs & Outputs

C++ supports “cout” and “cin” for displaying outputs and for taking inputs from users, respectively. The cout uses the iteration operator (<<), and cin uses (>>). 

🔹Output

For example:

cout << "Hello World";

cout prints anything under the “ ” to the screen.

🔹Input

int variable;

cin >> variable;

cin takes the input from the screen and stores it in the variable.

int x; // declaring a variable
cout << "Type a number: "; // Type any number and hit enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the value

Strings

It is a collection of characters surrounded by double quotes

🔹Declaring String

// Include the string library
#include <string>

// String variable
string variable1 = "Hello World";

🔹append function

It is used to concatenate two strings

string firstName = "Harry ";
string lastName = "Bhai";
string fullName = firstName.append(lastName);
cout << fullName;

🔹length function

It returns the length of the string

string variable1 = "CodeWithHarry";
cout << "The length of the string is: " << variable1.length();

🔹Accessing and changing string characters

string variable1 = "Hello World";
variable1[1] = 'i';
cout << variable1;
FunctionDescription
int compare(const string& str)Compare two string objects
int length()Finds the length of the string
void swap(string& str)Swaps the values of two string objects
string substr(int pos, int n)Creates a new string object of n characters
int size()Return the length of the string in terms of bytes
void resize(int n)Resizes the length of the string up to n characters
string& replace(int pos, int len, string& str)Replaces the portion of the string beginning at character position pos and spans len characters
string& append(const string& str)Adds a new character at the end of another string object
char& at(int pos)Accesses an individual character at specified position pos
int find(string& str, int pos, int n)Finds a string specified in the parameter
int find_first_of(string& str, int pos, int n)Find the first occurrence of the specified sequence
int find_first_not_of(string& str, int pos, int n )Searches for the string for the first character that does not match with any of the characters specified in the string
int find_last_of(string& str, int pos, int n)Searches for the string for the last character of a specified sequence
int find_last_not_of(string& str, int pos)Searches for the last character that does not match with the specified sequence
string& insert()Inserts a new character before the character indicated by the position pos
int max_size()Finds the maximum length of the string
void push_back(char ch)Adds a new character ch at the end of the string
void pop_back()Removes the last character of the string
string& assign()Assigns new value to the string
int copy(string& str)Copies the contents of string into another
void clear()Removes all the elements from the string
const_reverse_iterator crbegin()Points to the last character of the string
const_char* data()Copies the characters of string into an array
bool empty()Checks whether the string is empty or not
string& erase()Removes the characters as specified
char& front()Returns a reference to the first character
string& operator+=()Appends a new character at the end of the string
string& operator=()Assigns a new value to the string
char operator[](pos)Retrieves a character at a specified position pos
int rfind()Searches for the last occurrence of the string
iterator end()Refers to the last character of the string
reverse_iterator rend()Points to the first character of the string
void shrink_to_fit()Reduces the capacity and makes it equal to the size of the string
char* c_str()Returns pointer to an array containing a null-terminated sequence of characters
void reserve(int len)Requests a change in capacity
allocator_type get_allocator();Returns the allocated object associated with the string

Also Checkout Other Cheatsheets:

Maths

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

🔹max function

It returns the larger value among the two

cout << max(25, 140);

🔹min function

It returns the smaller value among the two

cout << min(55, 50);

🔹sqrt function

It returns the square root of a supplied number

#include <cmath>

cout << sqrt(144);

🔹ceil function

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

ceil(x)

🔹floor function

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

floor(x)

🔹pow function

It returns the value of x to the power of y

pow(x, y)

Operators 

C++ supports different types of operators to add logic to your code and perform operations on variables and their respective values. Here are the C++ operator types: 

1. Arithmetic Operators

You can perform common mathematical operations with arithmetic operators.

OperatorNameExample
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
++Increment++x
Decrement–x

2. Assignment Operators

You can assign values to variables with assignment operators.

OperatorExampleDescription Same As
=x = 5For assigning a value to the variable.x = 5
+=x += 3It will add the value 3 to the value of x.x = x + 3
-=x -= 3It will subtract the value 3 from the value of x.x = x – 3
*=x *= 3It will multiply the value 3 with the value of x.x = x * 3
/=x /= 3It will divide the value of x by 3.x = x / 3
%=x %= 3It will return the reminder of dividing the the value x by 3.x = x % 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3

3. Comparison Operators

You can use these operators to compare two values to return a true or false value. It will return true if both the values match and false if they don’t match.

OperatorNameExample
==Equal tox == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

4. Logical Operators

These operators determine the logic between variables. 

OperatorNameDescriptionExample
&&Logical andReturns true if both statements are truex < 5 && x < 10
||Logical orReturns true if one of the statements is truex < 5 || x < 4
!Logical notReverse the result, returns false if the result is true!(x < 5 && x < 10)

Conditions and If Statements

🔹If statement

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

If statement belongs to the category of decision-making statements. These statements make decisions based on a condition. If the condition in the condition block is true, the statements in the curly brackets { } are executed. Let’s see the example given below.

if(2<3){
cout << "2 is less than three";
}

🔹If-else statement

If-else is an extension of the if statement. If the conditions provided with if are not true, the statements in the else block are executed.

if(2>3){
cout<< "2 is greater than 3";
}
else{
cout<< "3 is greater than 2";
}

🔹else if

if can be paired with else if for additional conditions.

if(2>3){
cout<< "2 is greater than 3";
}
else if(2==3){
cout<< "2 is equal to 3";
}
else{
cout<< "3 is greater than 2";
}

🔹Switch case

switch (grade) {
 case 9:
   cout << "Freshman\n";
   break;
 case 10:
  cout << "Sophomore\n";
   break;
 case 11:
   cout << "Junior\n";
   break;
 case 12:
   cout << "Senior\n";
   break;
 default:
   cout << "Invalid\n";
   break;
}

A switch statement allows you to test an expression against a variety of cases. If a match is found, the code within begins to run. A case can be ended with the break keyword. When no case matches, default is used.

🔹Ternary Operator

It is shorthand of an if-else statement.

variable = (condition) ? expressionTrue : expressionFalse;

Loops 

Loops are used to execute a particular set of commands for a specific number of times based on the result of the evaluated condition. C++ includes the following loops

  • While loop
  • Do-while loop
  • For loop
  • Break statement
  • Continue statement

1. While Loop

The loop will continue till the specified condition is true.

while (condition)
{code}

2. Do-While Loop

When the condition becomes false, the do-while loop stops executing. However, the only difference between the while and do-while loop is that the do-while loop tests the condition after executing the loop. Therefore, the loop gets executed at least once.

do
{
Code
}
while (condition)

3. For Loop

You can use the for loop to execute a block of code multiple times. This loop runs the block until the condition specified in it holds false. 

for (int a=0; i< count; i++)
{
Code
}

4. Break Statement

This is used to break the flow of the code so the remaining code isn’t executed. This brings you out of the loop. 

For example: 

for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}

5. Continue Statement

This statement will break the flow and take you to the evaluation of the condition. Later, it starts the code execution again.

For example:

for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}

Arrays 

Arrays are derived data types that store multiple data items of similar types at contiguous memory locations.

For example:

string vehicles [4]; //declaring array to store up to 4 variables.
string vehicles[4]= {"car", "scooter", "cycle", "bike"}; //initializing the array

1. Accessing Array Values

You need to use the index number to access the elements stored in an array. 

string vehicles[4]= {"car", "scooter", "cycle", "bike"};
cout << vehicles [0];

2. Changing Array Elements

You can change the elements stored in an array using the index number. 

string vehicles[4]= {"car", "scooter", "cycle", "bike"};
vehicles [0]= " "airplane";
cout << vehicles[0];

Vectors

#include <vector>
int main() {
 vector<int> grade(3);
 grade[0] = 90;
 grade[1] = 80;
 grade[2] = 70;
 return 0;
}

A vector in C++ is a dynamic list of things that can expand and shrink in size. It can only hold values of the same type. It is important to #include the vector library in order to use vectors.

vector<string> wishlist;
wishlist.push_back("Furniture");
wishlist.push_back("Basket");
wishlist.pop_back();
cout << wishlist.size();  // returns the output 1
  • push_back() function adds the value at the end of the vector.
  • pop_back() function removes the element from the end of the vector.
  • size() returns the size of the vector.

Functions & Recursion

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

🔹Function Definition

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

🔹Function Call

function_name(arguments);

🔹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();
... .. ...
}

References 

When you declare a variable as a reference, it acts as an alternative to the existing one. You need to specify the reference variable with “&”, as shown below:

string food = "Pizza";
string &meal = food; // reference to food

Pointer 

A pointer in C++ is a variable that stores the memory address of another variable. Similar to regular variables, pointers also have data types. We use ‘*’ to declare pointers in C++. 

For example:

string food = "Pizza"; // string variable

cout << food; // Outputs the value of food (Pizza)
cout << &food; // Outputs the memory address of food (0x6dfed4)

Object-Oriented Programming

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

🔹Classes and Objects 

C++ is an object-oriented programming language with classes and objects. Class is a user-defined data type you can use to bind data members and member functions together. You can access them by creating an instance of that class. 

Creating a Class

Here’s how to create a class in C++:

classMyClass { // The class
public: // Access specifier- accessible to everyone
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Creating an Object

Objects work as an instance of the class, allowing you to access its members, functions, and variables. You must use the dot (.) operator, as shown below:

classMyClass {
public:
int myNum;
string myString;
};

intmain() {
MyClass myObj; // Creating an object of MyClass

myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return0;
}

Creating Multiple Objects

Here’s an example of how to create multiple objects of the same class:

classCar {
public:
string brand;
};

intmain() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";

// Create another object of Car
Car carObj2;
carObj2.brand = "Ford";
// Print attribute values
cout << carObj1.brand "\n";
cout << carObj2.brand "\n";
return0;
}

Class Methods

Methods are like functions that are defined within a class. C++ has two types of methods: inside the class and outside the class. 

Inside Class Method

classMyClass {
public:
voidmyMethod() { // Method/function inside the class
cout << "Hello World!";
}
};

intmain() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return0;
}

Outside Class Method

classMyClass {
public:
voidmyMethod(); // Method declaration
};

// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}

intmain() {
MyClass myObj; // object creation
myObj.myMethod(); // Call the method
return0;
}

🔹Constructors 

A constructor is a method automatically called upon object creation. It has the same name as the class name, and no data type.

For example:

classFir_Class {
public:
Fir_Class() { // Constructor
cout << "Hello World!";
}
};

intmain() {
Fir_Class myObj; // call the constructor
return0;
}

🔹Access Specifiers 

Access specifiers define the access of the class members and variables. C++ supports three types of access specifiers:

  • Public: Class members and variables are accessible from outside the class. 
  • Private: Class members and variables are accessible only within the class and not outside the class. 
  • Protected: Class members and variables are accessible only in their subclasses. 

🔹Encapsulation 

Encapsulation helps you hide sensitive data from the users. Here, we use the private access specifier for declaring the variables and methods. If you want to allow others to read or modify those variables and methods, you must use the public get and set methods. 

For example:

#include <iostream>
usingnamespacestd;

classEmployee {
private:
int name;

public:
// Setter
voidsetName(int n) {
name= s;
}
// Getter
intgetName() {
return name;
}
};

intmain() {
Employee myObj;
myObj.setName("Bob");
cout << myObj.getName();
return0;
}

🔹Inheritance 

C++ supports inheritance, allowing you to inherit the members and variables of one class to another. The inheriting class is the child class and the other is the parent class. You must use the (:) symbol to inherit:

// Parent class
classVehicle {
public:
string brand = "Ford";
voidsound() {
cout << "honk \n" ;
}
};

// Child class
classCar: public Vehicle {
public:
string model = "Mustang";
};

intmain() {
Car myCar;
myCar.sound();
cout << myCar.brand + " " + myCar.model;
return0;
}

🔹Polymorphism 

Polymorphism specifies the “many forms.” It is the ability of a single message to be displayed in multiple forms and takes place when you have multiple child classes and one base class. 

For example:

// Parent class
classAnimal {
public:
voidsound() {
cout << "The animal makes a sound \n" ;
}
};

// Child class
classPig : public Animal {
public:
voidsound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
classDog : public Animal {
public:
voidsound() {
cout << "The dog says: bow wow \n" ;
}
};
intmain() {
Animal ani;
Pig myPig;
Dog myDog;

ani.sound();
myPig.sound();
myDog.sound();
return0;
}

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.

🔹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();
}

🔹Reading the file

It allows us to read the file line by line

getline()

🔹Opening a File

It opens a file in the C++ program

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

🔹OPEN MODES





🔹in

Opens the file to read(default for ifstream)

fs.open ("test.txt", std::fstream::in)

🔹out

Opens the file to write(default for ofstream)

fs.open ("test.txt", std::fstream::out)

🔹binary

Opens the file in binary mode

fs.open ("test.txt", std::fstream::binary)

🔹app

Opens the file and appends all the outputs at the end

fs.open ("test.txt", std::fstream::app)

🔹ate

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

fs.open ("test.txt", std::fstream::ate)

🔹trunc

Removes the data in the existing file

fs.open ("test.txt", std::fstream::trunc)

🔹nocreate

Opens the file only if it already exists

fs.open ("test.txt", std::fstream::nocreate)

🔹noreplace

Opens the file only if it does not already exist

fs.open ("test.txt", std::fstream::noreplace)

🔹Closing a file

It closes the file

myfile.close()

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 except block

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

Also Checkout Other Articles:

Checkout Linkedin Assessment Answers – All LinkedIn Skill Assessment Answers | 100% Correct Answers | Free Quiz With LinkedIn Badge

Checkout Cognitive Classes Quiz Answers – All Cognitive Classes Answers | Free Course With Certificate | Free Cognitive Class Certification 2021

Checkout IBM Data Science Professional Certificate Answers – IBM Data Science Professional Certificate All Courses Answers | Free Data Science Certification 2021

Checkout Semrush Course Quiz Answers – Free Quiz With Certificate | All Semrush Answers For Free | 100% Correct Answers

Checkout Google Course Answers – All Google Quiz Answers | 100% Correct Answers | Free Google Certification

Checkout Hubspot Course Certification Answers – All Hubspot Quiz Answers | 100% Correct Answers | Hubspot Certification 2021

Checkout Hackerrank SQL Programming Solutions –Hackerrank SQL Programming Solutions | All SQL Programming Solutions in Single Post

Checkout Hackerrank Python Programming SolutionsHackerrank Python Programming Solutions | All Python Programming Solutions in Single Post

Checkout Hackerrank Java Programming SolutionsHackerrank JAVA Programming Solutions | All JAVA Programming Solutions in Single Post

Checkout Hackerrank C++ Programming SolutionsHackerrank C++ Programming Solutions | All C++ Programming Solutions in Single Post

Checkout Hackerrank C Programming Solutions Certification Answers –Hackerrank C Programming Solutions | All C Programming Solutions in Single Post

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock