Programming in C++
Programming in C++
Programming in C++
Nilkani Mort
2 Programming in C++
About book
ePUB is an open, industry-standard format for eBooks. However,
support of ePUB and its many features varies across reading devices
and applications. Use your device or app settings to customize the
presentation to your liking. Settings that you can customize often
include font, font size, single or double column, landscape or portrait
mode, and figures that you can click or tap to enlarge. For additional
information about the settings and features on your reading device or
app, visit the device manufacturer’s Web site. Many titles include
programming code or configuration examples. To optimize the
presentation of these elements, view the eBook in single-column,
landscape mode and adjust the font size to the smallest setting. In
addition to presenting code and configurations in the reflowable text
format, we have included images of the code that mimic the
presentation found in the print book; therefore, where the reflowable
format may compromise the presentation of the code listing, you will
see a “Click here to view code image” link. Click the link to view the
print-fidelity code image. To return to the previous page viewed, click
the Back button on your device or app.
3 Programming in C++
Acknowledgment
I’d like to thank sau prakashani for encouraging me to produce this new
book of c++ programming for beginner’s. I’m particularly grateful to
buddhadev maity for taking the time to cast his critical eye over the
entire draft text; he did not pull any punches in his extensive review
comments and the book is surely battered as a result. My thanks to all
the people at a press, who have done their usual outstanding
professional job of converting my initial text with all its imperfections
into this finished product. Any imperfections that remain are
undoubtedly mine.
My sincere thanks to those readers of this book who took the
trouble to point out my mistake and identify areas that could be better
explained. I also greatly appreciate all those who wrote or e-mailed just
to say how it helped them get started in programming.
4 Programming in C++
Contents
INTRODUCTION TO C++
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World";
return 0;
}
Learning C++
C vs C++
No. C C++
1 C follows the procedural C++ is multi-paradigm. It
style programming. supports both procedural and
object-oriented.
2 Data is less secured in C. In C++, you can use modifiers
for class members to make it
inaccessible for outside users.
3 C follows the top-down C++ follows the bottom-up
approach. approach.
4 C does not support function C++ supports function
overloading. overloading.
7 Programming in C++
Let's see the programming languages that were developed before the
C++ language.
Object-Oriented Programming
● Encapsulation
● Data hiding
● Inheritance
● Polymorphism
have been written using C++. C++ also has been used in
developing the most popular database system called MySQL.
❖ Programming Languages Development: C++ has been used
extensively in developing new programming languages like C#,
Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog,
etc.
❖ Computation Programming: C++ is the best friend of scientists
because of the fast speed and computational efficiencies.
❖ Games Development: C++ is extremely fast which allows
programmers to do procedural programming for CPU intensive
functions and provides greater control over hardware, because of
which it has been widely used in the development of gaming
engines.
❖ Embedded System: C++ is being heavily used in developing
Medical and Engineering Applications like software for MRI
machines, high-end CAD/CAM systems, etc.
This list goes on, there are various areas where software developers
are happily using C++ to provide great software. I highly recommend
you to learn C++ and contribute great software to the community.
10 Programming in C++
Features of C++
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
Compiler Object
8. Recursion based oriented
9. Extensible Extensi
ble Simple
10.Object-Oriented
11.Compiler based
Recursi
on Feature Of Portable
C++
Mid-level
Fast program
Speed ming
Memory Structu
Rich red
Manage
Library progra
ment
mming
1. Simple
11 Programming in C++
5. Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.
6. Memory Management
It supports the feature of dynamic memory allocation. In C++ language,
we can free the allocated memory at any time by calling the free()
function.
7. Speed
The compilation and execution time of C++ language is fast.
12 Programming in C++
8. Pointer
C++ provides the feature of pointers. We can directly interact with the
memory by using the pointers. We can use pointers for memory,
structures, functions, array etc.
9. Recursion
In C++, we can call the function within the function. It provides code
reusability for every function.
10. Extensible
C++ language is extensible because it can easily adopt new features.
11. Object Oriented
C++ is object oriented programming language. OOPs makes
development and maintenance easier whereas in Procedure-oriented
programming language it is not easy to manage if code grows as project
size grows.
12. Compiler based
C++ is a compiler-based programming language, it means without
compilation no C++ program can be executed. First, we need to compile
our program using a compiler and then we can execute our program.
C++ I/O operation is using the stream concept. Stream is the sequence
of bytes or flow of data. It makes the performance fast.
If bytes flow from main memory to device like a printer, display screen,
or a network connection, etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network
connection, etc to main memory, this is called as input operation.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
15 Programming in C++
Output:
End of line
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
17 Programming in C++
Where type is one of C++ types (such as int), and variable is the name of
the variable (such as x or myName). The equal sign is used to assign
values to the variable.
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign
the value later:
Example:
int myNum;
myNum = 15;
cout << myNum;
Other Types
Example:
int myNum = 5; // Integer (whole number without
decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
18 Programming in C++
Constants
However, you can add the const keyword if you don't want others (or
yourself) to override existing values (this will declare the variable as
"constant", which means unchangeable and read-only):
Example:
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
The data type specifies the size and type of information the variable will
store:
decimal digits
Use int when you need to store a whole number without decimals, like
35 or 1000, and float or double when you need a floating point number
(with decimals), like 9.99 or 3.14515.
int
float
double
double myNum = 19.99;
cout << myNum;
Booleans
A boolean data type is declared with the bool keyword and can only
take the values true or false. When the value is returned, true = 1 and
false = 0.
21 Programming in C++
Example:
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean values are mostly used for conditional testing, which you will
learn more about in a later chapter.
Characters
The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c':
Example:
#include<iostream>
using namespace std;
int main () {
char myGrade = 'B';
cout << myGrade;
return 0;
}
22 Programming in C++
Example:
#include<iostream>
using namespace std;
int main () {
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
return 0;
}
C++ Keywords
The reserved words may not be used as constant or variable or any
other identifier names.
A list of 32 Keywords in C++ Language which are also available in C
language is given below.
C++ Operators
Unary Operator
Relational Operators
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand,
if yes then condition becomes true.
27 Programming in C++
Logical Operators
Ternary Operator
Syntax
Example:
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. int main() {
5. int time = 20;
6. string result = (time < 18) ? "Good day." : "Good evening.";
7. cout << result;
8. return 0;
}
Output:
Good evening.
29 Programming in C++
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C++ if Statement
Syntax:
1. if(condition){
2. //code to be executed
3. } Conditin
Example:
If code
#include<iostream>
using namespace std;
After if code
int main () {
int num = 10;
30 Programming in C++
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Output:
It is even number
The C++ if-else statement also tests the condition. It executes if block if
condition is true otherwise else block is executed.
1. if(condition){
2. //code if condition is true If-else Statement
3. }else{
4. //code if condition is false False
5. }
Conditio Else code
n
Example:
If code
1. #include<iostream>
2. using namespace std;
3. int main () { After if
4. int num = 11;
5. if (num % 2 == 0)
6. {
31 Programming in C++
Output:
It is odd number
The C++ if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
32 Programming in C++
Condition 1
Condition2
Condition n
Example:
1. #include<iostream>
33 Programming in C++
31. {
32. cout<<"A+ Grade";
33. }
34. }
Output:
C++ switch
The C++ switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement in C++.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
35 Programming in C++
13. }
expression
Switch Statement
matched
Case-1
Statement-1 break
unmatched
Case-2 matched
Statement-2 break
unmatched
Case-3 matched
Statement-n break
unmatched
default
Statement n+1 break
36 Programming in C++
Example:
1. #include<iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 10: cout<<"It is 10"; break;
10. case 20: cout<<"It is 20"; break;
11. case 30: cout<<"It is 30"; break;
12. default: cout<<"Not 10, 20 or 30"; break;
13. }
14. }
Output:
Enter a number:
10
It is 10
37 Programming in C++
Loops in C++
● for loop
● while loop
Fals
Condition
● do-while loop e
True
3. Statement: The statement of the loop is executed each time until the
second condition is false.
Syntax:
1. #include<iostream>
2. using namespace std;
3. int main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }
Output:
1
2
3
4
5
6
7
8
39 Programming in C++
9
10
1. #include<iostream>
2. using namespace std;
3.
4. int main () {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. cout<<i<<" "<<j<<"\n";
8. }
9. }
10. }
Output:
11
12
13
21
22
23
31
32
33
40 Programming in C++
Syntax:
1. while(condition){
2. //code to be executed
3. }
1. #include<iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }
Output:
41 Programming in C++
1
2
3
4
5
6
7
8
9
10
In C++, we can use while loop inside another while loop, it is known as
nested while loop. The nested while loop is executed fully when the outer
loop is executed once.
1. #include<iostream>
2. using namespace std;
3. int main () {
4. int i=1;
5. while(i<=3)
6. {
7. int j = 1;
8. while (j <= 3)
42 Programming in C++
9. {
10. cout<<i<<" "<<j<<"\n";
11. j++;
12. }
13. i++;
14. }
15. }
Output:
11
12
13
21
22
23
31
32
33
The C++ do-while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed and you must have to execute
the loop at least once, it is recommended to use do-while loop.
43 Programming in C++
1. #include<iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9. }
Output:
1
2
3
4
44 Programming in C++
5
6
7
8
9
10
In C++, if you use do-while loop inside another do-while loop, it is known as
nested do-while loop. The nested do-while loop is executed fully for each
outer do-while loop.
1. #include<iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. int j = 1;
7. do{
8. cout<<i<<"\n";
9. j++;
10. } while (j <= 3) ;
11. i++;
12. } while (i <= 3) ;
13. }
45 Programming in C++
Output:
11
12
13
21
22
23
31
32
33
The C++ break is used to break loop or switch statement. It breaks the
current flow of the program at the given condition. In case of inner loop, it
breaks only inner loop.
Let's see a simple example of C++ break statement which is used inside the
loop.
1. #include<iostream>
2. using namespace std;
3. int main() {
4. for (int i = 1; i <= 10; i++)
5. {
6. if (i == 5)
46 Programming in C++
7. {
8. break;
9. }
10. cout<<i<<"\n";
11. }
12. }
Output:
1
2
3
4
The C++ break statement breaks the inner loop only if you use break
statement inside the inner loop.
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. break;
9. }
47 Programming in C++
Output:
11
12
13
21
31
32
33
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
48 Programming in C++
5. for(int i=1;i<=10;i++){
6. if(i==5){
7. continue;
8. }
9. cout<<i<<"\n";
10. }
11. }
Output:
1
2
3
4
6
7
8
9
10
C++ Comments
The C++ comments are statements that are not executed by the compiler.
The comments in C++ programming can be used to provide an explanation
of the code, variable, method or class. By the help of comments, you can
hide the program code also.
The single line comment starts with // (double slash). Let's see an example
of single line comment in C++.
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 11; // x is a variable
6. cout<<x<<"\n";
7. }
Output:
11
The C++ multi line comment is used to comment multiple lines of code. It is
surrounded by slash and asterisk (/∗ ..... ∗/). Let's see an example of multi
line comment in C++.
1. #include<iostream>
2. using namespace std;
50 Programming in C++
3. int main()
4. {
5. /* declare and
6. print variable in C++. */
7. int x = 35;
8. cout<<x<<"\n";
9. }
Output:
35
C++ Functions
Functions are used to perform certain actions, and they are important for
reusing code: Define the code once and use it many times.
Create a Function
Syntax
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
● Declared functions are not executed immediately. They are "saved for
later use", and will be executed later when they are called.
● To call a function, write the function's name followed by two
parentheses () and a semicolon ;
● In the following example, myFunction() is used to print a text (the
action), when it is called:
Example:
1. #include<iostream>
52 Programming in C++
3. void myFunction() {
4. cout << "I just got executed!\n";
5. }
6. int main() {
7. myFunction();
8. myFunction();
9. myFunction();
10. return0;
11. }
Output:
Example:
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma:
Syntax
The following example has a function that takes a string called fname as
parameter. When the function is called, we pass along a first name, which is
used inside the function to print the full name:
Example:
1. #include<iostream>
2. #include<string>
3. using namespace std;
7. int main() {
8. myFunction("Liam");
9. myFunction("Jenny");
10. myFunction("Anja");
11. return0;
12. }
Output:
55 Programming in C++
Liam Refsnes
Jenny Refsnes
Anja Refsnes
Return Values
The void keyword, used in the examples above, indicates that the function
should not return a value. If you want the function to return a value, you
can use a data type (such as int, string, etc.) instead of void, and use
the return keyword inside the function:
Example:
1. #include<iostream>
2. using namespace std;
3. int myFunction(int x) {
4. return 5 + x;
5. }
6. int main() {
7. cout << myFunction(3);
8. return0;
9. }
10.
Output:
8
56 Programming in C++
1. #include<iostream>
2. using namespace std;
6. int main() {
7. cout << myFunction(5, 3);
8. return0;
9. }
Output:
8
Pass By Reference
Example:
1. #include<iostream>
2. using namespace std;
4. int z = x;
5. x = y;
6. y = z;
7. }
8. int main() {
9. int firstNum = 10;
10. int secondNum = 20;
16. return 0;
17. }
Output:
Before swap:
1020
After swap:
2010
58 Programming in C++
With function overloading, multiple functions can have the same name
with different parameters:
Example:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which has two functions that add numbers
of different type:
1. #include<iostream>
2. using namespace std;
9. int main() {
10. int myNum1 = plusFuncInt(8, 5);
11. double myNum2 = plusFuncDouble(4.3, 6.26);
12. cout << "Int: " << myNum1 << "\n";
13. cout << "Double: " << myNum2;
14. return 0;
59 Programming in C++
15. }
Output:
Int: 13
Double: 10.56
Instead of defining two functions that should do the same thing, it is better
to overload one.
1. #include<iostream>
2. using namespace std;
9. int main() {
10. int myNum1 = plusFunc(8, 5);
11. double myNum2 = plusFunc(4.3, 6.26);
12. cout << "Int: " << myNum1 << "\n";
13. cout << "Double: " << myNum2;
60 Programming in C++
14. return 0;
15. }
Output:
Int: 13
Double: 10.56
Array in C++
Like other programming languages, array in C++ is a group of similar types
of elements that have contiguous memory location.
o Random Access
o Fixed size
2. Multidimensional Array
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
62 Programming in C++
11. }
Output:
10
0
20
0
30
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int test[3][3]; //declaration of 2D array
6. test[0][0]=5; //initialization
7. test[0][1]=10;
8. test[1][1]=15;
9. test[1][2]=20;
63 Programming in C++
10. test[2][0]=30;
11. test[2][2]=10;
12. //traversal
13. for(int i = 0; i < 3; ++i)
14. {
15. for(int j = 0; j < 3; ++j)
16. {
a. cout<< test[i][j]<<" ";
17. }
18. cout<<"\n"; //new line at each row
19. }
20. return 0;
21. }
Output:
5 10 0
0 15 20
30 0 10
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or
indicator that points to an address of a value.
64 Programming in C++
Advantage of pointer
Usage of pointer
Declaring a pointer
Pointer Example
Let's see the simple example of using pointers printing the address and
value.
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
66 Programming in C++
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=20,b=10,∗p1=&a,∗p2=&b;
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
7. ∗p1=∗p1+∗p2;
8. ∗p2=∗p1-∗p2;
9. ∗p1=∗p1-∗p2;
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
11. return 0;
12. }
Output: