-
C++
is developed by Bjarne Stroustrup as an extension to C language. -
It is a cross-platform and object-oriented programming language.
-
It is used to create high-performance applications.
-
It provides high-level of control over system resources and memory.
-
C++
:-
Supports both procedural & object-oriented programming.
-
Encapsulate both Data & Functions together as an object.
-
Supports both Built-in & User-defined data types.
-
Object driven language beacause of OOPs.
-
Namespace features are present in
C++ programming
to avoid name collisions. -
Standard IO header is
#include <iostream.h>
or#include <iostream>
.
-
-
C
:-
Supports procedural programming but not OOPs.
-
Data & Functions are separated because of procedural programming.
-
Supports only Built-in data types but not User-defined data types.
-
Function driven language because it is procedural programming.
-
Namespace features are not present in
C-programming
. -
Standard IO header is
#include <stdio.h>
or#include <stdio>
.
Learn more
about differences betweenC++
&C
. -
-
A
C++
compiler installed on your system to compileC++
code into machine readable format. Most widely usedC++
compilers are:-
GNU Compiler Collection (GCC):
download here
-
Clang
-
Microsoft Visual C++ Compiler (For Microsoft VS code user)
-
-
A Text-editor or an Integrated Development Environment (IDE).
-
Text-editor : Notepad++, Sublime text, Atom.
-
IDE : Turbo C/C++, Visual Studio Code, Code::Blocks, Eclipse, Xcode.
-
After complete installation of an IDE and a text-editor.
-
Write your code in the text-editor and save it with
.cpp
/.cc
/.cxx
/.c++
extension. -
Once
.cpp
file is saved, open any terminal or command prompt. -
Navigate to the folder where
.cpp
files are saved. -
Now Compile and Run with the following command:
-
To Build / Compile : Write command
g++ -o filename filename.cpp
org++ -std=c++11 filename.cpp -o filename
in command line and Hit Enter.// To compile / build C++ code. >> g++ -o filename filename.cpp OR >> g++ -std=c++11 demo.cpp -o demo
-
To Run : Write given command below in command line and Hit Enter.
// To run C++ code. >> filename.exe // In window cmd prompt. OR >> ./filename // In VS Code terminal
-
-
Life cycle of
C++
code involves the following steps:-
Creating source code and save source code with some filename followed by appropriate extension. such as
.cpp
,.c++
,.cc
or.cxx
. -
Compile the code.
-
On successful compilation of source code, it will create an object file with extension
.obj
. -
Then the object file is linked with required liberary for the proper execution of code.
-
After that an executable file is created with the name
filename.exe
. -
Now the code is ready for execution.
-
-
Here is the basic structure of
C++
code.// Basic structure of C++ code. #include <iostream> using namespace std; int main() { // Code goes here return 0; }
-
Line 1: This is a single line comment, not executable by compiler.
-
Line 3: consists of a Preprocessor Directives & Header File Liberary.
-
Preprocessor directives:
#include
,#define
etc.-
It instructs the compiler and processed before code compilation. It starts with hash (
#
) character. -
#include
: Used to include header file liberary.#include <iostream> #include <cmath> #include <string>
-
#define
: Used for defining constant or macros.// Defining constant. // Syntax: #define constName constVal
// Defining Macros. // Syntax: #define MACRO_NAME(parameters) macro_body // Example: #define SQUARE(x) ((x)*(x))
-
-
Header file liberary:
<iostream>
,<cmath>
,<ctime>
,<fstream>
,<string>
etc.-
Each header file liberary offers a wide range of functionalities to use within the
C++
code. -
<iostream>
: Provides facilities for performing input and output operations.1. It defines several classes and objects that allow you to work with input streams (
std::cin
) and output streams (std::cout
,std::cerr
,std::clog
).2. Provides escape characters like (
std::endl
,std::ends
) -
<cmath>
: Provides a collection of mathematical functions.1. Trigonometric functions:
sin(x)
,cos(x)
,tan(x)
,asin(x)
,acos(x)
,atan(x)
,sinh(x)
,cosh(x)
,tanh(x)
etc.2. Exponential & Logarithmic Functions:
exp(x)
,log(x)
,log10(x)
,log2(x)
,pow(x, y)
etc.3. Square root and Absolute functions:
sqrt(x)
,fabs(x)
4. Rounding functions:
ceil(x)
,floor(x)
,round(x)
etc. -
<ctime>
: Provides functionality for working with date and time information. -
<string>
: Defines the string class and related functions for string manipulation.#include <string>
1. String declaration and initialization:
std::string str1 = "Hello World!";
2. Strings concatenation:
std::string str1 = "Hrishikesh "; std::string str2 = "Kumar"; std::string result = str1 + str2; // Output: Hrishikesh Kumar
3. Accessing character from string:
std::string str1 = "Hrishikesh"; char i_th_char = str[i]; char j_th_char = str[j];
4. String manipulation:
-
Finding substrings:
// find index position of first matched character. std::string str1 = "hrishikesh"; size_t k_pos = str1.find("k"); std::cout << k_pos;
-
Erasing substrings:
// erase 3 characters starting from index-3. std::string str1 = "hrishikesh"; std::cout << str1.erase(3,3);
-
Replacing substrings:
// replace 3 characters starting from index-3 by "Kumar". std::string str1 = "hrishikesh"; std::cout << str1.replace(3,3,"Kumar");
5. String conversion:
-
String to Integer: (
stoi(str)
)// convert string into integer value. std::string str1 = "5"; int num = std::stoi(str1); std::cout << "String to int: " << num ;
-
String to Float: (
stof(str)
)// convert string into float value. std::string str1 = "5.755"; float num = std::stof(str1); std::cout << "String to float: " << num ;
-
Integer/Float to String: (
to_string(int_num/float_num)
)// convert integer into string. // convert int/float into string. float num1 = 56.3; int num2 = 435; std::string str1 = std::to_string(num1); std::string str2 = std::to_string(num2); std::cout << "float to string: " << str1 << std::endl; std::cout << "int to string: " << str2;
-
NOTE : Never terminates the header files with semicolon (
;
) -
-
-
Line 5:
using namespace std;
It includesnamespace
standard liberary to prevent naming conflicts.-
Used to organize code into logical groups.
-
Allows to remove prefix
std::
from every standard liberary functions. -
When we use
using namespace std;
directives. Then --
std::cout
can be written ascout
. -
std::cin
can be written ascin
. -
std::endl
can be written asendl
etc.
-
-
-
Line 7:
int main()
It is themain()
function that we'll see in every C++ code.-
Actually code execution begins inside
main()
function. -
main()
function must have a return type ofint
.
-
-
Line 7 col-12: (
{
) : Begins themain()
function body. -
Line 8: Spaces for function body to be written here enclosed within curly braces (
{
// function body}
). -
Line 9:
return 0;
Terminates the code execution insidemain()
function. -
Line 10 col-1 : (
}
) : Ends themain()
function body.
-
cout
:-
Used with (
<<
) to write/print output values/text on console/display. -
By default
cout
does not insert any new line automatically after the completion ofcout
statement(s). -
Use newline-character (
\n
) orendl
to jump to new line.#include <iostream> using namespace std; int main(){ cout<<"hello world"; cout<<"This is first cpp programm."; return 0; } /* =============================== */ /* Output: */ /* =============================== */ hello worldThis is first cpp programm.
-
-
cin
:-
Used with (
>>
) to Reads data from the keyboard or other input devices. -
It automatically adds newline-character (
\n
) after reading the input data(s). -
cin
considers white-space as terminating character. -
To retain white-space, use
getline()
method.// Syntax: getline(cin, stringName); // instead of `cin >> stringName;`
-
e.g:-
[NOTE :]
1. (
>>
) : known as Stream extraction operator or simply Extraction operator.2. (
<<
) : known as Stream insertion operator or simply Insertion operator. -
-
endl
: Terminate the current line and jump into a new-line.
-
newline character (
\n
) : Terminate the current line and jump into a new-line. -
tabspace character (
\t
) : Insert a tabspace (that is equivalent to 4-space character) between current-line and new-line or within a line. -
backslash character (
\\
) : Insert a backslash character. -
double quote character (
\"
) : Insert a double quote character.-
e.g:-
#include <iostream> using namespace std; int main(){ cout<<"1. New-line character.\n"; cout<<"2. tab-space\tcharacter."<<endl; cout<<"3. backslash\\character.\n"; cout<<"4. \"double quote\""; return 0; } /* ================================= */ /* Output: */ /* ================================= */ 1. New-line character. 2. tab-space character. 3. backslash\character. 4. "double quote"
-
-
There are two ways to write comment in
Cpp
.// This is single line comment. /* This is multiline comment. */
-
Variables: Variables in
C++
are like containers to store data values. -
Variables declaration: There can be couple of ways to declare a variable in
C++
.-
Assign value to variable while declaring it.
// Syntax: dataType varName = value; // Example: int num = 24; float n = 2.34; char character = 'H'; string str = "Hrishikesh";
-
Declaring varible and assigning it later.
// Syntax: dataType varName; varName = value; // Example: float n; string str; n = 2.01; str = "C++";
-
Declaring more than one variable of same type in a single statement.
// Syntax: dataType var1 = val1, var2 = val2, ..., varN = valN; // Example: int a = 12, b = 43, c = 23; string fname = "Hrishikesh", lname = "Kumar";
-
Declaring variables and then assigning it later.
// Syntax: dataType var1, var2, ..., varN; var1 = val1, var2 = val2, ..., varN = valN; // If multiple variables have same value. var1 = var2 = ... = value // Example: int a, b, c, d, e, f; a = 12, b = 43, c = 23; d = e = f = 101;
-
NOTE : If a variable is assigned with new value, its earlier value will be overwritten if any.
-
A value is declared as constant which is not likely to be changed further in the code.
-
A constant declaration must follow the rules to avoid any occurance of errors in following cases:
-
It is declared using
const
keyword inC++
.// Syntax: const dataType varName = value; // Example: const float PI = 3.1428; const int daysPerWeek = 7;
-
Identifiers are actually used to name variables. There are some important rules to follow while creating an identifier/variable.
- It must contains only letters, digits and underscores (
_
). - It must start with either letter or underscore but not digit.
- Identifiers are case-sensitive.
- White-space(s) are not allowed in identifier.
- Special characters (!, @, #, $, %...etc.) are not allowed except underscore ( _ ).
- Reserved keyword in Cpp are not allowed to be used as an identifier.
- It must contains only letters, digits and underscores (
-
Various primitive data types that are supported in
C++
are:-
bool
( 1 byte ) : Only two values: true = 1, false = 0. -
char
( 1 byte ) : can be assined with only one character within single quote : like'e'
. -
int
( 2 or 4 bytes ) : stores only non-decimal numbers with smaller range. -
float
( 4 bytes ) : stores only decimal numbers with smaller range. -
double
( 8 bytes ) : stores only decimal numbers with larger range. -
string
( 32 bytes ) : stores sequence of characters within double quotes (" "
) and Not built-in type, but behaves like one.
-
-
It sets the number of digits after decimal (
.
).-
float
: 6 or 7 digits. -
double
: 15 digits.
-
-
Qualifiers in
C++
are used to manipulate the size (or range) and/or sign or behaviour of the primitive data types. such as int, float, double.-
Qualifiers that are used to manipulate the sizes of data types:
-
short
( 2 bytes ) : stores only non-decimal numbers with smaller range thanint
generally. -
long
( 4 bytes ) : stores only non-decimal numbers with larger range thanint
. -
long long
( 8 bytes ) : stores only non-decimal numbers with larger range thanlong
. -
double long
( 16 bytes ) : stores only decimal numbers with larger range.
-
-
Qualifiers that are used to manipulate the sign of data types:
-
signed
( 4 bytes ) : Stores both positive and negative values. -
unsigned
( 4 bytes ) : Stores only positive values.
-
-
Qualifiers that are used to manipulate the behaviour of data types:
const
: It restricts the re-assigning new values to the variable prefixed withconst
keyword. Any modification results in an errors.
-
-
Operators are used to perform specific operations on operand(s) (variable(s) or value(s)).
-
There are typically three types of operators:
- Unary operators: Unary operators operates on single operands.
- Increment (
++
) - Decrement (
--
) - Logical operator (
!
) - Bitwise operator (
~
)
- Increment (
- Binary operators: Binary operators operates on two operands.
- Arithmatic operators (
+
,-
,*
,/
,%
) - Assignment operators (
=
,+=
,-=
,*=
,/=
,%=
) - Relational or Comparison operator (
==
,!=
,>
,<
,>=
,<=
) - Logical operator (
&&
,||
) - Bitwise operator (
&
,|
,^
,<<
,>>
)
- Arithmatic operators (
- Ternary operators: Ternary operators involves three operands or expressions or components.
- Conditional/Ternary operator (
condition ? exp1 : exp2
)
- Conditional/Ternary operator (
- Unary operators: Unary operators operates on single operands.
-
Arithmatic operators are binary operators that are used to perform mathematical operations on operands. Various arithmatic operators are:
-
Addition (
+
) : used to adds two or more numbers. -
Subtraction (
-
) : used to find difference between two numbers. -
Multiplication (
*
) : used to find product of two or more numbers. -
Division (
/
) : used to divide a number by another number. -
Modulus (
%
) : used to find remainder when a number is divided by another number.
-
-
Assignment operators are also type of binary operators which is shorter way to use arithmatic operators.
-
Assign updated value to left operand by performing some mathematical task on itself.
- Assignment (
=
) : used to assign the value of right operand to the left operand.
-
Addition assignment (
+=
) : used to update value of left operand by adding value of right operand to the initial value of left operand. -
Subtraction assignment (
-=
) : used to update value of left operand by subtracting value of right operand from the initial value of left operand. -
Multiplication assignment (
*=
) : used to update value of left operand by multiplying value of right operand with initial value of left operand. -
Division assignment (
/=
) : used to update value of left operand after dividing left operand by right operand. -
Modulus assignment (
%=
) : It stores the remainder to left operand when number itself (value of left operand) is divided by right operand. -
Bitwise-AND assignment (
&=
) -
Bitwise-OR assignment (
|=
) -
Bitwise-XOR assignment (
^=
) -
Right-Shift assignment (
>>=
) -
Left-Shift assignment (
<<=
)
- Increment (
++
) : It is used to update the value of operand by adding value 1 to its initial value. - Decrement (
--
) : It is used to update the value of operand by subtracting value 1 from its initial value.
[NOTE:] Both these operator can be used in two ways:
1. post-increment or post-decrement.
2. pre-increment or pre-decrement.
-
Relational operators are also binary operators used to compare two values and determine the relationship between them.
-
It returns a boolean value (
0
or1
) based on the comparison result. -
Different types of relational operators are:
-
Is Equal to (
==
) : Checks if the values of two operands are equal.-
Returns
1
if values are equal. -
Returns
0
if values are not equal.
-
-
Not Equal to (
!=
) : Checks if the values of two operands are not equal.-
Returns
1
if values are not equal. -
Returns
0
if values are equal.
-
-
Greater than (
>
) : Checks if the value of the left operand is greater than the value of the right operand.-
Returns
1
if left operand>
right operand. -
Returns
0
if left operand<
right operand.
-
-
Less than (
<
) : Checks if the value of the left operand is less than the value of the right operand.-
Returns
1
if left operand<
right operand. -
Returns
0
if left operand>
right operand.
-
-
Greater than or Equal to (
>=
) : Checks if the value of the left operand is greater than or equal to the value of the right operand.-
Returns
1
if left operand>=
right operand. -
Returns
0
if left operand<
right operand.
-
-
Less than or Equal to (
>=
) : Checks if the value of the left operand is less than or equal to the value of the right operand.-
Returns
1
if left operand<=
right operand. -
Returns
0
if left operand>
right operand.
-
-
-
Logical operators are used to perform logical operations on boolean values or expressions.
-
It returns boolean value (
1
or0
) as result after evaluating the expression. -
There are three types of logical operation in
C++
:-
Logical AND (
&&
) : Checks if all the boolean values and/or relational expressions are true.-
Returns
1
: if all the boolean values and/or expressions are true. -
Returns
0
: if atleast one boolean value or expression are false.
[NOTE:]
As early as the expression encounters afalse
value or condition, it stops further evaluation of the expression and return0
. -
-
Logical OR (
||
) : Checks if atleast one boolean values or relational expressions are true.-
Returns
1
: if atleast one boolean value or relational expression are true. -
Returns
0
: if all the boolean values and/or relational expressions are false.
[NOTE:]
As early as the expression encounters atrue
value or condition, it stops further evaluation of the expression and return1
. -
-
Logical NOT (
!
) : It is used to negate the value of its operand.-
Returns
1
: if the value of operand isfalse
. -
Returns
0
: if the value of operand istrue
.
[NOTE:]
The logical NOT operator is often used in conditional statements, loops, and boolean expressions to modify the logical state of expressions. -
-
-
It performs bit-level specific operations on integral operands (integer data types).
-
These operators manipulate individual bits of integers directly.
-
Firstly, it converts the operands into binary numbar (that is in form of
0
&1
). then perform bitwise operation on each bits. -
There are various types of bitwise operators:
-
Bitwise AND (
&
) : Sets each bit to1
if corresponding bits of each operands are 1, otherwise sets it to0
. -
Bitwise OR (
|
) : Sets each bit to1
if either of the corresponding bits of operands is/are 1, otherwise sets it to0
. -
Bitwise XOR (
^
) : Sets each bit to1
if only one of the two corresponding bits of the operands is 1, otherwise sets it to 0. -
Bitwise NOT (
~
) : It reverse each bits of an operand from1
to0
and vice-versa. -
Right Shift (
>>
) : Shifts the bits of the left operand to the right by a number of positions specified by the right operand. Vacated bits are filled with zeros. -
Left Shift (
<<
) : Shifts the bits of the left operand to the left by a number of positions specified by the right operand. Vacated bits are filled with zeros.
-
-
It is a unique operator in programming languages that operands on three operands.
-
It is oftenly used as shorthand for
if-else
conditional statement. -
It is also known as Conditioinal operators.
-
Syntex:
// Syntax : Conditional Operator condition ? expression1 : expression2
-
Working of conditional operators (
? :
) - It takes three operands as given:1. condition : It is a test condition to evaluate result on the basis of which conditional statement will produce the result either expression1 or expression2.
2. expression1 : This expression will be executed only if the condition is
true
.3. expression2 : This expression will be executed only if the condition is
false
.