Programming in C++

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

1 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

Chapter 1: Introduction of C++

Chapter 2: Features and I/O Streams

Chapter 3: Data types and operator

Chapter 4: C++ Branching Statement

Chapter 5: C++ looping

Chapter 6: C++ Function

Chapter 7: C++ Array

Chapter 7: C++ Pointer


5 Programming in C++

INTRODUCTION TO C++

Hello World using C++

#include<iostream>
using namespace std;
int main()
{
cout << "Hello World";
return 0;
}

C++ is a middle-level programming language developed by Bjarne


Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of
platforms, such as Windows, Mac OS, and the various versions of UNIX.
This C++ tutorial adopts a simple and practical approach to describe the
concepts of C++ for beginners to advanced software engineers.
6 Programming in C++

C++ is a statically typed, compiled, general-purpose, case-sensitive,


free-form programming language that supports procedural, object-
oriented, and generic programming.

Learning C++

The most important thing while learning C++ is to focus on concepts.


The purpose of learning a programming language is to become a better
programmer; that is, to become more effective at designing and
implementing new systems and at maintaining old ones.
C++ supports a variety of programming styles. You can write in the
style of Fortran, C, Smalltalk, etc., in any language. Each style can
achieve its aims effectively while maintaining runtime and space
efficiency.

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++

5 In C, you can't use functions In C++, you can use functions


in structure. in structure.
6 C does not support reference C++ supports reference
variables. variables.
7 In C, scanf() and C++ mainly uses stream cin
printf() are mainly used for and cout to perform input and
input/output. output operations.
8 Operator overloading is not Operator overloading is possible
possible in C. in C++.
9 C programs are divided C++ programs are divided
into procedures and into functions and classes.
modules
10 C does not provide the feature C++ supports the feature of
of namespace. namespace.
11 Exception handling is not easy C++ provides exception
in C. It has to perform using handling using Try and Catch
other functions. block.

Let's see the programming languages that were developed before the
C++ language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson


8 Programming in C++

Traditional 1972 Dennis Ritchie


C
K&RC 1978 Kernighan & Dennis
Ritchie
C++ 1979 Bjarne Stroustrup

Object-Oriented Programming

C++ fully supports object-oriented programming, including the four


pillars of object-oriented development −

● Encapsulation
● Data hiding
● Inheritance
● Polymorphism

Applications of C++ Programming


As mentioned before, C++ is one of the most widely used programming
languages. It has a presence in almost every area of software
development. I'm going to list few of them here:
❖ Application Software Development: C++ programming has been
used in developing almost all the major Operating Systems like
Windows, Mac OSX and Linux. Apart from the operating systems,
the core part of many browsers like Mozilla Firefox and Chrome
9 Programming in C++

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++

C++ is an object-oriented programming language. It provides a lot


of features that are given below.

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++

C++ is a simple language in the sense that it provides a structured


approach (to break the problem into parts), rich set of library functions,
data types, etc.
2. Machine Independent or Portable
Unlike assembly language, c programs can be executed in many
machines with a little bit or no change. But it is not platform-
independent.
3. Mid-level programming language
C++ is also used to do low-level programming. It is used to develop
system applications such as kernel, driver etc. It also supports the
feature of high level language. That is why it is known as mid-level
language.

4. Structured programming language


C++ is a structured programming language in the sense that we can
break the program into parts using functions. So, it is easy to
understand and modify.

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++ Basic Input/Output


13 Programming in C++

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.

I/O Library Header Files


Let us see the common header files used in C++ programming are:

Header Function and Description


File

<iostream It is used to define the cout, cin and cerr objects,


> which correspond to standard output stream,
standard input stream and standard error
stream, respectively.

<iomanip> It is used to declare services useful for


performing formatted I/O, such as setprecision
and setw.

<fstream> It is used to declare services for user-controlled


file processing.
14 Programming in C++

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with
the standard output device, which is usually a display screen. The cout
is used in conjunction with stream insertion operator (<<) to display the
output on a console
Let's see the simple example of standard output stream (cout):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
6. }
Output:
Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the
standard input device, which is usually a keyboard. The cin is used in
conjunction with stream extraction operator (>>) to read the input from
a console.
Let's see the simple example of standard input stream (cin):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
15 Programming in C++

5. cout << "Enter your age: ";


6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }
Output:
Enter your age: 22
Your age is: 22

Standard end line (endl)

The endl is a predefined object of ostream class. It is used to insert a


new line characters and flushes the stream.
Let's see the simple example of standard end line (endl):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl;
7. }

Output:

C++ Tutorial Javatpoint


16 Programming in C++

End of line

C++ Variable Types

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different


keywords), for example:

● int - stores integers (whole numbers), without decimals, such as


123 or -123
● double - stores floating point numbers, with decimals, such as
19.99 or -19.99
● char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
● string - stores text, such as "Hello World". String values are
surrounded by double quotes
● bool - stores values with two states: true or false

Declaring (Creating) Variables

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.

To create a variable that should store a number, look at the following


example:

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

You can also declare a variable without assigning the value, and assign
the value later:

Example:

int myNum;
myNum = 15;
cout << myNum;

Other Types

A demonstration of other data types:

Example:
int myNum = 5; // Integer (whole number without
decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
18 Programming in C++

char myLetter = 'D'; // Character


string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

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'

C++ Basic Data Types


A data type specifies the type of data that a variable can store such as
integer, floating, character etc.

There are 4 types of data types in C++ language.


19 Programming in C++

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types

The data type specifies the size and type of information the variable will
store:

Data Type Size Description

int 4-bit Stores whole numbers, without decimals

float 4-bit Stores fractional numbers, containing one or


more decimals. Sufficient for storing 7 decimal
digits
double 8-bit Stores fractional numbers, containing one or
more decimals. Sufficient for storing 15
20 Programming in C++

decimal digits

boolean 1-bit Stores true or false values

char 1-bit Stores a single character/letter/number, or


ASCII values

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

int myNum = 1000;


cout << myNum;

float

float myNum = 5.75;


cout << myNum;

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++

Alternatively, you can use ASCII values to display certain characters:

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.

auto break case char Const continue default do

double else enum extern Float for goto if


23 Programming in C++

int long register return Short signed sizeof static

struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C


language are given below.

asm dunamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t

C++ Operators

Operators are used to perform operations on variables and values.


24 Programming in C++

In the example below, we use the + operator to add together two


values:
Example:
int x = 100 + 50;
C++ divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
25 Programming in C++

Arithmetic operators are used to perform common mathematical


operations.

Operator Name Example Description

+ Addition X+Y Adds together two values

- Subtraction X-Y Subtracts one value from anothe

* Multiplication X*Y Multiplies two values

/ Division X/Y Divides one value from another

% Modulus X%Y Returns the division remainder

Unary Operator

Operator Name Example Description

++ Increment X++ Increases the value of a variable


by 1
-- Decrement --X Decreases the value of a variable
by 1

Relational Operators

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then −


26 Programming in C++

Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition becomes
true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> 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 less (A < B) is 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++

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right operand,
if yes then condition becomes true.

Logical Operators

There are following logical operators supported by C++ language.

Assume variable A holds 1 and variable B holds 0, then –

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands are non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.
28 Programming in C++

Ternary Operator

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

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++

C++ Branching Statement

C++ branching statement used to check the condition. It checks Boolean


condition, means true or false. Various type of branching Statement given
below:

o if statement

o if-else statement

o nested if statement

o if-else-if ladder

C++ if Statement

The C++ if statement tests the condition. It is executed if the condition is


true.

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

C++ if-else Statement

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++

7. cout<<"It is even number";


8. }
9. else
10. {
11. cout<<"It is odd number";
12. }
13. return 0;
14. }

Output:

It is odd number

C++ if-else-if ladder Statement

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++

4. //code to be executed if condition2 is true


5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

Condition 1

Condition2

Condition n

Statement-1 Statement-2 Statement-n Statement-s

Example:

1. #include<iostream>
33 Programming in C++

2. using namespace std;


3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. if (num <0 || num >100)
8. {
9. cout<<"wrong number";
10. }
11. else if(num >= 0 && num < 50){
12. cout<<"Fail";
13. }
14. else if (num >= 50 && num < 60)
15. {
16. cout<<"D Grade";
17. }
18. else if (num >= 60 && num < 70)
19. {
20. cout<<"C Grade";
21. }
22. else if (num >= 70 && num < 80)
23. {
24. cout<<"B Grade";
25. }
26. else if (num >= 80 && num < 90)
27. {
28. cout<<"A Grade";
29. }
30. else if (num >= 90 && num <= 100)
34 Programming in C++

31. {
32. cout<<"A+ Grade";
33. }
34. }

Output:

Enter a number to check grade:66


C Grade

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++

In programming languages, loops are used to execute a set of


instructions/functions repeatedly when some conditions become true. There
are three types of loops in C++. Initialization

● for loop

● while loop
Fals
Condition
● do-while loop e

True

C++ for Loop Statement


The C++ for loop is used to iterate a part of the
program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or
Inc/dec
do-while loops.

The C++ for loop is same as C/C#. We can initialize For-loop


variable, check condition and increment/decrement ststement
value.It consists of four parts:

1. Initialization: It is the initial condition which is executed once when


the loop starts. Here, we can initialize the variable, or we can use an
already initialized variable. It is an optional condition.

2. Condition: It is the second condition which is executed each time to


test the condition of the loop. It continues execution until the condition
is false. It must return boolean value either true or false. It is an
optional condition.
38 Programming in C++

3. Statement: The statement of the loop is executed each time until the
second condition is false.

4. Increment/Decrement: It increments or decrements the variable


value. It is an optional condition.

Syntax:

1. for(initialization; condition; incr/decr){


2. //code to be executed
3. }

C++ For Loop Example

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

C++ Nested For Loop Example

Let's see a simple example of nested for loop in C++.

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++

C++ While loop


In C++, while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed, it is recommended to use while loop
than for loop.

Syntax:

1. while(condition){
2. //code to be executed
3. }

C++ While Loop Example

Let's see a simple example of while loop to print table of 1.

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

C++ Nested While Loop Example

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.

Let's see a simple example of nested while loop in C++ programming


language.

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

C++ Do-While Loop

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++

The C++ do-while loop is executed at least once because condition is


checked after the loop body.
do
Syntax:
Statement conditin
1. do{
2. //code to be executed
3. }while(condition);
True

C++ do-while Loop Example Conditin

Let's see a simple example of C++ do-while


loop to print the table of 1.
False

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

C++ Nested do-while Loop

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.

Let's see a simple example of nested do-while loop in C++.

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

C++ Break Statement

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.

C++ Break Statement Example

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

C++ Break Statement with Inner Loop

The C++ break statement breaks the inner loop only if you use break
statement inside the inner loop.

Let's see the example code:

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++

10. cout<<i<<" "<<j<<"\n";


11. }
12. }
13. }

Output:
11
12
13
21
31
32
33

C++ Continue Statement

The C++ continue statement is used to continue loop. It continues the


current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.

C++ Continue Statement Example

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.

There are two types of comments in C++.


49 Programming in C++

o Single Line comment

o Multi Line comment

C++ Single Line Comment

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

C++ Multi Line Comment

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

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

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

C++ provides some pre-defined functions, such as main(), which is used to


execute code. But you can also create your own functions to perform certain
actions.
51 Programming in C++

To create (often referred to as declare) a function, specify the name of the


function, followed by parentheses ():

Syntax

void myFunction() {
// code to be executed
}

Example Explained

● myFunction() is the name of the function


● void means that the function does not have a return value. You will
learn more about return values later in the next chapter
● inside the function (the body), add code that defines what the function
should do

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:

Inside main, call myFunction():

1. #include<iostream>
52 Programming in C++

2. using namespace std;

3. void myFunction() {
4. cout << "I just got executed!\n";
5. }

6. int main() {
7. myFunction();
8. myFunction();
9. myFunction();
10. return0;
11. }

Output:

I just got executed!


I just got executed!
I just got executed!

Function Declaration and Definition

A C++ function consists of two parts:

● Declaration: the function's name, return type, and parameters (if


any)
● Definition: the body of the function (code to be executed)
53 Programming in C++

void myFunction() { // declaration


// the body of the function (definition)
}
You will often see C++ programs that have function declaration
above main(), and function definition below main(). This will make the code
better organized and easier to read:

Example:

// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}

C++ Functions Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as


variables inside the function.
54 Programming in C++

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

void functionName(parameter1, parameter2, parameter3) {


// code to be executed
}

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;

4. void myFunction(string fname) {


5. cout << fname << " Refsnes\n";
6. }

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++

This example returns the sum of a function with two parameters:

1. #include<iostream>
2. using namespace std;

3. int myFunction(int x, int y) {


4. return x + y;
5. }

6. int main() {
7. cout << myFunction(5, 3);
8. return0;
9. }
Output:
8

Pass By Reference

In the examples above, we used normal variables when we passed


parameters to a function. You can also pass a reference to the function. This
can be useful when you need to change the value of the arguments:

Example:

1. #include<iostream>
2. using namespace std;

3. void swapNums(int &x, int &y) {


57 Programming in C++

4. int z = x;
5. x = y;
6. y = z;
7. }

8. int main() {
9. int firstNum = 10;
10. int secondNum = 20;

11. cout << "Before swap: " << "\n";


12. cout << firstNum << secondNum << "\n";

13. swapNums(firstNum, secondNum);

14. cout << "After swap: " << "\n";


15. cout << firstNum << secondNum << "\n";

16. return 0;
17. }
Output:
Before swap:
1020

After swap:
2010
58 Programming in C++

C++ Function Overloading

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;

3. int plusFuncInt(int x, int y) {


4. return x + y;
5. }

6. double plusFuncDouble(double x, double y) {


7. return x + y;
8. }

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.

In the example below, we overload the plusFunc function to work for


both int and double:

1. #include<iostream>
2. using namespace std;

3. int plusFunc(int x, int y) {


4. return x + y;
5. }

6. double plusFunc(double x, double y) {


7. return x + y;
8. }

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.

In C++ std::array is a container that encapsulates fixed-size arrays. In


C++, array index starts from 0. We can store only fixed set of elements in
C++ array.

Advantages of C++ Array

o Code Optimization (less code)

o Random Access

o Easy to traverse data


61 Programming in C++

o Easy to manipulate data

o Easy to sort data etc.

Disadvantages of C++ Array

o Fixed size

C++ Array Types

There are 2 types of arrays in C++ programming:

1. Single Dimensional Array

2. Multidimensional Array

C++ Single Dimensional Array

Let's see a simple example of C++ 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

C++ Multidimensional Arrays

The multidimensional array is also known as rectangular arrays in C++. It


can be two dimensional or three dimensional. The data is stored in tabular
form (row ∗ column) which is also known as matrix.

C++ Multidimensional Array Example

Let's see a simple example of multidimensional array in C++ which declares,


initializes and traverse two dimensional arrays.

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

1) Pointer reduces the code and improves the performance, it is used to


retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's


memory.

Usage of pointer

There are many usages of pointers in C++ language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and


calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It


reduces the code and improves performance.
65 Programming in C++

Symbols used in pointer

Symbol Name Description


& Address operator Determine the address of a
(ampersand variable.
sign)
∗ (asterisk Indirection operator Access the value of an address.
sign)

Declaring a pointer

The pointer in C++ language can be declared using ∗ (asterisk symbol).

int ∗ a; //pointer to int

char ∗ c; //pointer to char

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++

10. cout<<"Value of p variable is:"<<*p<<endl;


11. return 0;
12. }

Output:

Address of number variable is:0x7ffccc8724c4


Address of p variable is:0x7ffccc8724c4
Value of p variable is:30

Pointer Program to swap 2 numbers without using 3rd


variable

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:

Before swap: ∗p1=20 ∗p2=10


After swap: ∗p1=10 ∗p2=20
67 Programming in C++

You might also like