0% found this document useful (0 votes)
85 views56 pages

C Handout

C++ is a versatile programming language that supports multiple programming paradigms, including object-oriented programming. It provides features such as high performance, control over system resources, and a strong foundation for understanding computer architecture. The document also covers key concepts like identifiers, keywords, variables, constants, data types, and the structure of a C++ program.

Uploaded by

spelumi998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views56 pages

C Handout

C++ is a versatile programming language that supports multiple programming paradigms, including object-oriented programming. It provides features such as high performance, control over system resources, and a strong foundation for understanding computer architecture. The document also covers key concepts like identifiers, keywords, variables, constants, data types, and the structure of a C++ program.

Uploaded by

spelumi998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 56

C++ is a powerful general-purpose programming language.

It can be used to develop operating systems,


browsers, games, and so on. C++ supports different ways of programming like procedural, object-
oriented, functional, and so on. C++ is a cross-platform language that gives programmers a high level of
control over system resources and memory.

Object-oriented programming(OOP) in C++

C++ offers the essentials necessary to implement object-oriented programming. It has classes and
objects, access specifiers, and the OOP concepts of inheritance, encapsulation, abstraction, and
polymorphism.

Feautures of C++
1. Multi-paradigm Language - C++ supports at least seven different styles of programming.
Developers can choose any of the styles.
2. General Purpose Language - You can use C++ to develop games, desktop apps, operating
systems, and so on.
3. Speed - Like C programming, the performance of optimized C++ code is exceptional.
4. Object-oriented - C++ allows you to divide complex problems into smaller sets by using objects.
5.
Importance of Learning C++
1. C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of
control in terms of memory management, better performance and finally a robust software
development.
2. C++ is used to develop games, desktop apps, operating systems, browsers, and so on because of
its performance.
3. After learning C++, it will be much easier to learn other programming languages like Java,
Python, etc.
4. C++ helps you to understand the internal architecture of a computer, how computer stores and
retrieves information.

Identifiers
Identifiers are the unique names given to variables, classes, functions, or other entities by the
programmer. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or
more letters, underscores, and digits (0 to 9).

C ++ does not allow punctuation characters such as @, $, and % within identifiers.

C++ is a case-sensitive programming language. Thus, Manpower and manpower


are two different identifiers in C++. Here are some examples of acceptable
identifiers:
moh, zara, abc, move_name, a_123,myname50 _temp, j, a23b9, retVal etc
Keywords
Keywords are predefined words that have special meanings to the compiler. Keywords are reserved
words and cannot be used for anything other than their designated purposes. In C++, a reserved word is
a word that cannot be used as an identifier, such as the name of a variable, function, label or any other
identifier names. it is "reserved. The following list shows some reserved words in C++.

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete,
do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto,
if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template,
this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void,
volatile, wchar_t, while

C++ Variables and Constants or Literal

C++ Variables
In programming, a variable is a container (storage area) to hold data. To indicate the storage area, each
variable should be given a unique name (identifier). For example,
int Age =14;
In the above, Age is a variable of the int data type, and we have assigned an integer value 14 to it. The
value of a variable can be changed, hence the name variable as described below.
int age = 14; // age is 14
age = 17; // age is 17

Rules for naming a variable


1. A variable name can only have alphabets, numbers, and the underscore _.
2. A variable name cannot begin with a number.
3. It is a preferred practice to begin variable names with a lowercase character. For example, name
is preferable to Name.
4. A variable name cannot be a keyword. For example, int is a keyword that is used to denote
integers.
5. A variable name can start with an underscore. However, it's not considered a good practice.

Note: We should try to give meaningful names to variables. For example, first_name is better than fn

C++ Constsant or Literal


Literals or Constant are data used for representing fixed values. They can be used directly in the code.
For example: 1, 2.5, 'c' etc. Here, 1, 2.5 and 'c' are literals or constant and this is beacuase you cannot
assign different values to these terms.
Different types of constant or literals in C++ programming
1. Integers
An integer is a numeric literal(associated with numbers) without any fractional or exponential part e.g 0,
1, -9,22
2. Floating-point
A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For
example: 1.0,2.1,-5.1,0.000342
3. Characters
A character literal is created by enclosing a single character inside single quotation marks. For example:
'a', 'm', 'F', '2', '}' etc.
4. Escape Sequences
Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C++
programming. For example, newline (enter)-\ln, tab-\b, question mark-\?, double qoute \", etc
5. String Literals
A string literal is a sequence of characters enclosed in double-quote marks. For example: "good", ëarth is
round" etc

Boolean Literals

There are two Boolean literals and they are part of standard C++ keywords −
A value of true representing true.
A value of false representing false.

C++ Constants

In C++, we can create variables whose value cannot be changed. For that, we use the const keyword.
Here's an example:
const int LIGHT_SPEED = 299792458;
LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant.

In the above, we have used the keyword const to declare a constant named LIGHT_SPEED. If we try to
change the value of LIGHT_SPEED, we will get an error.

Defining Constants

There are two simple ways in C++ to define constants −

i. Using #define preprocessor. It is used as show below:


#define identifier value

e.g

#define LENGTH 10

2. Using const keyword. it is used as shown below:


const LENGTH 10

C++ Data Types

In C++, data types are declarations for variables. This determines the type and size of data associated
with variables. For example,

int age = 13;

The statement above states that age is a variable of type int. Meaning, the variable can only store
integer numbers.

C++ Fundamental Data Types

The table below shows the fundamental data types, their meaning, and their sizes (in bytes):

Data Type Meaning Size (in Bytes)


int Integer 2 or 4
float Floating-point 4
double Double Floating-point 8
char Character 1
bool Boolean 1
void Empty/Null 0

Now, let us discuss these fundamental data types in more detail.

1. int
The int keyword is used to indicate integers. Its size is usually 4 bytes. Meaning, it can store values
from -2147483648 to 2147483647.

For example: int salary = 85000;

2. float and double


float and double are used to store floating-point numbers (decimals and exponentials). The size of
float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the precision of float.
For example: float area = 64.74;
double volume = 134.64534;

As mentioned above, these two data types are also used for exponentials. For example,

double distance = 45E12 // 45E12 is equal to 45*10^12

3. char

Keyword char is used for characters. Its size is 1 byte. Characters in C++ are enclosed inside single
quotes ' '.

For example: char test = 'h';

4. bool

The bool data type has one of two possible values: true or false. Booleans are used in conditional
statements and loops (which we will learn in later ).

For example: bool cond = false;

6. void

The void keyword indicates an absence of data. It means "nothing" or "no value".

We will use void when we learn about functions and pointers.

Note: We cannot declare variables of the void type.

Type Modifiers

We can further modify some of the fundamental data types by using type modifiers. There are 4 type
modifiers in C++. They are: signed, unsigned, short, long

We can modify the following data types with the above modifiers: int, double, char

C++ Modified Data Types List

Data Type Size (in Bytes) Meaning


signed int 4 used for integers (equivalent to int)
unsigned int 4 can only store positive integers
short 2 used for small integers (range -32768 to 32767)
unsigned short 2 used for small positive integers (range 0 to 65,535)
long at least 4 used for large integers (equivalent to long int)
unsigned long 4 used for large positive integers or 0
(equivalent to unsigned long int)
long long 8 used for very large integers (equivalent to
long long int).
unsigned long long 8 used for very large positive integers or 0
(equivalent to unsigned long long int)
long double 12 used for large floating-point numbers
signed char 1 used for characters (guaranteed range -127
to 127)
unsigned char 1 used for characters (range 0 to 255)

Derived Data Types

Data types that are derived from fundamental data types are derived types. For example: arrays,
pointers, function types, structures, etc.

Structure of a C++ program

A C++ program is structured in a specific and particular manner. In C++, a program is divided into the
following three sections:

Standard Libraries Section

Main Function Section

Function Body Section

1. Preprocessor Directives

A preprocessor reads your program before it is compiled and only executes those lines beginning with a
#symbol. The #include directive causes the preprocessor to include the contents of another file, known a
sheader file, in the program. The preprocessor inserts the entire contents of the header file into the
program at the point it encounters the #include directive.

for example, #include<iostream> will include the contents of the <iostream> file in the program, which
allows a C++ program to display output on the screen and read input from the keyboard.

2. Namespace

C++ uses namespace to organize the names of program entities. The statement using namespace std
declares that the program will be accessing entities whose names are

part of the namespace called std. The reason the program needs access to the std namespace is
because every name created by the iostream file is part of that namespace. In order for a program to
use the entities in iostream, it must have access to std namespace.

3. main function

Every C++ program must have exactly one main function. It is the starting point of the program
execution. When a C++ program executes, the main function is called by the operating system.

4. Console I/O

cout

* standard output stream


* console
cin

* standard input stream


* keyboard

5. Statements

A statement is a complete instruction that causes the computer to perform some action.
The body of any function is a sequence of statements. Statements can be a combination of keywords,
operators, and program-defined symbols. They always end with a semicolon (;)

6. Comments

Single-line Comments: two forward slash //

Multi-line Comments: start with /* and end with */

Probably the best way to start learning a programming language is by writing a program. Therefore, here
is our

first program:

// my first program in C++

#include <iostream>

using namespace std;

int main ()

cout << "Hello World!";


return 0;

The above program is one of the simplest programs that can be written in C++, but it already contains
the fundamental components that every C++ program has. We are going to look line by line at the code
we have just written:

Line 1: // my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief description of
what our program is.

Line 2: #include <iostream>

Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines
with expressions but indications for the compiler's preprocessor. In this case the directive #include
<iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream)
includes the declarations of the basic standard input-output library in C++, and it is included because its
functionality is going to be used later in the program.

Line 3:using namespace std;

All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this expression that
we will be using these entities. This line is very frequent in C++ programs that use the standard library.

Line 4: int main ()

This line corresponds to the beginning of the definition of the main function. The main function is the
point by where all C++ programs start their execution, independently of its location within the source
code. It does not matter whether there are other functions with other names defined before or after it -
the instructions contained within this function's definition will always be the first ones to be executed in
any C++ program. For that same reason, it is essential that all C++ programs have a main function. The
word main is followed in the code by a pair of parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are these
parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within
them. Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.

Line 5: cout << "Hello World!";

This line is a C++ statement. A statement is a simple or compound expression that can actually produce
some effect. In fact, this statement performs the only action that generates a visible effect in our first
program.

cout represents the standard output stream in C++, and the meaning of the entire statement is to insert
a sequence of characters (in this case the Hello World sequence of characters) into the standard output
stream (which usually is the screen). cout is declared in the iostream standard file within the std
namespace, so that's why we needed to include that specific file and to declare that we were going to
use this specific namespace earlier in our code.

Notice that the statement ends with a semicolon character (;). This character is used to mark the end of
the statement and in fact it must be included at the end of all expression statements in all C++ programs
(one of the most common syntax errors is indeed to forget to include some semicolon after a
statement).

Line 6: return 0;

The return statement causes the main function to finish. return may be followed by a return code (in our
example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the most
usual way to end a C++ console program.

You may have noticed that not all the lines of this program perform actions when the code is executed.
There were lines containing only comments (those beginning by //). There were lines with directives for
the compiler's preprocessor (those beginning by #). Then there were lines that began the declaration of
a function (in this case,the main function) and, finally lines with statements (like the insertion into cout),
which were all included within the block delimited by the braces ({}) of the main function.

The program has been structured in different lines in order to be more readable, but in C++, we do not
have strict rules on how to separate instructions in different lines. For example, instead of

int main ()
{
cout << " Hello World!";
return 0;
}

We could have written:

int main () { cout << "Hello World!"; return 0; }

Operators
Assignment (=)
The assignment operator assigns a value to a variable.
a = 5;
Thestatement above assigns the integer value 5 to the variable a.
a = b;
This statement assigns to variable a, the value contained in variable b.

A property that C++ has over other programming languages is that the assignment operation
can be used as the value (or part of value) for another assignment operation.

For example:
a = 2 + (b = 5);
is equivalent to:
b = 5;
a = 2 + b;
that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the
previous assignment of b (i.e. 5), leaving a with a final value of 7.

The following expression is also valid in C++:


a = b = c = 5;
It assigns 5 to the all the three variables: a, b and c.

Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the C++ language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with their
respective mathematical operators. The only one that you might not be so used to see is
modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the
remainder of a division of two values.

For example, if we write:


a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.
Compound assignment operator (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators:

Expression Equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);

and the same for all other operators. For example:

// compound assignment operators


#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}

Output
5

Increase and decrease (++, --)


Shortening even more some expressions, the increase operator (++) and the decrease operator
(--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -
=1, respectively. Thus:
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of them increase by one the value of c and same
is applicable to -- operator which decreases by one the value of c.
A characteristic of this operator is that it can be used both as a prefix and as a suffix. That
means that it can be written either before the variable identifier (++a) or after it (a++). Although
in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions
in which the result of the increase or decrease operation is evaluated as a value in an outer
expression they may have an important difference in their meaning: In the case that the
increase operator is used as a prefix (++a) the value is increased before the result of the
expression is evaluated and therefore the increased value is considered in the outer expression;
in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated
and therefore the value stored before the increase operation is evaluated in the outer
expression. Notice the difference

Example 1
B=3;
A=++B;
// A contains 4, B contains 4

Example 2
B=3;
A=B++;
// A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is
copied to A and then B is increased.

Relational and equality operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the relational and
equality operators. The result of a relational operation is a Boolean value that can only be true
or false, according to its Boolean result. We may want to compare two expressions, for
example, to know if they are equal or if one is greater than the other is. Here is a list of the
relational and equality operators that can be used in C++:

== Equal to

!= Not equal to

> Greater than

< Less than


>= Greater than or equal to

<= Less than or equal to

Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs),
the first one is an assignment operator and the other one (==) is the equality operator.

Logical operators ( !, &&, || )


The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one
operand, located at its right, and the only thing that it does is to inverse the value of it,
producing false if its operand is true and true if its operand is false. Basically, it returns the
opposite Boolean value of evaluating its operand.

For example:

!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.


!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.

The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds with Boolean logical operation AND. This
operation results true if both its two operands are true, and false otherwise.

The operator || corresponds with Boolean logical operation OR. This operation results true if
either one of its two operands is true, thus being false only when both operands are false
themselves.

Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and
a different one if the expression is evaluated as false. Its format is:

condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return result2.

Example
// conditional operator
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}

Output : 7

In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus
the first valuespecified after the question mark was discarded in favor of the second value (the
one after the colon) which was b, with a value of 7.

Comma operator ( , )

The comma operator (,) is used to separate two or more expressions that are included where
only one expression is expected. When the set of expressions has to be evaluated for a value,
only the rightmost expression is considered.

For example, the following code: a = (b=3, b+2);

Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a
would contain the value 5 while variable b would contain value 3.

C++ Expression

C++ expression consists of operators, constants, and variables which are arranged according to
the rules of the language. It can also contain function calls which return values. An expression
can consist of one or more operands, zero or more operators to compute a value. Every
expression produces some value which is assigned to the variable with the help of an
assignment operator.
Basic Input/Output
The standard C++ library includes the header file iostream, where the standard input and
output stream objects are declared.

Standard Output (cout)

By default, the standard output of a program is the screen, and the C++ stream object defined to access
it is cout. cout is used in conjunction with the insertion operator, which is written as << (two "less
than" signs).

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

The << operator inserts the data that follows it into the stream preceding it. In the examples above it
inserted the constant string Output sentence, the numerical constant 120 and variable x into the
standard output stream cout. Notice that the sentence in the first instruction is enclosed between
double quotes (") because it is a string of characters. Whenever we want to use strings of characters we
must enclose them between double quotes (") so that they can be clearly distinguished from variable
names. For example, these two sentences have very different results:

cout << "Hello"; // prints Hello


cout << Hello; // prints the content of Hello variable

The insertion operator (<<) may be used more than once in a single statement:

cout << "Hello, " << "I am " << "a C++ statement";

This last statement would print the message Hello, I am a C++ statement on the screen. The utility of
repeating the insertion operator (<<) is demonstrated when we want to print out a combination of
variables and constants or more than one variable:

cout << "Hello, I am " << age << " years old and my phone number is " << phonenumber;

If we assume the age variable to contain the value 24 and the phonenumber variable to contain 90064
the output of the previous statement would be:

Hello, I am 24 years old and my phone number is 90064

It is important to notice that cout does not add a line break after its output unless we explicitly indicate
it,
therefore, the following statements:

cout << "This is a sentence.";


cout << "This is another sentence.";

will be shown on the screen one following the other without any line break between them:

This is a sentence.This is another sentence.

even though we had written them in two different insertions into cout. In order to perform a line break
on the output we must explicitly insert a new-line character into cout. In C++ a new-line character can
be specified as \n (backslash, n):

cout << "First sentence.\n ";


cout << "Second sentence.\nThird sentence.";

This produces the following output:

First sentence.
Second sentence.
Third sentence.

Additionally, to add a new-line, you may also use the endl manipulator. For example:

cout << "First sentence." << endl;


cout << "Second sentence." << endl;

would print out:

First sentence.
Second sentence.

The endl manipulator produces a newline character, exactly as the insertion of '\n' does, in order to
specify a new line without any difference in its behavior.

Standard Input (cin).


The standard input device is usually the keyboard. Handling the standard input in C++ is done by
applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed
by the variable that will store the data that is going to be extracted from the stream. For example:

int age;
cin >> age;
The first statement declares a variable of type int called age, and the second one waits for an input from
cin (the keyboard) in order to store it in this integer variable. cin can only process the input from the
keyboard once the RETURN key has been pressed.

You must always consider the type of the variable that you are using as a container with cin extractions.
If you request an integer you will get an integer, if you request a character you will get a character and if
you request a string of characters you will get a string of characters.

// i/o example
#include <iostream>
using namespace std;
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}

You can also use cin to request more than one datum input from the user:

cin >> a >> b;

is equivalent to:

cin >> a;
cin >> b;

In both cases the user must give two data, one for variable a and another one for variable b that may be
separated by any valid blank separator: a space, a tab character or a newline.

cin and strings

We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type
variables:
cin >> mystring;
However, as it has been said, cin extraction stops reading as soon as if finds any blank space character,
so in this case we will be able to get just one word for each extraction. This behavior may or may not be
what we want; for example if we want to get a sentence from the user, this extraction operation would
not be useful. In order to get entire lines, we can use the function getline, which is the more
recommendable way to get user input with cin as shown below

// cin with strings


#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}

Control Structures

A program is usually not limited to a linear sequence of instructions. During its process it may repeat
code or take decisions. For that purpose, C++ provides control structures that serve to specify what has
to be done by our program, when and under which circumstances.

With the introduction of control structures we are going to have to introduce a new concept: the
compound-statement or block.

A block is a group of statements which are separated by semicolons (;) like all C++ statements, but
grouped together in a block enclosed in braces: { }:

{ statement1; statement2; statement3; }

Most of the control structures require a generic statement as part of its syntax. A statement can be
either a simple statement (a simple instruction ending with a semicolon) or a compound statement
(several instructions grouped in a block), like the one just described. In the case that we want the
statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we
want the
statement to be a compound statement it must be enclosed between braces ({}), forming a block.
Conditional structure: if and else

The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
if (condition) statement

Where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after this
conditional structure.

For example, the following code fragment prints x is 100 only if the value stored in the x variable is
indeed 100:
if (x == 100)
cout << "x is 100";

If we want more than a single statement to be executed in case that the condition is true we can specify
a block using braces { }:

if (x == 100)
{
cout << "x is ";
cout << x;
}

We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword
else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100"

prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x
is
not 100. The if + else structures can be concatenated with the intention of verifying a range of values.
The following example shows its use telling if the value currently stored in x is positive, negative or none
of them (i.e. zero):
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

Remember that in case that we want more than a single statement to be executed, we must group them
in a block by enclosing them in braces { }.

Iteration structures (loops)

Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop

Its format is:


while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.

For example, we are going to make a program to countdown using a while-loop:

/ custom countdown using while


#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return 0;
}

output :

Enter the starting number > 8


8, 7, 6, 5, 4, 3, 2, 1, FIRE

The do-while loop

Its format is:


do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never fulfilled. For example, the following example program echoes any
number you enter until you enter 0.

// number echoer
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}

Output:

Enter number (0 to end): 12345


You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end):0
You entered :0

The for loop

Its format is:


for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in
addition, the for loop provides specific locations to contain an initialization statement and an increase
statement. So this loop is specially designed to perform a repetitive action with a counter which is
initialized and increased on each iteration.

It works in the following way:


1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed
only once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped
(not executed).
3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:

// countdown using a for loop


#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Jump statements.

The break statement


Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an
infinite loop, or to force it to end before its natural end. For example, we are going to stop the count
down before its natural end (maybe because of an engine check failure?):

// break loop example


#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}

Output:

10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

The continue statement

The continue statement causes the program to skip the rest of the loop in the current iteration as if the
end of the statement block had been reached, causing it to jump to the start of the following iteration.
For example, we are going to skip the number 5 in our countdown:

// continue loop example


#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

Output:
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

The goto statement

goto allows to make an absolute jump to another point in the program. You should use this feature with
caution since its execution causes an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto statement.
A label is made of a valid identifier followed by a colon (:).

Generally speaking, this instruction has no concrete use in structured or object oriented programming
aside from those that low-level programming fans may find for it.

For example, here is our countdown loop using goto:

#include <iostream>
using namespace std;
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
return 0;
}

Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The selective structure: switch statement.

The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant
values for an expression. Something similar to concatenation of several if and else if instructions.

Its form is the following:


switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}

It works in the following way:


i. switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group
of statements 1 until it finds the break statement. When it finds this break statement the
program jumps to the end of the switch selective structure.
ii. If expression was not equal to constant1 it will be checked against constant2. If it is equal to this,
it will execute group of statements 2 until a break keyword is found, and then will jump to the
end of the switch selective structure.
iii. Finally, if the value of expression did not match any of the previously specified constants (you
can include as many case labels as values you want to check), the program will execute the
statements included after the default: label, if it exists (since it is optional).

Example 1:
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}

Example 2:

switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}

Notice that switch can only be used to compare an expression against constants. Therefore we cannot
put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they
are not valid C++ constants.
Functions

A function is a group of statements that is executed when it is called from some point of the program.
The
following is its format:
type name ( parameter1, parameter2, ...) { statements }
where:
• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type specifier followed by
an
identifier, like any regular variable declaration (for example: int x) and which acts within the
function as a regular local variable. They allow to pass arguments to the function when it is
called. The differentparameters are separated by commas.
• statements is the function's body. It is a block of statements surrounded by braces { }.

// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}

Output:The results is 8

Inline functions (C++)


C++ provides inline functions to reduce the function call overhead. An inline function is a
function that is expanded in line when it is called. When the inline function is called whole code
of the inline function gets inserted or substituted at the point of the inline function call. This
substitution is performed by the C++ compiler at compile time.

Example of using inline function

#include <iostream>
using namespace std;

inline void displayNum(int num) {


cout << num << endl;
}
int main() {
// first function call
displayNum(5);

// second function call


displayNum(8);

// third function call


displayNum(666);

return 0;
}
Output:
5
8
666

How the program work during compilation

#include <iostream>
using namespace std;

inline void displayNum(int num) {


cout << num << endl;
}
int main() {
cout << 5 << endl;
cout << 8 << endl;
cout << 666 << endl;
}

Inline functions Advantages:


i. Function call overhead doesn’t occur.
ii. It also saves the overhead of push/pop variables on the stack when a function is called.
iii. It also saves the overhead of a return call from a function.
iv. An inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function called preamble and return.

Disadvantages of Inline Function in C++


i. Inline functions must be short in length as lengthier inline functions can cause a
reduction of the cache hit rate of the instructions. This can have adverse effects on the
efficiency of the program.
ii. Excess use of inline functions in the code may lead to the enlargement of the size of the
binary executable code.
iii. In the case of large functions, compilation overhead can take place and reduce the
efficiency of the code.
iv. Implementation of these functions in the header files can make them heavy.

C++ Function Overloading

In C++, two functions can have the same name if the number and/or type of arguments passed
is different. These functions having the same name but different arguments are known as
overloaded functions.

Consider the function declaratios below:

// same name different arguments


int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }

All 4 functions declared above are overloaded functions.

Notice that the return types of all these 4 functions are not the same. Overloaded functions
may or may not have different return types but they must have different number or type of
arguments.

For example,

// Error code
int test(int a) { }
double test(int b){ }

In the above, both functions have the same name, the same type, and the same number of
arguments. Hence, the compiler will throw an error.

// Program to compute absolute value


// Works for both int and float
#include <iostream>
using namespace std;

// function with float type parameter


float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

// function with int type parameter


int absolute(int var) {
if (var < 0)
var = -var;
return var;
}

int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;

// call function with float type parameter


cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}

Output:
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5

Recursive Function

A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
The recursion continues until some condition is met. To prevent infinite recursion, if...else
statement (or similar approach) can be used where one branch makes the recursive call and the
other doesn't.

Example: Factorial of a Number Using Recursion

// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}

Output:
Enter a non-negative number: 4
Factorial of 4 = 24

As we can see, the factorial() function is calling itself. However, during each call, we have
decreased the value of n by 1. When n is less than 1, the factorial() function ultimately returns
the output.

Advantages of C++ Recursion


i. It makes our code shorter and cleaner.
ii. Recursion is required in problems concerning data structures and advanced algorithms,
such as Graph and Tree Traversal.

Disadvantages of C++ Recursion


i. It takes a lot of stack space compared to an iterative program.
ii. It uses more processor time.
iii. It can be more difficult to debug compared to an equivalent iterative program.

Default and Passing Argument in C++

Arguments in C++ are the values of parameters passed to a function while calling the function.

Default Argument

Default Values for Parameters: When you define a function, you can specify a default value for
each of the parameters. This value will be used if the corresponding argument is left blank
when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the
function definition. If a value for that parameter is not passed when the function is called, the
default given value is used, but if a value is specified, this default value is ignored and the
passed value is used instead.

Consider the following example −

#include <iostream>
using namespace std;

int sum(int a, int b = 20) {


int result;
result = a + b;

return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120

Passing Parameter to Function in C++


C++ supports three types of argument data types – pass by value, pass by reference, and pass
by pointer.

Passing argument by value


The passing argument by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.

By default, C++ uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function.

Consider the function swap() definition as follows.

#include <iostream>
using namespace std;

// function definition to swap the values.


void swap(int x, int y) {
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put x into y */

return;
}

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.


swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;
}

result −
When the above code is put together in a file, compiled and executed, it produces the following

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

Which shows that there is no change in the values though they had been changed inside the
function.

Passing argument by reference

The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument.

To pass the value by reference, argument reference is passed to the functions just like any
other value. So accordingly you need to declare the function parameters as reference types as
in the following function swap(), which exchanges the values of the two integer variables
pointed to by its arguments.

#include <iostream>
using namespace std;

// function definition to swap the values.


void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}

result −
When the above code is put together in a file, compiled and executed, it produces the following

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Passing argument by reference

The call by pointer method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument.

To pass the value by pointer, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed to
by its arguments.

#include <iostream>
using namespace std;

// function definition to swap the values.


void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */

return;
}

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values.


* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}
Library Functions In C++

Library functions which are also called as “built-in” functions are the functions that are already
available and implemented in C++. We can directly call these functions in our program as per
our requirements. Library functions in C++ are declared and defined in special files called
“Header Files” which we can reference in our C++ programs using the “include” directive.

For Example, to include all the built-in functions related to math, we should include <cmath>
header as follows:

#include <cmath>

Some of the Header files are briefed along with their description below.

Headers Description
iostream This header contains the prototype for standard input and output functions used
in C++ like cin, cout, etc.
cmath This is the header containing various math library functions.
cstdlib The header cstdlib contains various functions related to conversion between text
and numbers, memory allocation, random numbers, and other utility functions.
ctime ctime contains function prototypes related to date and time manipulations in C+
+.
cctype This header includes function prototypes that test the type of characters (digit,
punctuation, etc.). It also has prototypes that are used to convert from
uppercase to lowercase and another way around.
cstring cstring header includes function prototypes for C-style string-processing
functions.
cstdio This header contains function prototypes for the C-style standard input/output
library functions which we included initially in stdio.h
fstream Function prototypes for functions that perform input/output from/to files on
disk
cfloat This header file contains the size limits for floating-point numbers on the system.
string The header string defines the class string of the C++ Standard Library.

We have already used some of these headers in the note such <iostream>, <string>, <ctime>
headers that we have used from time to time.

<cmath> Header
This header contains various function prototypes related to mathematical functions. Some of
the prototypes that are used extensively are listed here.

Function Description
sqrt(x) Accepts any non-negative numeric parameter x and returns the square
root of this number x
pow(base,exponent) Raises the ‘base’ value to the power specified by the exponent. Returns
base^exponent.
exp(x) Takes any number (positive, negative or zero) as a parameter and returns
exponential (Euler’s number) e raised to the given parameter
fabs(x) Returns absolute value of an argument.
log(x) Returns the natural logarithm (to the base e) of value x
log 10(x) Return the logarithm (to the base 10) of value x
sin(x) Returns sine of the angle x (in radians)
cos(x) Returns cosine of angle x (in radians)
tan(x) Returns tangent of angle x (in radians)
asin(x) Returns inverse sine (in radians) of number x
acos(x) Returns inverse cosine (in radians) of number x
atan(x) Returns inverse tangent (in radians) of number x

<cctype> Header
This header contains function prototypes that are mainly used for converting the character to
upper/lower case or to check if a character is a digit etc.

Function prototypes included in <cctype> header are listed as below:

Function Description
toupper(ch) Takes in character ‘ch’ as an argument and returns the uppercase
equivalent of ch if it's present otherwise returns ch.
tolower(ch) Takes in character ‘ch’ as an argument and returns the lowercase
equivalent of ch if it's present otherwise returns ch.
isalpha(ch) Returns non-zero if ch is alphabet otherwise 0.
isalnum(ch) Returns non-zero if ch is alphanumeric (alphabet or number) otherwise 0.
isupper(ch) Returns non-zero value if ch is uppercase otherwise 0.
isdigit(ch) Returns non-zero value if ch is a number otherwise 0.
islower() Returns non-zero value if ch is lowercase otherwise 0.
<stdlib> Header
We also have another header <stdlib> that includes various useful library functions that are
used extensively in C++ programming.

We have listed some of the popular functions in <stdlib> below:

Function Description
abs(x) Returns absolute value of an integral argument x
atof(const char* str) Converts string to double; returns double
atoi(const char* str) Converts string to int; returns an int
atol(const char* str) Converts string to long int; returns a long int
atoll(const char* str) Converts string to long long int; returns a long long int
strtod Converts string to double
strtol Converts string to long int
strtoul Converts string to unsigned long integer
strtof Converts string to float
strtold Converts string to long double
strtoull Converts string to unsigned long long integer
strtoll Converts string to long long integer

C++ Array
In C++, an array is a variable that can store multiple values of the same type. For example,
Suppose a class has 27 students, and we need to store the grades of all of them. Instead of
creating 27 separate variables, we can simply create an array:
double grade[27];
Here, grade is an array that can hold a maximum of 27 elements of double type.
In C++, the size and type of arrays cannot be changed after its declaration.

C++ Array Declaration


dataType arrayName[arraySize];

For example,
int x[6];
Here,
int - type of element to be stored
x - name of the array
6 - size of the array

Access Elements in C++ Array

In C++, each element in an array is associated with a number. The number is known as an array
index. We can access elements of an array by using those indices.
// syntax to access array elements
array[index];
C++ Array Declaration
// declare and initialize and array
int x[6] = {19, 10, 8, 17, 9, 15};
// declare and initialize an array
int x[] = {19, 10, 8, 17, 9, 15};
Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.
C++ Array With Empty Members
In C++, if an array has a size n, we can store upto n number of elements in the array. However,
what will happen if we store less than n number of elements.
For example,
// store only 3 elements in the array
int x[6] = {19, 10, 8};
Here, the array x has a size of 6. However, we have initialized it with only 3 elements.
In such cases, the compiler assigns random values to the remaining places. Oftentimes, this
random value is simply 0.
C++ Array with empty members
Empty array members are automatically assigned the value 0
How to insert and print array elements?
int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9


mark[3] = 9;

// take input from the user


// store the value at third position
cin >> mark[2];

// take input from the user


// insert at ith position
cin >> mark[i-1];

// print first element of the array


cout << mark[0];

// print ith element of the array


cout >> mark[i-1];
Example 1: Displaying Array Elements
#include <iostream>
using namespace std;

int main() {

int numbers[5] = {7, 5, 6, 12, 35};

cout << "\nThe numbers are: ";

// Printing array elements


// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}

return 0;
}
Run Code
Output

The numbers are: 7 5 6 12 35

Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have printed
numbers[i].

Example 2: Take Inputs from User and Store Them in an Array


#include <iostream>
using namespace std;

int main() {

int numbers[5];

cout << "Enter 5 numbers: " << endl;

// store input from user to array


for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements


for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}

return 0;
}
Run Code
Output

Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15
Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an
input from the user and stored it in numbers[i].

Two Dimensional Array example


// C++ Program to display all elements
// of an initialised two dimensional array

#include <iostream>
using namespace std;

int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};

// use of nested for loop


// access rows of the array
for (int i = 0; i < 3; ++i) {

// access columns of the array


for (int j = 0; j < 2; ++j) {
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}

Taking Input for Two Dimensional Array


#include <iostream>
using namespace std;

int main() {
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

// Printing array elements


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
}
}

return 0;
}

Function and Array


Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students

#include <iostream>
using namespace std;

// declare function to display marks


// take a 1d array as parameter
void display(int m[5]) {
cout << "Displaying marks: " << endl;

// display array elements


for (int i = 0; i < 5; ++i) {
cout << "Student " << i + 1 << ": " << m[i] << endl;
}
}

int main() {

// declare and initialize an array


int marks[5] = {88, 76, 90, 61, 69};
// call display function
// pass array as argument
display(marks);

return 0;
}

C++ Structures

Structure is a collection of variables of different data types under a single name. It is similar to a class in
that, both holds a collection of data of different data types.
For example: You want to store some information about a person: his/her name, citizenship number
and salary. You can easily create different variables name, citNo, salary to store these information
separately.
However, in the future, you would want to store information about multiple persons. Now, you'd need
to create different variables for each information per person: name1, citNo1, salary1, name2, citNo2,
salary2
You can easily visualize how big and messy the code would look. Also, since no relation between the
variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single name Person, and
use it for every person. Now, the code looks much cleaner, readable and efficient as well.
This collection of all related information under a single name Person is a structure.

How to declare a structure in C++ programming?

The struct keyword defines a structure type followed by an identifier (name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside curly
braces) of that structure. For example:

struct Person
{
char name[50];
int age;
float salary;
};

Here a structure person is defined which has three members: name, age and salary.
When a structure is created, no memory is allocated.
The structure definition is only the blueprint for the creating of variables. You can imagine it as a
datatype. When you define an integer as below:

int foo;

The int specifies that, variable foo can hold integer element only. Similarly, structure definition only
specifies that, what property a structure variable holds when it is defined.
Note: Remember to end the declaration with a semicolon (;)

How to define a structure variable?

Once you declare a structure person as above. You can define a structure variable as:
Person bill;
Here, a structure variable bill is defined which is of type structure Person.
When structure variable is defined, only then the required memory is allocated by the compiler.

Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory of int is 4
bytes and memory of char is 1 byte.
Hence, 58 bytes of memory is allocated for structure variable bill.

How to access members of a structure?

The members of structure variable is accessed using a dot (.) operator.


Suppose, you want to access age of structure variable bill and assign it 50 to it. You can perform this task
by using following code below:
bill.age = 50;

Example: C++ Structure

C++ Program to assign data to members of a structure variable and display it.

using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

int main()
{
Person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output
Enter Full name: Magdalena Dankova
Enter age: 27
Enter salary: 1024.4

Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4

A pointer variable can be created not only for native types like (int, float, double etc.) but they can also
be created for user defined types like structure.

Here is how you can create pointer for structures

#include <iostream>
using namespace std;
struct temp {
int i;
float f;
};

int main() {
temp *ptr;
return 0;
}:

#include <iostream>
using namespace std;

struct Distance {
int feet;
float inch;
};

int main() {
Distance *ptr, d;

ptr = &d;
cout << "Enter feet: ";
cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;

cout << "Displaying information." << endl;


cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
return 0;
}

Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches

C++ Class
A class is a blueprint for the object.
We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors,
doors, windows, etc. Based on these descriptions we build the house. House is the object.

Create a Class
A class is defined in C++ using keyword class followed by the name of the class.

The body of the class is defined inside the curly brackets and terminated by a semicolon at the end.

class className {
// some data
// some functions
};
For example,

class Room {
public:
double length;
double breadth;
double height;

double calculateArea(){
return length * breadth;
}

double calculateVolume(){
return length * breadth * height;
}

};
Here, we defined a class named Room.

The variables length, breadth, and height declared inside the class are known as data members. And, the
functions calculateArea() and calculateVolume() are known as member functions of a class.

C++ Objects
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated.

To use the data and access functions defined in the class, we need to create objects.

Syntax to Define Object in C++


className objectVariableName;

We can create objects of Room class (defined in the above example) as follows:

// sample function
void sampleFunction() {
// create objects
Room room1, room2;
}

int main(){
// create objects
Room room3, room4;
}

Here, two objects room1 and room2 of the Room class are created in sampleFunction(). Similarly, the
objects room3 and room4 are created in main().

As we can see, we can create objects of a class in any function of the program. We can also create
objects of a class within the class itself, or in other classes.

Also, we can create as many objects as we want from a single class.

C++ Access Data Members and Member Functions


We can access the data members and member functions of a class by using a . (dot) operator. For
example,

room2.calculateArea();
This will call the calculateArea() function inside the Room class for object room2.

Similarly, the data members can be accessed as:

room1.length = 5.5;
In this case, it initializes the length variable of room1 to 5.5.

Example 1: Object and Class in C++ Programming


// Program to illustrate the working of
// objects and class in C++ Programming

#include <iostream>
using namespace std;
// create a class
class Room {

public:
double length;
double breadth;
double height;

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// assign values to data members


room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}
Run Code
Output

Area of Room = 1309


Volume of Room = 25132.8
In this program, we have used the Room class and its object room1 to calculate the area and volume of a
room.
In main(), we assigned the values of length, breadth, and height with the code:

room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
We then called the functions calculateArea() and calculateVolume() to perform the necessary
calculations.

Note the use of the keyword public in the program. This means the members are public and can be
accessed anywhere from the program.

As per our needs, we can also create private members using the private keyword. The private members
of a class can only be accessed from within the class. For example,

class Test {

private:
int a;
void function1() { }

public:
int b;
void function2() { }
}
Here, a and function1() are private. Thus they cannot be accessed from outside the class.

On the other hand, b and function2() are accessible from everywhere in the program.

To learn more about public and private keywords, please visit our C++ Class Access Modifiers tutorial.

Example 2: Using public and private in C++ Class


// Program to illustrate the working of
// public and private in C++ Class

#include <iostream>
using namespace std;

class Room {

private:
double length;
double breadth;
double height;

public:

// function to initialize private variables


void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// pass the values of private variables as arguments


room1.initData(42.5, 30.8, 19.2);

cout << "Area of Room = " << room1.calculateArea() << endl;


cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}
Run Code
Output

Area of Room = 1309


Volume of Room = 25132.8
The above example is nearly identical to the first example, except that the class variables are now
private.
Since the variables are now private, we cannot access them directly from main(). Hence, using the
following code would be invalid:

// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
Instead, we use the public function initData() to initialize the private variables via the function
parameters double len, double brth, and double hgt.

Constructor

A constructor is a special type of member function that is called automatically when an object is created.

In C++, a constructor has the same name as that of the class and it does not have a return type. For
example,

class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor

has the same name as the class,


does not have a return type, and
is public
C++ Default Constructor
A constructor with no parameters is known as a default constructor. In the example above, Wall() is a
default constructor.

Example 1: C++ Default Constructor


// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

public:
// default constructor to initialize variable
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main() {
Wall wall1;
return 0;
}
Run Code
Output

Creating a Wall
Length = 5.5
Here, when the wall1 object is created, the Wall() constructor is called. This sets the length variable of
the object to 5.5.

Destructor
In C#, destructor (finalizer) is used to destroy objects of class when the scope of an object ends. It has
the same name as the class and starts with a tilde ~. For example,

class Test {
...
//destructor
~Test() {
...
}
}
Here, ~Test() is the destructor.

Example 1: Working of C# Destructor


using System;
namespace CsharpDestructor {
class Person {

public Person() {
Console.WriteLine("Constructor called.");
}

// destructor
~Person() {
Console.WriteLine("Destructor called.");
}

public static void Main(string [] args) {

//creates object of Person


Person p1 = new Person();
}
}
}
Output

Constructor called.
Destructor called.
In the above example, we have created a destructor ~Person inside the Person class.

You might also like