Programming Masru
Programming Masru
What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.
C++ gives programmers a high level of control over system resources and
memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11,
C++14, and C++17.
C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
Get Started
This tutorial will teach you the basics of C++.
It is not necessary to have any prior programming experience.
There are many text editors and compilers to choose from. In this tutorial, we
will use an IDE (see below).
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C++ code.
C++ Quickstart
Let's create our first C++ file.
myfirstprogram.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Don't worry if you don't understand the code above - we will discuss it in detail
in later chapters. For now, focus on how to run the code.
Then, go to Build > Build and Run to run (execute) the program. The result
will look something to this:
Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.
Congratulations! You have now written and executed your first C++ program.
C++ Syntax
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Example explained
Line 1: #include <iostream> is a header file library that lets us work with input
and output objects, such as cout (used in line 5). Header files add functionality
to C++ programs.
Line 2: using namespace std means that we can use names for objects and
variables from the standard library.
Don't worry if you don't understand how #include <iostream> and using
namespace std works. Just think of it as something that (almost) always appears
in your program.
Line 4: Another thing that always appear in a C++ program, is int main(). This
is called a function. Any code inside its curly brackets {} will be executed.
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes
the code more readable.
Line 7: Do not forget to add the closing curly bracket } to actually end the main
function.
Omitting Namespace
You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:
Example
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
The cout object, together with the << operator, is used to output values/print
text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
The cout object, together with the << operator, is used to output values/print
text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
New Lines
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code. Comments
can be singled-lined or multi-lined.
Any text between // and the end of the line is ignored by the compiler (will not
be executed).
Example
cout << "Hello World!"; // This is a comment
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
In C++, there are different types of variables (defined with different keywords),
for example:
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Where type is one of C++ types (such as int), and variable is the name of the
variable (such as x or myName). The equal sign is used to assign values to the
variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Other Types
You will learn more about the individual types in the Data Types chapter.
To declare more than one variable of the same type, use a comma-separated
list:
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
C++ Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Example
// Good
int minutesPerHour = 60;
The general rules for constructing names for variables (unique identifiers) are:
C++ Constants
When you do not want others (or yourself) to override existing variable values,
use the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that
are unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
You have already learned that cout is used to output (print) values. Now we will
use cin to get user input.
cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
In the following example, the user can input a number, which is stored in the
variable x. Then we print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion operator
(<<)
cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
In this example, the user must input two numbers. Then we print the sum by
calculating (adding) the two numbers:
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Use the correct keyword to get user input, stored in the variable x:
int x;
cout << "Type a number: ";
>> ;
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
The data type specifies the size and type of information the variable will store:
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for st
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or
1000, and float or double when you need a floating point number (with
decimals), like 9.99 or 3.14515.
int
int myNum = 1000;
cout << myNum;
float
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;
The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore it is
safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
Boolean Types
A boolean data type is declared with the bool keyword and can only take the
values true or false. When the value is returned, true = 1 and false = 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
cout << myGrade;
Alternatively, you can use ASCII values to display certain characters:
Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
The string type is used to store a sequence of characters (text). This is not a
built-in type, but it behaves like one in its most basic usage. String values must
be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
// Include the string library
#include <string>
C++ Math
C++ has many functions that allows you to perform mathematical tasks on
numbers.
Max and min
The max(x,y) function can be used to find the highest value of x and y:
Example
cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
Example
cout << min(5, 10);
Example
// Include the cmath library
#include <cmath>
A list of other popular Math functions (from the <cmath> library) can be found in
the table below:
Function Description
expm1(x) Returns ex -1
int x = 5;
int y = 10;
cout << (x, y);
You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:
Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9
Or even easier:
Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is
equal to 10
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal
to 15
Booleans are the basis for all C++ comparisons and conditions.
Programming ….. creating a set of instructions that tell a computer how to perform a task.
While executing the program, raw data is processed into a desired output format. These computer
programs are written in a programming language which are high level languages.
High level languages
are nearly human languages which are more complex than the computer understandable
programs we are going to write are in a high-level language which is almost similar to human language.
High level programs also make it easier for programmers to inspect and understand each other's
programs easier
The computer only understands binary language (the language of 0’s and 1’s) also called
machine-understandable language or low-level language
What is a compiler?
Computers understand only one language and that language consists of sets of instructions made of
ones and zeros. This computer language is appropriately called machine language.
Because a computer can only understand machine language and humans wish to write in high level
languages high level languages have to be re-written (translated) into machine language at some point.
This is done by special programs called compilers, interpreters, or assemblers that are built into the
various programming applications.
The easiest way for beginners to compile C++ programs is by using an Integrated Development
Environment (IDE). An IDE generally integrates several development tools, including a text editor and
tools to compile programs directly from it.
Visual Studio
Windows Compile console programs using VS Express 2013
Express
Comments in C++
Comments in C++ are simply a piece of source code ignored by the compiler. They are only
helpful for a programmer to add a description or additional information about their source code.
//single-line comment
/* block comment */
The first type will discard everything after the compiler encounters “//”. In the second type, the
compiler discards everything between “/*” and “*/”.
cout is part of the standard library, and all the elements in the standard C++ library are declared within
what is called a namespace: the namespace std.
In order to refer to the elements in the std namespace a program shall either qualify each and every
use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of
its components. The most typical way to introduce visibility of these components is by means of using
declarations:
Identifiers
A valid identifier is a sequence of one or more letters, digits, or underscore characters (_). Spaces,
punctuation marks, and symbols cannot be part of an identifier. In addition, identifiers shall always
begin with a letter. They can also begin with an underline character (_), but such identifiers are -on most
cases- considered reserved for compiler-specific keywords or external identifiers, as well as identifiers
containing two successive underscore characters anywhere. In no case can they begin with a digit.
C++ uses a number of keywords to identify operations and data descriptions; therefore, identifiers
created by a programmer cannot match these keywords. The standard reserved keywords that cannot
be used for programmer created identifiers are:
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores, and digits (0 to 9). ... C++ is a case-sensitive programming
language.
alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case,
catch, char, char16_t, char32_t, class, compl, const, constexpr, const_cast,
continue, decltype, default, delete, do, double, dynamic_cast, else, enum,
explicit, export, extern, false, float, for, friend, goto, if, inline, int,
long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or,
or_eq, private, protected, public, register, reinterpret_cast, return, short,
signed, sizeof, static, static_assert, static_cast, struct, switch, template,
this, thread_local, throw, true, try, typedef, typeid, typename, union,
unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq
Very important: The C++ language is a "case sensitive" language. That means that an identifier
written in capital letters is not equivalent to another one with the same name but written in
small letters. Thus, for example, the RESULT variable is not the same as the result variable or
the Result variable. These are three different identifiers identifiying three different variables.
Character types: They can represent a single character, such as 'A' or '$'. The most basic type
is char, which is a one-byte character. Other types are also provided for wider characters.
Numerical integer types: They can store a whole number value, such as 7 or 1024. They exist in
a variety of sizes, and can either be signed or unsigned, depending on whether they support
negative values or not.
Floating-point types: They can represent real values, such as 3.14 or 0.01, with different levels
of precision, depending on which of the three floating-point types is used.
Boolean type: The boolean type, known in C++ as bool, can only represent one of two
states, true or false.
Character types
char32_t Not smaller than char16_t. At least 32 bits.
Integer types (signed) signed char Same size as char. At least 8 bits.
signed long long int Not smaller than long. At least 64 bits.
unsigned char
unsigned long
long int
float
Declaration of variables
C++ is a strongly-typed language, and requires every variable to be declared with its type before its first
use. This informs the compiler the size to reserve in memory for the variable and how to interpret its
value. The syntax to declare a new variable in C++ is straightforward: we simply write the type followed
by the variable name (i.e., its identifier). For example:
1 int a;
2 float mynumber;
These are two valid declarations of variables. The first one declares a variable of type int with the
identifier a. The second one declares a variable of type float with the identifier mynumber. Once
declared, the variables a and mynumber can be used within the rest of their scope in the program.
If declaring more than one variable of the same type, they can all be declared in a single statement by
separating their identifiers with commas. For example:
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:
1 int a;
2 int b;
3 int c;
To see what variable declarations look like in action within a program, let's have a look at the entire C++
code of the example about your mental memory proposed at the beginning of this chapter:
Initialization of variables
When the variables in the example above are declared, they have an undetermined value until they are
assigned a value for the first time. But it is possible for a variable to have a specific value from the
moment it is declared. This is called the initialization of the variable.
In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the
evolution of the language over the years:
The first one, known as c-like initialization (because it is inherited from the C language), consists of
appending an equal sign followed by the value to which the variable is initialized:
int x = 0;
Introduction to strings
Fundamental types represent the most basic types handled by the machines where the code may run.
But one of the major strengths of the C++ language is its rich set of compound types, of which the
fundamental types are mere building blocks.
An example of compound type is the string class. Variables of this type are able to store sequences of
characters, such as words or sentences. A very useful feature!
A first difference with fundamental data types is that in order to declare and use objects (variables) of
this type, the program needs to include the header where the type is defined within the standard library
(header <string>):
As you can see in the previous example, strings can be initialized with any valid string literal, just like
numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all
initialization formats are valid with strings:
Note: inserting the endl manipulator ends the line (printing a newline character and flushing the
stream).
Constants
Constants are expressions with a fixed value.
Literals
Literals are the most obvious kind of constants. They are used to express particular values within the
source code of a program.
a = 5;
Literal constants can be classified into: integer, floating-point, characters, strings, Boolean, pointers, and
user-defined literals.
Integer Numerals
1 1776
2 707
3 -273
They express real values, with decimals and/or exponents. They can include either a decimal point,
an e character (that expresses "by ten at the Xth height", where X is an integer value that follows
the e character), or both a decimal point and an e character:
1 3.14159 // 3.14159
2 6.02e23 // 6.02 x 10^23
3 1.6e-19 // 1.6 x 10^-19
4 3.0 // 3.0
1 'z'
2 'p'
3 "Hello world"
4 "How do you do?"
The first two expressions represent single-character literals, and the following two represent string
literals composed of several characters. Notice that to represent a single character, we enclose it
between single quotes ('), and to express a string (which generally consists of more than one character),
we enclose the characters between double quotes (").
Both single-character and string literals require quotation marks surrounding them to distinguish them
from possible variable identifiers or reserved keywords. Notice the difference between these two
expressions:
x
'x'
Here, x alone would refer to an identifier, such as the name of a variable or a compound type,
whereas 'x' (enclosed within single quotation marks) would refer to the character literal 'x' (the
character that represents a lowercase x letter).
Character and string literals can also represent special characters that are difficult or impossible to
express otherwise in the source code of a program, like newline (\n) or tab (\t). These special
characters are all of them preceded by a backslash character (\).
Escape
Description
code
\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\a alert (beep)
\\ backslash (\)
For example:
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"
After this directive, any occurrence of identifier in the code is interpreted as replacement, where
replacement is any sequence of characters (until the end of the line). This replacement is performed by
the preprocessor, and happens before the program is compiled, thus causing a sort of blind
replacement: the validity of the types or syntax involved is not checked in any way.
For example:
Note that the #define lines are preprocessor directives, and as such are single-line instructions that -
unlike C++ statements- do not require semicolons (;) at the end; the directive extends automatically until
the end of the line. If a semicolon is included in the line, it is part of the replacement sequence and is
also included in all replaced occurrences.
Operators
Once introduced to variables and constants, we can begin to operate with them by using operators.
What follows is a complete list of operators. At this point, it is likely not necessary to know all of them,
but they are all listed here to also serve as reference.
x = 5;
This statement assigns the integer value 5 to the variable x. The assignment operation always takes
place from right to left, and never the other way around:
x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the moment this
statement is executed is lost and replaced by the value of y.
Consider also that we are only assigning the value of y to x at the moment of the assignment operation.
Therefore, if y changes at a later moment, it will not affect the new value taken by x.
For example, let's have a look at the following code - I have included the evolution of the content stored
in the variables as comments:
This program prints on screen the final values of a and b (4 and 7, respectively). Notice how a was not
affected by the final modification of b, even though we declared a = b earlier.
Assignment operations are expressions that can be evaluated. That means that the assignment itself has
a value, and -for fundamental types- this value is the one assigned in the operation. For example:
y = 2 + (x = 5);
In this expression, y is assigned the result of adding 2 and the value of another assignment expression
(which has itself a value of 5). It is roughly equivalent to:
1 x = 5;
2 y = 2 + x;
x = y = z = 5;
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by C++ are:
operato description
r
+ addition
- subtraction
multiplicatio
*
n
/ division
% modulo
Operations of addition, subtraction, multiplication and division correspond literally to their respective
mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the
remainder of a division of two values. For example:
x = 11 % 3;
results in variable x containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Compound assignment operators modify the current value of a variable by performing an operation on
it. They are equivalent to assigning the result of an operation to the first operand:
y += x; y = y + x;
x -= 5; x = x - 5;
x /= y; x = x / y;
and the same for all other compound assignment operators. For example:
1 ++x;
2 x+=1;
3 x=x+1;
are all equivalent in its functionality; the three of them increase by one the value of x.
In the early C compilers, the three previous expressions may have produced different executable code
depending on which one was used. Nowadays, this type of code optimization is generally performed
automatically by the compiler, thus the three expressions should produce exactly the same executable
code.
A peculiarity 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 name (++x) or after it (x++). Although in simple expressions like x+
+ or ++x, both have exactly the same meaning; in other expressions in which the result of the increment
or decrement operation is evaluated, they may have an important difference in their meaning: In the
case that the increase operator is used as a prefix (++x) of the value, the expression evaluates to the
final value of x, once it is already increased. On the other hand, in case that it is used as a suffix (x++),
the value is also increased, but the expression evaluates to the value that x had before being increased.
Notice the difference:
Example 1 Example 2
x = 3; x = 3;
y = ++x; y = x++;
// x contains 4, y contains 4 // x contains 4, y contains 3
In Example 1, the value assigned to y is the value of x after being increased. While in Example 2, it is the
value x had before being increased.
There are two types of increments:
Prefix increment ++ a and Postfix increment a++
Similarly decrements are also of two types:
Prefix –a and Postfix a—
a++;
++a;
system ("pause");
return 0;
Relational and comparison operators ( ==, !=, >, <, >=, <= )
Two expressions can be compared using relational and equality operators. For example, to know if two
values are equal or if one is greater than the other.
The result of such an operation is either true or false (i.e., a Boolean value).
== Equal to
!= Not equal to
1 (7 == 5) // evaluates to false
2 (5 > 4) // evaluates to true
3 (3 != 2) // evaluates to true
4 (6 >= 6) // evaluates to true
5 (5 < 5) // evaluates to false
Of course, it's not just numeric constants that can be compared, but just any value, including, of course,
variables. Suppose that a=2, b=3 and c=6, then:
Be careful! The assignment operator (operator =, with one equal sign) is not the same as the equality
comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-
hand to the variable on its left, while the other (==) compares whether the values on both sides of the
operator are equal. Therefore, in the last expression ((b=2) == a), we first assigned the
value 2 to b and then we compared it to a (that also stores the value 2), yielding true.
The logical operators && and || are used when evaluating two expressions to obtain a single relational
result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its
operands are true, and false otherwise. The following panel shows the result of
operator && evaluating the expression a&&b:
a b a && b
The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results
of a||b:
|| OPERATOR (or)
a b a || b
For example:
1 ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false )
2 ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false )
When using the logical operators, C++ only evaluates what is necessary from left to right to come up
with the combined relational result, ignoring the rest. Therefore, in the last example ( (5==5)||(3>6)),
C++ evaluates first whether 5==5 is true, and if so, it never checks whether 3>6 is true or not. This is
known as short-circuit evaluation, and works like this for these operators:
operato
short-circuit
r
if the left-hand side expression is false, the combined result is false (the right-hand side
&&
expression is never evaluated).
if the left-hand side expression is true, the combined result is true (the right-hand side
||
expression is never evaluated).
This is mostly important when the right-hand expression has side effects, such as altering values:
Here, the combined conditional expression would increase i by one, but only if the condition on the left
of && is true, because otherwise, the condition on the right-hand side (++i<n) is never evaluated.
If condition is true, the entire expression evaluates to result1, and otherwise to result2.
For example:
In this example, a was 2, and b was 7, so the expression being evaluated (a>b) was not true, thus the
first value specified 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 right-most
expression is considered.
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.
operato asm
description
r equivalent
| OR Bitwise inclusive OR
1 int i;
2 float f = 3.14;
3 i = (int) f;
The previous code converts the floating-point number 3.14 to an integer value (3); the remainder is
lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is to use the
functional notation preceding the expression to be converted by the type and enclosing the expression
between parentheses:
i = int (f);
sizeof
This operator accepts one parameter, which can be either a type or a variable, and returns the size in
bytes of that type or object:
x = sizeof (char);
Here, x is assigned the value 1, because char is a type with a size of one byte.
The value returned by sizeof is a compile-time constant, so it is always determined before program
execution.
Other operators
Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the
specifics for object-oriented programming.
Precedence of operators
A single expression may have multiple operators. For example:
x = 5 + 7 % 2;
In C++, the above expression always assigns 6 to variable x, because the % operator has a higher
precedence than the + operator, and is always evaluated before. Parts of the expressions can be
enclosed in parenthesis to override this precedence order, or to make explicitly clear the intended
effect. Notice the difference:
From greatest to smallest priority, C++ operators are evaluated in the following order:
Leve
Precedence group Operator Description Grouping
l
() functional forms
2 Postfix (unary) Left-to-right
[] subscript
+ - unary prefix
= *= /= %= += -
= assignment / compound
Assignment-level >>= <<= &= ^= | assignment
15 Right-to-left
expressions =
?: conditional operator
Basic I/O in C++:C++ comes with libraries which provides us with many ways for performing
input and output. In C++ input and output is performed in the form of a sequence of bytes or
more commonly known as streams. The two keywords cout and cin are used very often for
taking inputs and printing outputs. These two are the most basic methods of taking input and
output in C++.
Algorithm
An algorithm is a procedure used for solving problem or performing a computation.
Algorithms act as an exact list of instructions that conduct specified actions step by
step in either hardware or software based routines. Algorithms are used widely
throughout all areas of IT.
Flowcharts
A flowchart is a type of diagram that represents an algorithm, workflow or process.
The flowchart shows the steps as boxes of various kinds, and their order by connecting the boxes
with arrows. This diagrammatic representation illustrates a solution model to a given problem.
The rounded rectangles, or terminal points, indicate the flowchart's starting and ending
points.
Flow Lines
Note: The default flow is left to right and top to bottom (the same way you read English).
To save time arrowheads are often only drawn when the flow lines go contrary the normal.
Input/Output
Process
Decision
The diamond is used to represent the true/false statement being tested in a decision symbol.
Variable
A scope is a region of the program and broadly speaking there are three places, where
variables can be declared −
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us
explain what are local and global variables.
Local Variables
Variables that are declared inside a function or block are local variables. They can be
used only by statements that are inside that function or block of code. Local variables
are not known to functions outside their own. Following is the example using local
variables −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
Global variables are defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. Following is the
example using global and local variables −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local
variable inside a function will take preference. For example −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result −
10
1. Local Scope: A variable is said to have a local scope or is local when it is declared inside
a code block. The variable remains active only inside the block and is not accessible
outside the code block.
2. Global Scope: A variable has a global scope when it is accessible throughout the
program. A global variable is declared on top of the program before all the function
definitions.
Example:
#include <iostream.h>
Int globalResult=0; //global variable
int main()
{
Int localVar = 10; //local variable.
…..
Precedence when there is a Global variable and a Local variable in the program with the
same name
Answer: Whenever there is a local variable with the same name as that of a global variable, the
compiler gives precedence to the local variable.
Example:
#include <iostream>
int x = 10;
int main()
{
int x = 5;
cout<<x<<endl;
}
The output of the above code is 5. This is because, although both the variables have the same
name, the compiler has given preference to the local scope.
When there is a Global variable and Local variable with the same name, how will you
access the global variable?
Answer: When there are two variables with the same name but different scope, i.e. one is a local
variable and the other is a global variable, the compiler will give preference to a local variable.
In order to access the global variable, we make use of “scope resolution operator (::)”. Using
this operator, we can access the value of the global variable.
Example:
#include<iostream.h>
int x= 10;
int main()
{
int x= 5;
cout<<”Global Variable x = “<<::x;
cout<<”\nlocal Variable x= “<<x;
}
Output:
Global Variable x = 10
local Variable x= 2
Answer: A constant is an expression that has a fixed value. They can be divided into integer,
decimal, floating point, character or string constants depending on their data type.
Apart from decimal, C++ also supports two more constants i.e. octal (to the base 8) and
hexadecimal (to the base 16) constants.
Examples of Constants:
75 //integer (decimal)
0113 //octal
0x4b //hexadecimal
3.142 //floating point
‘c’ //character constant
“Hello, World” //string constant
Note: When we have to represent a single character, we use single quotes and when we want to
define a constant with more than one character, we use double quotes.
unary operator
It is an operator that acts on one operand e g
++x or x--
binary operator
+,-,* a+b
ternary operator
All programs could be written in terms of only three control structures, namely,
The term "control structures" comes from the field of computer science. When we introduce C++'s
implementations of control structures, we'll refer to them in the terminology of the C++ standard document as
"control statements."
The if...else selection statement performs an action if a condition is true or performs a different action if the
condition is false.
The switch selection statement performs one of many different actions, depending on the value of an integer
expression.
The if selection statement is a single-selection statement because it selects or ignores a single action
The if...else statement is called a double-selection statement because it selects between two different
actions
The switch selection statement is called a multiple-selection statement because it selects among many
different actions
CONDITIONAL STATEMENTS
There are three conditional statements :
If
If-else
Switch
THE IF STATEMENT
Syntax
If(condition)
{
Statement(s)
}
EXAMPLE
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
cout<<"enter age";
cin>>age;
if(age <18)
{
cout<<"you are a juvenile you can not vote";
}
return 0;
}
Flowchart of if statement
The if statement will execute the statement when the when the condition is true.
It does nothing when the condition is false.
In many situations we want to specify both actions when the condition is true and when it is false.
If the condition is true take one action else take another action.
This is possible through if else statements.
SYNTAX
If (condition)
Statement1;
}
Else
{
Statement2;
}
EXAMPLE
// IF-ELSE Statements.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int age;
cout<<"enter age";
cin>>age;
if(age <18)
{
cout<<"you are a juvenile you can not vote";
}
else
{
cout<<"you are an adult go and vote\n";
}
system("pause");
return 0;
}
SYNTAX
if (condition 1)
statements;
else if (condition 2)
statements;
else if (condition n)
statements;
... ... ...
else
statements;
EXAMLE
#include <iostream>
using namespace std;
int main ()
{
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
Else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
condition is initially false, the action (or group of actions) will not execute.
The do...while statement performs the action (or group of actions) in its body at least once.
Each of the words if, else, switch, while, do and for is a C++ keyword.
These words are reserved by the C++ programming language to implement various features, such as C++'s
control statements. Keywords must not be used as identifiers, such as variable names.
The if Statement
Use the if statement to specify a block of C++ code to be executed if a
condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
C++ Else
The else Statement
Use the else statement to specify a block of code to be executed if the condition
is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
C++ Else If
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and
condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
int time = 22;
if (time < 10)
{
cout << "Good morning.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Instead of writing:
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
SYNTAX
If (condition)
{
statement1;
Else
Statement2;
Else
Statement3;
EXAMLE
#include <iostream>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int n=6;
//outer if statement
if (n % 2==0) {
//Inner if statement
if(n % 3==0){
cout <<"divisible by 2 and 3";
else {
return 0;
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
Note: The default keyword must be used as the last statement in the switch,
and it does not need a break.
C++ Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
A loop is used to execute statements more than once. It involves repeating of
some portions of a program either a specified number of times or until a
particular condition is satisfied.
While loop
Do while loop
For loop
If the condition is false at the start, the loop will not be executed at all.
The while loop loops through a block of code as long as a specified condition
is true:
Syntax
while (condition)
{
// code block to be executed
}
NOTE: For any type of a loop , these three points are important:
Initialization;
While (condition)
Statements
EXAMLE
#include <iostream>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int main(int argc, char** argv)
int i = 1 ;
while (i<11)
i++;
return 0;
include <iostream>
int i = 10 ;
while (i > 0)
i--;
return 0;
In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
PROGRAM TO ADD 10 INTEGERS
EXAMPLE
#include <iostream>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int i = 1;
int sum = 0;
while (i<=10)
i++;
}
return 0;
EXAMPLE
#include <iostream>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int i = 1;
int prod = 1;
while (i <= 5)
prod =prod * i;
i++;
cout << prod << "\n";
return 0;
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
C++ Exercises
Test Yourself With Exercises
Exercise:
Print i as long as i is less than 6.
int i = 1;
(i < 6) {
cout << i << "\n";
;
}
C++ Do/While Loop
Do while loop is similar to the while loop except that the do while loop test the
condition at the end of the loop called posttest.
NOTE: The body of the loop will be executed at least once in the worst case.
Syntax
do {
// code block to be executed
}
while (condition);
If you do not use it, the compiler will display syntax error.
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the loop
will never end!
The while loop tests the condition before executing any of the statements within
the while loop that is before entering the loop and it is called pretest
The do while loop tests the condition after having executed the statements
within the loop at least once that is at the end of the loop which is called
posttest.
NOTE: This means that the do while loop would execute its statements at least
once.
The while loop on the other hand will not execute its statements if the condition
fails for the first time that is loop is executed zero times or multiple times.
EXAMPLE
#include <iostream>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
do
rev = num % 10 ;
num = num/10 ;
return 0;
It is often the case in programming that you want to do something for a fixed
number of times.
The for loop is ideal suited for such cases since it allows us to specify three
important things about a loop in a single line that is
1 initialization
2 condition
3 increment or decrement
Syntax
for (initialization; condition; increment or decrement of counter)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 1 to 10:
Example
// For loop incremental.cpp : Defines the entry point for the console
application.
//
#include "stdafx.h"
#include <iostream>
using namespace std ;
system("pause");
return 0;
}
Example explained
Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}
ANOTHER EXAMLE
// FOR LOOP table of results.cpp : Defines the entry point for the console
application.
//
#include "stdafx.h"
#include <iostream>
using namespace std ;
{
cout<<i<<"\t\t"<<i*i<<"\n";
system("pause");
return 0;
}
Exercise:
Use a for loop to print "Yes" 5 times:
(int i = 0; i < 5; ) {
cout << << "\n";
}
NOTE : You may be thinking why there are two loops doing the same thing
It is convenient to use while loop when you don’t have any idea how many times the loop will be
repeated.
The for loop is usually used in those cases when you know the number of times the loop will be
repeated in advance.
In nested for loop, the outer loop starts its execution by initializing the loop counter and
checking the condition.
SYNTAX
for (initialization; condition; increase/decrease)
Statement(s)
EXAMPLE
// nested for loop.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
cout<<"\n";
system("pause");
return 0;
}
C++ Break and Continue
C++ Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}
Continue Example
int i = 0;
while (i < 10)
{
if (i == 4)
{
i++;
continue;
}
cout << i << "\n";
i++;
}
C++ Exercises
Test Yourself
Exercise:
Stop the loop if i is 5:
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:
string cars[4];
We have now declared a variable that holds an array of four strings. To insert
values to it, we can use an array literal - place the values in a comma-separated
list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Example
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
C++ Exercises
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}
The following example outputs the index of each element together with its
value:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}
C++ Omit Array Size
This is completely fine. However, the problem arise if you want extra space for
future elements. Then you have to overwrite the existing values:
If you specify the size however, the array will reserve the extra space:
Now you can add a fourth and fifth element without overwriting the others:
cars[3] = {"Mazda"};
cars[4] = {"Tesla"};
string cars[5];
cars[0] = {"Volvo"};
cars[1] = {"BMW"};
...
C++ Functions
Why Functions?
At times, a certain portion of codes has to be used many times. Instead of re-writing the
codes many times, it is better to put them into a " function ", and "call" this " function "
many time - for ease of maintenance and understanding.
The benefits of using functions are:
Advantages of using functions in a program
Divide and conquer: construct the program from simple, small pieces or components.
Modularize the program into self-contained tasks.
1. Avoid repeating codes: It is easy to copy and paste, but hard to maintain and
synchronize all the copies.
2. Software Reuse: you can reuse the functions in other programs, by packaging
them into library codes.
Two parties are involved in using a function: a caller who calls the function, and
the function called. The caller passes argument(s) to the function. The function receives
these argument(s), performs the programmed operations within the function's body,
and returns a piece of result back to the caller.
Def:-
Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you
can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():
Syntax
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Declaration: return type the function's name, and parameters (if any)
Definition: the body of the function (code to be executed)
Note: If a user-defined function, such as myFunction() is declared after the main() function, an
error will occur. It is because C++ works from top to bottom; which means that if the function is not
declared above main(), the program is unaware of it:
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
However, it is possible to separate the declaration and the definition of the function - for code
optimization.
You will often see C++ programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Exercises
void () {
cout << "I just got executed!";
}
int main() {
;
return 0;
}
Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma:
Syntax
int add(parameter1, parameter2, parameter3) {
// code to be executed
}
The following example has a function that takes integers int a and int b as
formal parameters.
Example
Int add(int a, int b) // decalartion
{ //definition
int c;
c=a+b;
return c;
}
int main() {
If we call the function without an argument, it uses the default value ("Norway"):
Example
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Note that when you are working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.
Return Values
If you want the function to return a value, you can use a data type (such
as int, string, float etc.) instead of void, and use the return keyword inside the
function.
void keyword
The void keyword, indicates that the function should not return a value.
Therefore, no need to write the return keyword inside the function body.
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
The pass by reference method of passing arguments to a function copies the address
of an argument into the formal parameter. This can be useful when you need to
change the value of the arguments.
Pass by value
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum
and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
C++ Function Overloading
Function overloading in C++: C++ program for function
overloading. Function overloading means two or more functions
can have the same name but either the number of arguments or
the data type of arguments has to be different.
Return type has no role because the function will return a value
when it is called and at compile time compiler will not be able to
determine which function to call. In the first example in our code,
we make two functions one for adding two integers and other for
adding two floats, but they have the same name, and in the
second program we make two functions with identical names but
pass them a different number of arguments. Function
overloading is also known as compile time polymorphism.
Output of program:
1.C programming
2.C programming
3.C++ programming
Function Overloading
With function overloading, multiple functions can have the same name with
different parameters:
Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which have two functions that add numbers of
different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
}
Example
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Note: Multiple functions can have the same name as long as the number and/or
type of parameters are different.
Function Prototype
In C++, a function must be declared before it can be called. It can be achieved by either
placing the function definition before it is being used, or declare a so-called function
prototype.
A function prototype tells the compiler the function's interface, i.e., the return-type,
function name, and the parameter type list (the number and type of parameters). The
function can now be defined anywhere in the file. For example,
You could optionally include the parameter names in the function prototype. The names
will be ignored by the compiler, but serve as documentation. For example,
// Function Prototype
double getArea(double radius); // parameter names are ignored, but serve as
documentation
int max(int number1, int number2);
Function prototypes are usually grouped together and placed in a so-called header file.
The header file can be included in many programs. We will discuss header file later.
Another Example
We have a function called max(int, int), which takes two int and return their
maximum. We invoke the max() function from the main().
1/* Testing max function (TestMaxFunction.cpp) */
2#include <iostream>
3using namespace std;
4
5int maximum(int, int); // Function prototype (declaration)
6
7int main() {
8 cout << maximum(5, 8) << endl; // Call maximum() with literals
9
10 int a = 6, b = 9, c;
11 c = maximum(a, b); // Call maximum() with variables
12 cout << c << endl;
13
14 cout << maximum(c, 99) << endl; // Call maximum()
15}
16
17// Function definition
18// A function that returns the maximum of two given int
19int maximum(int num1, int num2) {
20 return (num1 > num2) ? num1 : num2;
21}
Types of function
We have two types of function in C++:
1) Built-in functions
2) User-defined functions
1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and
define these functions as they are already written in the C++ libraries such as
iostream, cmath etc. We can directly call them when we need.
Here we are using built-in function pow(x,y) which is x to the power y. This
function is declared in cmath header file so we have included the file in our
program using #include directive.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}
Output:
32
2) User-defined functions
We have already seen user-defined functions, the example we have given at the
beginning of this tutorial is an example of user-defined function. The functions
that we declare and write in our programs are user-defined functions. Lets see
another example of user-defined functions.
User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);
int main(){
int x, y;
cout<<"enter first number: ";
cin>> x;
C++ OOP
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and
functions from the class.
You will learn much more about classes and objects in the next chapter.
C++ Classes and Objects
C++ Classes/Objects
Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
Attributes and methods are basically variables and functions that belongs to
the class. These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.
Create a Class
Example
Create a class called "MyClass":
Example explained
Create an Object
In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object
name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the
object:
Example
int main() {
MyClass myObj; // Create an object of MyClass
Example
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Class Methods
In the following example, we define a function inside the class, and we name it
"myMethod".
Note: You access methods just like you access attributes; by creating an object
of the class and by using the dot syntax ( .):
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
To define a function outside the class definition, you have to declare it inside the
class and then define it outside of the class. This is done by specifiying the
name of the class, followed the scope resolution :: operator, followed by the
name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
Example
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
C++ Constructors
Constructors
Example
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call
the constructor)
return 0;
}
Note: The constructor has the same name as the class, it is always public, and
it does not have any return value.
Constructor Parameters
Constructors can also take parameters (just like regular functions), which can be
useful for setting initial values for attributes.
The following class have brand, model and year attributes, and a constructor with
different parameters. Inside the constructor we set the attributes equal to the
constructor parameters (brand=x, etc). When we call the constructor (by creating
an object of the class), we pass parameters to the constructor, which will set the
value of the corresponding attributes to the same:
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different
values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
Just like functions, constructors can also be defined outside the class. First,
declare the constructor inside the class, and then define it outside of the class
by specifying the name of the class, followed by the scope
resolution :: operator, followed by the name of the constructor (which is the
same as the class):
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
int main() {
// Create Car objects and call the constructor with different
values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
Access Specifiers
By now, you are quite familiar with the public keyword that appears in all of our
class examples:
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
The public keyword is an access specifier. Access specifiers define how the
members (attributes and methods) of a class can be accessed. In the example
above, the members are public - which means that they can be accessed and
modified from outside the code.
However, what if we want members to be private and hidden from the outside
world?
Example
class MyClass
{
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
error: y is private
Tip: It is considered good practice to declare your class attributes as private (as
often as you can). This will reduce the possibility of yourself (or others) to mess
up the code. This is also the main ingredient of the Encapsulation concept,
which you will learn more about in the next chapter.
Note: By default, all members of a class are private if you don't specify an
access specifier:
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
C++ Encapsulation
Encapsulation
Encapsulation
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
Example
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Example explained
Inside main(), we create an object of the Employee class. Now we can use
the setSalary() method to set the value of the private attribute to 50000. Then
we call the getSalary() method on the object to return the value.
Why Encapsulation?
C++ Inheritance
Inheritance
Inheritance
inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which are defined in other class.
derived class (child) - the class that inherits from another class
base class (parent) - the class being inherited from
In the example below, the Car class (child) inherits the attributes and methods
from the Vehicle class (parent):
Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Multilevel Inheritance
A class can also be derived from one class, which is already derived from
another class.
Example
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Multiple Inheritance
A class can also be derived from more than one base class, using a comma-
separated list:
Example
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Access Specifiers
You learned from the Access Specifiers chapter that there are three specifiers
available in C++. Until now, we have only used public (members of a class are
accessible from outside the class) and private (members can only be accessed
within the class). The third specifier, protected, is similar to private, but it can
also be accessed in the inherited class:
Example
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
C++ Polymorphism
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
Like Inheritance lets us inherit attributes and methods from another class. Polymorphism uses
those methods to perform different tasks. This allows us to perform a single action in different ways.
For example, think of a base class called Animal that has a method called animalSound(). Derived
classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation
of an animal sound (the pig oinks, and the cat meows, etc.):
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};
Remember from the Inheritance chapter that we use the : symbol to inherit from a class.
Now we can create Pig and Dog objects and override the animalSound() method:
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
C++ Polymorphism
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
For example, think of a base class called Animal that has a method
called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds
- And they also have their own implementation of an animal sound (the pig
oinks, and the cat meows, etc.):
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};
Remember from the Inheritance chapter that we use the : symbol to inherit
from a class.
Now we can create Pig and Dog objects and override the animalSound() method:
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
Next Page
The main purpose of C++ programming is to add object orientation to the C
programming language and classes are the central feature of C++ that supports object-
oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation
and methods for manipulating that data into one neat package. The data and functions
within a class are called members of the class.
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly
using direct member access operator (.) dot operator. We will learn how private and
protected members can be accessed.
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable.
2 Class Access Modifiers
A class member can be defined as public, private or protected. By default
members would be assumed as private.
4 Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with
an object of the same class, which has been created previously.
5 Friend Functions
A friend function is permitted full access to private and protected members of a
class.
6 Inline Functions
If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time.
7 this Pointer
Every object has a special pointer this which points to the object itself.
The core of the pure object-oriented programming is to create an object, in code, that has certain
properties and methods. While designing C++ modules, we try to see whole world in the form of objects.
For example a car is an object which has certain properties such as color, number of doors, and the like.
It also has certain methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented programming −
Object
This is the basic unit of object oriented programming. That is both data and function that operate on
data are bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained.
Similar way, C++ classes provides different methods to the outside world without giving internal detail
about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which variables but
object-oriented programming provides you framework to place the data and the relevant functions
together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the existing
class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the
code size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or
functions to the operators or functions is called polymorphism. Poly refers to many. That is a single
function or an operator functioning in many ways different upon the usage is called polymorphism.
Overloading
The concept of overloading is also a branch of polymorphism. When the exiting operator or function is
made to operate on new data type, it is said to be overloaded.
C++ Files
C++ Files
Example
#include <iostream>
#include <fstream>
There are three objects included in the fstream library, which are used to create,
write or read files:
fstream A combination of ofstream and ifstream: creates, reads, and writes to files
To create a file, use either the ofstream or fstream object, and specify the name
of the file.
To write to the file, use the insertion operator (<<).
Example
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
Read a File
To read from a file, use either the ifstream or fstream object, and the name of
the file.
Note that we also use a while loop together with the getline() function (which
belongs to the ifstream object) to read the file line by line, and to print the
content of the file:
Example