C Handout
C Handout
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).
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
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
Note: We should try to give meaningful names to variables. For example, first_name is better than fn
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
e.g
#define LENGTH 10
In C++, data types are declarations for variables. This determines the type and size of data associated
with variables. For example,
The statement above states that age is a variable of type int. Meaning, the variable can only store
integer numbers.
The table below shows the fundamental data types, their meaning, and their sizes (in bytes):
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.
As mentioned above, these two data types are also used for exponentials. For example,
3. char
Keyword char is used for characters. Its size is 1 byte. Characters in C++ are enclosed inside single
quotes ' '.
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 ).
6. void
The void keyword indicates an absence of data. It means "nothing" or "no value".
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
Data types that are derived from fundamental data types are derived types. For example: arrays,
pointers, function types, structures, etc.
A C++ program is structured in a specific and particular manner. In C++, a program is divided into the
following three sections:
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
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
Probably the best way to start learning a programming language is by writing a program. Therefore, here
is our
first program:
#include <iostream>
int main ()
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:
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.
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.
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.
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.
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;
}
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.
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.
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);
Output
5
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
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.
For example:
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:
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.
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.
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).
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:
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:
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:
will be shown on the screen one following the other without any line break between them:
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):
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For example:
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.
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:
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.
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
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: { }:
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:
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 { }.
Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.
and its functionality is simply to repeat statement while the condition set in expression is true.
output :
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:
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.
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
Jump statements.
Output:
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
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:
Output:
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
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.
#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 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.
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
#include <iostream>
using namespace std;
return 0;
}
Output:
5
8
666
#include <iostream>
using namespace std;
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.
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.
int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;
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.
// 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.
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.
#include <iostream>
using namespace std;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
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.
#include <iostream>
using namespace std;
return;
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
result −
When the above code is put together in a file, compiled and executed, it produces the following
Which shows that there is no change in the values though they had been changed inside the
function.
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;
return 0;
}
result −
When the above code is put together in a file, compiled and executed, it produces the following
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;
return;
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
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 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.
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.
For example,
int x[6];
Here,
int - type of element to be stored
x - name of the array
6 - size of the 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}
int main() {
return 0;
}
Run Code
Output
Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have printed
numbers[i].
int main() {
int numbers[5];
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].
#include <iostream>
using namespace std;
int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};
return 0;
}
int main() {
int numbers[2][3];
return 0;
}
#include <iostream>
using namespace std;
int main() {
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.
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 (;)
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.
C++ Program to assign data to members of a structure variable and display it.
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
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.
#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;
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.
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.
room2.calculateArea();
This will call the calculateArea() function inside the Room class for object room2.
room1.length = 5.5;
In this case, it initializes the length variable of room1 to 5.5.
#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() {
return 0;
}
Run Code
Output
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.
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
Run Code
Output
// 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
#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.
public Person() {
Console.WriteLine("Constructor called.");
}
// destructor
~Person() {
Console.WriteLine("Destructor called.");
}
Constructor called.
Destructor called.
In the above example, we have created a destructor ~Person inside the Person class.