Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C M M Sammurized Note

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

Language – Practical Tutorial

Compiled by. Mr. James Batista A. L


Don Bosco Vocational Training Center – Gumbo
Juba South Sudan

Student’s Information
Name: _________________________________________________________
Year: ______________________ Shift _______________________________
Tel: _________________________ Email: ____________________________
1

Who Invented C++? | and a Quick brief History


Bjarne Stroustrup created the C++ programming language in 1980 at AT&T Bell Laboratories. He
discovered that "C" was lacking in simulations (the technique of representing the real world by a
computer program) and decided to extend the language by incorporating some features from Simula
67, his favorite language.
Simula 67 was one of the first object-oriented programming languages. Bjarne Stroustrup originally
referred to it as "C with Classes."
Rick Mascitti coined the term "C++." The "++" operator is an increment operator in C++. C++ has
evolved to deal with problems encountered by users and through discussions at AT&T since its
inception.
The C++ programming language first appeared in 1985. Can you imagine the age of this language?
Because of its age, the language is now very stable, and there is a large community to help you if
you start coding in C++ and get stuck somewhere.

What is C++?
C++ is a general-purpose computer programming language that has the following primary
characteristics:
• object-oriented
• dynamic memory allocation
• generic
• functional

C++ is a C programming language extension. C++ contains all of the elements of the C language as
well as extra features for working with objects, classes, events, and other object-oriented concepts.
C++ influenced many computer programming languages, of which the following is a list of some of
the most famous and powerful ones:
• Java
• Python
• PHP
including C#, Perl, and many more.

The main reasons for C++'s (why C++?)


The main reason why C++ is so successful and well-known is that it uses object-oriented technology,
which is the newest and most realistic way to make software.
1. C++ Popularity and High Salary
C++ is one of the most popular languages in the world. It is used by some 4.4 million
developers worldwide. Also, C++ Developers are quite sought and they hold some of the
most high-paying jobs in the industry with an average base pay of $103, 035 per year.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
2

2. C++ has Abundant Library Support


C++ has the Standard Template Library (STL) which is very useful as it helps in writing code
compactly and quickly as required. It contains mainly four components i.e. algorithms, containers,
functions, and iterators.
3. C++ has a Large Community
There is a large online community of C++ users and experts that is particularly helpful in case any
support is required. There are a lot of resources like GeeksforGeeks etc. available on the internet
regarding C++. Some of the other online resources for C++
include StackOverflow, cppreference.com, Standard C++, etc.
4. C++ in Databases
There are many modern-day databases such as MySQL, MongoDB, MemSQL, etc. that are written
in C++. This is because C++ is quite modern and it supports features like exceptions, lambda
expressions, etc. Many of the databases that are written in C++ are used in almost all of the in-use
applications such as YouTube, WordPress, Twitter, Facebook, etc.
5. C++ in Operating Systems
All the major operating systems such as Windows, Linux, Android, Ubuntu, iOS, etc. are written
in a combination of C and C++. The Windows applications are written in C++, while Android
applications are written in Java along with C/C++ with non-default run-times for C++ support. Also,
C++ can be used to develop the core of the applications in iOS. In general, C or C++ are used in
operating systems because of the speed and strongly typed nature of these languages.
6. C++ in Compilers
C++ is closer to the hardware level and is a comparatively low-level language. Because of this
reason, it is used in many compilers as a backend programming language. An example of this is
the GNU Compiler Collection (GCC) which is currently written mostly in C++ along with C.
7. C++ in Web Browsers
A lot of web browsers are developed using C++ such as Chrome, Firefox, Safari, etc. Chrome
contains C++ in the rendering engine, JavaScript engine, and UI. Firefox uses mainly in the rendering
engine and a little in the UI. Safari also uses C++ in the rendering engine and JavaScript engine. All
these web browsers and more use C++, particularly in the rendering engines because it provides the
required speed that is necessary for the rendering engines since they need to display the content at
an accelerated rate.
8. C++ in Graphics
Applications requiring graphics such as digital image processing, computer vision, screen
recording programs, etc. use C++ due to its high speed. This can also include different games that
have graphics as a big part of their structure.
9. C++ in Embedded Systems
C++ is closer to the hardware level and so it is quite useful in embedded systems as the software and
hardware in these are closely coupled. There are many embedded systems that use C++ such
as smart watches, MP3 players, GPS systems, etc.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
3

10. C++ is Portable


Program developed in C++ that can be moved from one platform to another. This is one of the main
reasons that applications requiring multi-platform or multi-device development often use C++.

C++ Environment Setup


For setting up a C++ Integrated Development Environment (IDE) on your local machine you need
to install two important software:
1. C++ Compiler
2. Text Editor
For C++, we'd recommend these:
• For Windows, Falcon, Code::block, Visual Studio is the common choice. The Community
Edition is free and has everything we'll need.
• For Mac, Xcode is likely the best option. It can be downloaded for free from the App Store.
• For Linux, Qt Creator is a commonly recommended choice.
The files you create with your editor are called source files and for C++ they typically are named
with the extension .cpp, .cp, or .c.
You can install any of these text editor or built-in IDEs
• Vim, Clion, Falcon, Codeblocks, Visual Studio Code, Sublime Notepad++, DEV ++ and so
forth.
For our case, we are going to use falcon. To install it, visit their website Falcon C++ download |
SourceForge.net

Concept of OOPs
1. Inheritance
Inheritance is the process by which one object can acquire the properties of another. When the class
child, inherits the class parent, the class child is referred to as derived class (sub class) and the class
parent as a base class (super class). In this case, the class child has two parts: a derived part and an
incremental part. The derived part is inherited from the class parent. The incremental part is the new
code written specifically for the class child.
2. Polymorphism.
Comes from the Greek words “poly” and “morphism”. “poly” means many and “morphism” means
form i.e.. many forms. Polymorphism means the ability to take more than one form. For
example, an operation has different behavior in different instances. The behavior depends upon the
type of the data used in the operation.
3. Encapsulation
Wrapping of data and functions together as a single unit is known as encapsulation. By default, data
is not accessible to outside world and they are only accessible through the functions which are
wrapped in a class. prevention of data direct access by the program is called data hiding or
information hiding

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
4

4. Data abstraction
Abstraction refers to the act of representing essential features without including the back ground
details or explanation. Classes use the concept of abstraction and are defined as a list of attributes
such as size, weight, cost and functions to operate on these attributes. They encapsulate all essential
properties of the object that are to be created. The attributes are called as data members as they hold
data and the functions which operate on these data are called as member functions. Class use the
concept of data abstraction so they are called abstract data type (ADT)

Basic syntax in C++


#include <iostream>
Using namespace std;
Int main ()
{
cout<<”Hello World!”;
return 0;
}

• #include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
lines with expressions but indications for the compiler's preprocessor. In this case the directive
#include <iostream> tells the preprocessor to include the iostream standard file. This specific file
(iostream) includes the declarations of the basic standard input-output library in C++, and it is
included because its functionality is going to be used later in the program.
• using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std.
So, in order to access its functionality, we declare with this expression that we will be using these
entities. This line is very frequent in C++ programs that use the standard library, and in fact it will
be included in most of the source codes included in these tutorials.
• int main ()
This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C++ programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined before or
after it – the instructions contained within this function's definition will always be the first ones to
be executed in any C++ program.
For that same reason, it is essential that all C++ programs have a main function. The word main is
followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++,
what differentiates a function declaration from other types of expressions are these parentheses that
follow its name. Optionally, these parentheses may enclose a list of parameters within them.
• cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible effect

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
5

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).
• 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.

Let us write our first program in C++


Example
#include<iostream>
using namespace std;
int main()
{
cout<<"Welcome!";
cout<<endl;
return 0;
}

To see the output of the above C++ source code, navigate to "Build" and select "Build and run" or
directly hit the "F9" key. After building and running the above C++ program, here is a snapshot of
the output:

I used the red arrow to focus your attention solely on the output text.
In a separate article, I defined each and every line of code in the preceding C++ example program.
You can find it here: C++ basic syntax.
Now that everything is in place, let's get started on the course.
Exercise 1:
- Write a C++ program to print “Hello World!”
- Write a program to print your Name:

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
6

Comments in C++
Comments are content written within the program to explain specific blocks of code or to aid in
debugging.
Comments are text that is ignored by the compiler during compilation and execution in C++ or any
other programming language. The two types of comments that can be used in a C++ program are as
follows:
1. Single-line comments
2. Multi-line comments

Single-line comments in C++


Comments that span only one line are known as "single-line comments." Anything written after "//"
is referred to as the content of the single-line comment. For example:
// C++ program to print " hello world " on output console.
#include<iostream>
using namespace std;
int main()
{
cout<<"hello world!";
// cout<<" hello world ";
cout<<endl;

return 0;
}
In the above example, the second "cout" statement will not be executed because I used "//" to make
it a comment.

Multi-line comments in C++


Comments that span multiple lines are known as "multi-line comments." Anything written between
"/*" and "*/" is referred to as a multi-line comment. For example:
#include<iostream>
using namespace std;
int main()
{
/* The following statement
* will print the text
* " hello world "
* on the output console
*/
cout<<" hello world";
cout<<endl;

return 0;
}

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
7

You will get the same output as in the previous example. You can also use "/* comment_content */"
to write a single-line comment.

Concept of Comments in Computer Programming


Comments can be used for the various purpose like:
1. Planning and reviewing:
In comments, we can write the pseudocode which we planned before writing the source code.
Pseudocode is a mixture of natural language and high-level programming language.
2. Code description:
Code description is used by the programmer to make others understand his/her intent. It contains
the summary of the code.
3. Algorithmic description:
Comments are used for explanation of the methodology. Such explanations may include
diagrams and formal mathematical proofs. This may constitute the explanation of the code, rather
than a clarification of its intent. For example, a programmer may add a comment to explain why
an insertion sort was chosen instead of a quicksort, as the former is, in theory, slower than the
latter.
4. Resource inclusion:
Logos, diagrams, and flowcharts consisting of ASCII art constructions can be inserted into source
code formatted as a comment. Further, copyright notices can be embedded within source code as
comments.
5. Metadata:
Comments also contain metadata of the program. This metadata helps in software maintenance.
The metadata includes the name of the creator of the original version, current maintainer of the
program, data when the first version was created, the name of the people who have edited the
program files so far etc.
6. Debugging:
Brute force method is a common method of debugging. In this approach, print statements are
inserted throughout the program to print the intermediate values with the hope that some of the
printed values will help to identify the errors. After doing debugging we comment those print
statements. Hence comment is also used for debugging.
7. Automatic documentation generation:
Programming tools sometimes store documentation and metadata in comments. These may
include insert positions for automatic header file inclusion, commands to set the file’s syntax
highlighting mode, or the file’s revision number.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
8

8. Stress relief:
Commenting on development tools, competitors, employers, working conditions, or the quality
of the code itself are the ways to relieve stress. The occurrence of this phenomenon can be easily
seen from online resources that track profanity in source code.

Constants in C++
Constants in C++ refer to variables with fixed values that cannot be changed. Once they are defined
in the program, they remain constant throughout the execution of the program. They are generally
stored as read-only tokens in the code segment of the memory of the program. They can be of any
available data type in C++ such as int, char, string, etc.
To create a constant variable in C++, use the "const" keyword before defining a normal variable.
As an example:
#include<iostream>
using namespace std;
int main()
{
const float pi = 3.1416;
float rad = 10.3;

cout<<"Area = "<<pi*rad*rad;
cout<<endl;

return 0;
}
I used the following C++ statement in the above example
cout<<endl;
only to create a single line space between the output text and the "Process returned 0 (0x0) execution
time: 0.047 s" for your convenience to make the output text more visible.

Escape Sequences in C++


Characters that are part of an escape sequence do not actually represent themselves; rather, they
generate other outputs. For instance, inserting the character "\n" into the escape sequence causes a
new line to be displayed on the output console. The following is a list of characters that can be used
as escape sequences in C++.
• \a: Audible bell (alert)
• \b: Backspace
• \f: Formfeed
• \n: Newline or linefeed
• \r: Carriage Return
• \t: Horizontal tab
• \v: Vertical tab
• \\: Backslash
• \': Single quote

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
9

• \": Double quote


• \?: Question mark
• \On: Octal number (On represents the number in octal)
• \xHn: Hexadecimal number (Hn represents the number in hexadecimal)
• \0: Null
For example:
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello,";
cout<<"\my name is William,\n\n\n";
cout<<"\tand \t\tI\'ve been a ";
cout<<"\n\"C++ programmer\"";
cout<<" for \'eight years.\'";
cout<<endl;
return 0;
}

Exercise 2:
Write a program to print the following | Use Single and Multi-line comments:
1- Name
2- Date
3- Year

C++ Identifiers and Keywords with Examples


In this article, you will learn about "identifiers" and "keywords," the two most important topics when
discussing C++ programming. So, without further ado, let us start with the identifiers.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
10

What are identifiers?


Identifiers are the basic building blocks of a program. Identifiers are used as a general name given
to different parts of the program, namely variables, objects, classes, functions, arrays, etc.
Since C++ is a case-sensitive language, therefore, "hello world," "Hello world," "Hello
World," and "HELLO WORLD" are all four different identifiers.

Rules to create or name an identifier in C++


To create an identifier in the C++ language, you need to follow the following rules:
• An identifier must begin with a letter from A to Z, a-z, or _ (an underscore character).
• Then we can add letters (A-Z, a-z), digits (0-9), and underscores to its name.
• Reserved words (keywords) are not allowed to be used as identifiers.
Following is a list of some valid identifiers. This list is included for your convenience because
examples help to make the topic more understandable.
• Hello_world
• Myvar
• _myvar
• _my34var_
• sum_of_two_numbers

Tip: You may either use underscore in variable names to separate parts of the name, such as
last_name, first_name, and main_balance, or you may go for "capital style" notation, such as
lastName, firstName, and mainBalance, i.e., capitalizing the first letter of the next word.

C++ Identifiers Example


The following C++ program is an example program of C++ identifiers that will give you an idea of
how identifiers are used in C++ programming:
#include<iostream>
using namespace std;
int main()
{
char ch;
char name[20];
int num;
cout<<"Enter a character: ";
cin>>ch;
cout<<"You entered: "<<ch<<endl;
cout<<"\nEnter your name: ";
cin>>name;
cout<<"Your name is: "<<name<<endl;
cout<<"\nEnter a number: ";
cin>>num;
cout<<"You entered: "<<num<<endl;
return 0;
}

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
11

Exercise 3:
Write a program to collect your personal information | remember to apply escape sequences:
1- First_Name:
2- Second_Name:
3- Department:
4- Index_No:

Keywords in C++
To a language compiler, certain words have a heightened significance, and these are known as
keywords. Because these are reserved words that are used for specific purposes, you are not allowed
to use them as regular identifier names.
I previously stated that reserved words or keywords may not be used as identifiers. As a result, it is
critical to remember the list of keywords so that you do not accidentally use them as identifiers. As
C++ keywords, keep the following list in mind:
• asm: To declare that a block of code is to be passed to the assembler.
• auto: A storage class specifier that is used to define objects in a block.
• break: Terminates a switch statement or a loop.
• case: Used specifically within a switch statement to specify a match for the
statement’s expression.
• catch: Specifies actions taken when an exception occurs.
• char: Fundamental data type that defines character objects.
• class: To declare a user-defined type that encapsulates data members and operations
or member functions.
• const: To define objects whose value will not alter throughout the lifetime of program
execution.
• continue:- Transfers control to the start of a loop.
• default:- Handles expression values in a switch statement that are not handled by
case.
• delete: Memory deallocation operator.
• do: indicate the start of a do-while statement in which the sub-statement is executed
repeatedly until the value of the expression is logical-false.
• double: Fundamental data type used to define a floating-point number.
• else: Used specifically in an if-else statement.
• enum: To declare a user-defined enumeration data type.
• extern: An identifier specified as an extern has an external linkage to the block.
• float:- Fundamental data type used to define a floating-point number.
• for: Indicates the start of a statement to achieve repetitive control.
• friend: A class or operation whose implementation can access the private data
members of a class.
• goto: Transfer control to a specified label.
• if: Indicate the start of an if statement to achieve selective control.
• inline: A function specifier that indicates to the compiler that inline substitution of
the function body is to be preferred to the usual function call implementation.
• int: Fundamental data type used to define integer objects.
• long: A data type modifier that defines a 32-bit int or an extended double.
• new: Memory allocation operator.
• operator: Overloads a c++ operator with a new declaration.
• private: Declares class members which are not visible outside the class.
• protected: Declares class members which are private except to derived classes

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
12

• public: Declares class members who are visible outside the class.
• register: A storage class specifier that is an auto specifier, but which also indicates to
the compiler that an object will be frequently used and should therefore be kept in a
register.
• return: Returns an object to a function’s caller.
• short: A data type modifier that defines a 16-bit int number.
• signed: A data type modifier that indicates an object’s sign is to be stored in the high-
order bit.
• sizeof: Returns the size of an object in bytes.
• static: The lifetime of an object-defined static exists throughout the lifetime of
program execution.
• struct: To declare new types that encapsulate both data and member functions.
• switch: This keyword is used in the “Switch statement”.
• template: parameterized or generic type.
• this: A class pointer points to an object or instance of the class.
• throw: Generate an exception.
• try: Indicates the start of a block of exception handlers.
• typedef: Synonym for another integral or user-defined type.
• union: Similar to a structure, struct, in that it can hold different types of data, but a
union can hold only one of its members at a given time.
• unsigned: A data type modifier that indicates the high-order bit is to be used for an
object.
• virtual: A function specifier that declares a member function of a class that will be
redefined by a derived class.
• void: Absent of a type or function parameter list.
• volatile: Define an object which may vary in value in a way that is undetectable to the
compiler.
• while: Start of a while statement and end of a do-while statement.

C++ Character Set


In this article, you will gain a basic understanding of the topic "character set in C++," along with an
illustration of its use. Therefore, let's not waste any more time and get right down to its concise
introduction.

Introduction to character sets


A character set is a collection of typographically correct symbols that are usable within a specific
language. A letter, a digit, or any other sign can be represented by something called a character.
C++ has the following character set:
• Letters: A-Z, a-z
• Digits: 0-9
• Special symbols: +, *, /, ^, \, (,), [,], {,}, =, !=, <, >, ', ", $, ;, :, %, !, &, _, #, <=, >=, @
• White spaces: blank space, horizontal tab, carriage return, newline, form feed

Above are the list of character set, which are used most of the time, specially the first two which are
"letters" and "digits". However, C++ can process any of the 256 ASCII characters as data or as
literals.
Note that the term "literals" refers to the character or group of characters (word) that is used to
describe the value that is used in the program.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
13

C++ Character Set Example


The following C++ program will provide you with an example of how character sets can be used in
the C++ programming language:
#include<iostream>
using namespace std;
int main()
{
char letter, digit, special;
cout<<"Enter a letter: ";
cin>>letter;
cout<<"You entered a letter: "<<letter<<endl;
cout<<"\nEnter a digit: ";
cin>>digit;
cout<<"You entered a digit: "<<digit<<endl;
cout<<"\nEnter a special character: ";
cin>>special;
cout<<"You entered a special character: "<<special<<endl;
return 0;
}

C++ Input and Output Operators


In this article, you will learn about the two most commonly used operators in C++, the input (>>)
and the output (<<) operators. These two operators are used every time we need to receive input
from the user and output the data to the output console. So without any further delay, let's start.
Input coming from the user's terminal, referred to as "standard input," is tied to the predefined
iostream cin, and output directed to the user's terminal, referred to as "standard output," is tied to the
predefined iostream cout.

C++ Output Operator


The output operator ("<<") ("put to"), also called the stream insertion operator, is used to direct a
value to standard output.
C++ Output Operator Example
The following C++ program is an example demonstrating the output operator.
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello and thank you for visiting codescracker\n";
return 0;
}

C++ Input Operator

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
14

The input operator (">>") ("get from"), also known as the stream extraction operator, is used to read
a value from standard input.
C++ Input Operator Example
Following is an example program in C++ that uses the C++ input operator, which is ">>.".
#include<iostream>
using namespace std;
int main()
{
int num;
cin>>num;
return 0;
}
If you execute the above C++ program, you will get nothing in the output. The only thing you need
to do with the output console is enter a number, say "23," and hit the "ENTER" key to see the
following output:

C++ Variables
Variables, one of the most important concepts in the C++ programming language, will be introduced
and investigated in this article. So, without further ado, here is a list of topics that are all related to
the "variables" discussed in this article.
• Introduction to variables
• Declaration of a Variable
• Initialization of a variable
• Dynamic initialization of a variable
• Variable scope
• Storage classes

Introduction to C++ variables


Variables are storage locations with names that can be changed while the program is running. For
example, to store a student's name and grades during a program run, we need two storage locations
with different names so that they can be easily distinguished.
Variables, called "symbolic variables," serve the purpose. The variables are called symbolic
variables because these are named locations. For instance, the following statement declares a
variable i of the data type int:
int i;

Declaration of a Variable in C++


Here is the general form to declare a variable in C++:
type variableName;
Here, type is any valid C++ data type, and variableName is the variable's name. An identifier is a
variable name. As a result, when declaring the name of a variable, all of the rules of identifier naming
apply. The following declaration declares an int variable age:
int age;
Consider the following program as an example.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
15

#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"How old are you? ";
cin>>age;
cout<<"\nYou're "<<age<<" years old.";
cout<<endl;
return 0;
}

Exercise 4:
Write a program C++ to check your age | remember to apply escape sequences:
Initialization of a variable in C++
Declaring a variable without a value can be called an "uninitialized variable," and the variable's value
is said to be "undefined." A first value (initial value) may be specified in the definition of a variable.
A variable with a declared first value is said to be an initialized variable.
The following is the general syntax for assigning values to variables in C++.
type variableName = value;
Here is a code fragment showing the variable initialization in C++.
int val = 100;
Let's take an example program demonstrating C++ variable initialization.
#include<iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
cout<<"The value of 'a' = "<<a;
cout<<endl;
cout<<"The value of 'b' = "<<b;
cout<<endl;
return 0;
}
The output produced by the above C++ program should exactly be:
The value of 'a' = 10
The value of 'b' = 20

However, instead of initializing a variable's value when it is declared, you can do so later in the
program. For example:
int val;
val = 20;
Let me create another example for your understanding. So the following program is created after
modifying the previous program.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
16

#include<iostream>
using namespace std;
int main()
{
int a, b, sum;
a = 10, b = 20;
cout<<"The value of 'a' = "<<a;
cout<<"\nThe value of 'b' = "<<b;
sum = a+b;
cout<<"\n\nThe sum of 'a' and 'b' is "<<sum;
cout<<endl;
return 0;
}
The following is the output:
The value of 'a' = 10
The value of 'b' = 20
The sum of 'a' and 'b' is 30

Dynamic initialization of a variable in C++


The ability to initialize variables at runtime is another feature of C++. This is known as "dynamic
initialization." Variables can be initialized at run time by using expressions in their declaration. For
example, consider the following variable declaration:
float avg;
avg = sum/tot;
You can also combine the above two statements into one, like this:
float avg = sum/tot;
It will initialize "avg" using the information available at run time, i.e., using the values of "sum" and
"tot" at run time. Here is an example program demonstrating dynamic initialization in C++.
#include<iostream>
using namespace std;
int main()
{
float mark, sum = 0, tot = 5, avg;
cout<<"Enter marks obtained in 5 subjects: ";
for(int i=0; i<5; i++)
{
cin>>mark;
sum = sum+mark;
}
avg = sum/tot;
cout<<"\nAverage Mark = "<<avg;
cout<<endl;
return 0;
}
The following snapshot shows the sample run of the above C++ program:

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
17

In the preceding example, the variable "avg" was dynamically assigned at program runtime, whereas
the variable "sum" was dynamically changed during program runtime.
Important: Variables that haven't been initialized aren't empty. If you do not initialize your
variables, they will contain junk (or garbage) values left over from the program that last used the
memory location they now occupy until the program places a value there.

C++ Variable Scope


Variable scope represents the scope of a variable, that is, where it can be used in a C++ program.
Basically, there can be two scopes for a variable in a C++ program, which are:
• Local variables in C++
• Global variables in C++

C++ Local Variables


Local variables are those variables that are declared inside a function or block. Here is an example
of local variables in C++, demonstrating the variable scope in C++:
#include<iostream>
using namespace std;
int main()
{
while(true)
{
int num;
cout<<"Enter a number less than 10: ";
cin>>num;
if(num < 10)
break;
}
cout<<endl;
return 0;
}
The above program continues receiving inputs until the user provides a number less than 10. But this
is not the point; the point is, the variable "num" declared inside the "while" block is known only to
that block. Therefore, if we try to access this variable outside the "while" block, then it will be
unknown or undefined. So the variable "num" can be called a local variable.

C++ Global Variables


Global variables are variables that exist outside of all functions and blocks. For example:
#include<iostream>
using namespace std;
int num;
int main()
{
while(true)
{
cout<<"Enter a number less than 10: ";

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
18

cin>>num;
if(num < 10)
break;
}
cout<<"\nThe latest value of 'num' = "<<num;
cout<<endl;
return 0;
}
The sample run of the above C++ program with some sample inputs, say: 12, 32, 45, 676, and 3,
should exactly be:
Enter a number less than 10: 12
Enter a number less than 10: 32
Enter a number less than 10: 45
Enter a number less than 10: 676
Enter a number less than 10: 3
The latest value of 'num' = 3
In the above example, the variable "num," which is defined above the "main()" method, outside all
the functions and blocks, is called a global variable.

C++ Data Types with Examples


The data are the values used in the program. Data can be of many types, for example, character,
integer, real, string, etc. Anything enclosed in single quotes represents character data in C++.
Numbers without fractions represent integer data. Numbers with fractions represent real data, and
anything enclosed in double quotes represents a string.
So, C++, like any other language, provides ways and facilities to handle different types of data by
providing data types.
Data types are used to identify the type of data and the operations that go with it. C++ data types are
of the following two types:
1. Fundamental Types
2. Derived Types
Now, in brief, let's go over the details of the above two data type categories in C++. But, before we
get into the details of the two data type categories mentioned above, here is a list of other topics that
fall under the category of "data types" and are also covered in this article. This list is provided for
your convenience so that you can navigate it at your leisure. Otherwise, you will learn about each
"data type" topic in this article one by one.
• C++ Data Types Size and Range
• Data Type Assignment Rules in C++

C++ Fundamental Data Types


Fundamental data types are those that are not composed of other data types. There are the following
five fundamental data types:
1. int
2. char
3. float

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
19

4. double
5. bool
6. void
Please note: The "int" data type represents integers, the "char" data type represents characters, the
"float" data type represents floating-point numbers, the "double" data type represents double
precision floating-point numbers, the "bool" data type refers to boolean type values (true or false),
and the "void" data type represents an empty set of values.

int type in C++


Integers are whole numbers such as 4, 56, -234, 0, etc. They have no fractional parts. Integers are
represented in C++ by the int data type.
An identifier declared as an "int" cannot have a fractional part. Let's take an example program.
#include<iostream>
using namespace std;
int main()
{
int a, b, res;
cout<<"Enter the two numbers: ";
cin>>a>>b;
res = a+b;
cout<<"\nSum = "<<res;
cout<<endl;
return 0;
}
Here is a sample run of the above C++ program:

Now supply the input, say 210 or any number, and hit the "ENTER" key, and then 40 and hit the
"ENTER" key again to see the following output:

As already stated, an "int" type value cannot have a fractional part. For example:
#include<iostream>
using namespace std;
int main()
{
int num;

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
20

cout<<"Enter a number: ";


cin>>num;
cout<<"\nYou entered: "<<num;
cout<<endl;
return 0;
}
The following snapshot shows the sample run of the above C++ example with user input "123.658."

The fractional part will be removed automatically if you try to initialize a number with a fractional
part to a variable of the "int" type. You need to use the "float" type in that case.

Char type in C++


Characters can store any member of the C++ implementation's basic character set. If a character
from this set is stored in a character variable, its value is equivalent to the integer code of that
character. An identifier declared as "char" becomes a character variable.
#include<iostream>
using namespace std;
int main()
{
char myChar;
cout<<"Enter a character: ";
cin>>myChar;
cout<<"\nYou entered: "<<myChar;
cout<<endl;

return 0;
}

The sample run of the above C++ example should be:


Enter a character: c
You entered: c

float type in C++


A floating-point number is any number that contains a fractional component. A number in floating-
point format might look something like 3.14159. A floating-point number, as opposed to an integer
number, can be identified by the presence of the decimal point.

int vs. float in C++


In comparison to integers, floating-point numbers have two advantages. For starters, they can
represent values between integers. Second, they are capable of representing a much broader range

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
21

of values. However, floating-point numbers have one disadvantage as well. In general, floating-point
operations are slower than integer operations.

double type in C++


In addition, the handling of floating-point numbers can be done with the data type double. However,
it is still considered to be a separate data type due to the fact that it requires twice as much memory
as the float type and can store floating-point numbers with a significantly greater range and precision
(significant numbers after the decimal point).
It is used in situations where the precision offered by type float is insufficient.

bool type in C++


The "bool" type in C++ is used when we need to store the following two values:
• true
• false
Please note: Don't use any type of quote while initializing a value (true or false) to a "bool" type
variable. For example:
bool x = true;
The term "true" refers to "1," whereas "false" refers to "0." For example:
#include<iostream>
using namespace std;
int main()
{
bool x = true, y = false;
cout<<x<<endl;
cout<<y<<endl;
return 0;
}

void type in C++


The void type specifies an empty set of values. It is used as the return type for functions that do not
return a value. No object of type "void" may be declared.
The "void" is essentially a keyword that can be used in place of a data type to represent the absence
of data wherever you would normally put that data type. As an illustration, the statement:
void codescracker();
indicates that the function "codescracker()" does not return any value.

C++ Data Types Size and Range


The size and range of these data types vary with each processor type and with the implementation
of the C++ compiler. Most of the time, a character takes up one byte and an integer takes up two
bytes, but you can't assume this if you want your programs to work on as many computers as
possible.
Data Type Storage Size (in Bytes) Range
char 1 -127 to 127
unsigned char 1 0 to 255
signed char 1 -127 to 127
int 2 or 4 -32,767 to 32,767

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
22

unsigned int 2 or 4 0 to 65,535


signed int 2 or 4 -32,767 to 32,767
short int 2 -32,767 to 32,767
unsigned short int 2 0 to 65,535
signed short int 2 -32,767 to 32,767
long int 4 -2,147,483,647 to 2,147,483,647
signed long int 4 -2,147,483,647 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
float 4 1E-37 to 1E+37 (six digits of precision)
double 8 1E-37 to 1E+37 (ten digits of precision)
long double 10 1E-37 to 1E+37 (ten digits of precision)
bool 1 true or false
void 0 empty

A byte is made up of 8 bits, with a bit being the smallest unit of memory. 1 bit can represent two
distinct binary number combinations (0 and 1), i.e., 21, 2 bits can represent four distinct binary
number combinations (00, 01, 10, 11,) i.e., 22, and so on. As a result, a single byte (8 bits) can
represent 28 = 256 different combinations. A two-byte unit, for example, can represent 65536 (216)
different values.
To determine the actual size of a variable on your platform, use the "sizeof()" method. As an
example:
#include<iostream>
using namespace std;
int main()
{
cout<<"\"int\" = "<<sizeof(int);
cout<<"\n\"unsigned int\" = "<<sizeof(unsigned int);
cout<<"\n\"signed int\" = "<<sizeof(signed int);
cout<<endl;

return 0;
}
My system has a 64-bit architecture, and the following is the output of the above C++ example on
my platform, using the "Code::Blocks" IDE:

Please note: The \n is used to insert a line break on the output console, whereas \" is used to output
a double quote.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
23

Data Type Assignment Rules in C++


The following guidelines should be followed when assigning data types:
• When you are certain that a variable contains only integers, i.e., no decimal points, you
should assign it the short, int, or long data type. Choose the "long" format when the integers
to be processed are large.
• When it is necessary to work with fractional numbers, also known as numbers that contain
decimals, assign the float or double data type. The "double" data type should be used
whenever possible because it eliminates the possibility of rounding-off errors.
• If the variable will always contain one character of data, assign it the char data type. This
indicates that there is only one letter (or character).

C++ Derived Data Types


Using the declaration operators, you can take the basic data types and turn them into other types.
Here are some of the most important data types derived from C++ fundamental types.
• Array
• Function
• Pointer
• Reference
Some other derived types are: class, structure, union, enum, and typedef. These are also called "user-
defined types." You will learn all about these derived types in the coming articles or tutorials.

C++ Formatting Output


This article will teach you how to format the output console. In other words, this article discusses
information that can be used to design the output console so that the user can easily read the data.
And, on occasion, we must format the output in order to lay out the data in a way that meets the
requirements. So without any further delay, let's start.
Formatting output in C++ is important in the development of the output screen, which can be easily
read and understood. C++ offers the programmer several input/output manipulators. Two of these
widely used I/O manipulators are:
• setw()
• setprecision()
In order to use these manipulators, you must include the header file named iomanip. Here is an
example showing how to include this header file in your C++ program.
#include<iomanip>

The setw() manipulator in C++


In C++, the setw() manipulator sets the width of the field assigned for the output. It takes the size of
the field (in number of characters) as a parameter. Here is an example of this code fragment:
cout<<setw(6)<<"C";
generates the following output on the screen (each underscore represents a blank space).
_ _ _ _ _C

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
24

The setw() manipulator does not stick from one cout statement to the next. For example, if you want
to right-justify three numbers within an 8-space field, you will need to repeat setw() for each value,
as shown below:
cout<<setw(8)<<22<<"\n";
cout<<setw(8)<<4444<<"\n";
cout<<setw(8)<<666666<<endl;
The output will be (each underscore represents a blank space):
______22
____4444
__666666
Note: The endl and "\n" are both used to break the line.

Example of formatting output using setw() in C++


Here is an example program demonstrating how to format the output screen using "setw()" in C++.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int i, num;
cout<<"Enter a number: ";
cin>>num;
cout<<"\nThe multiplication table of "<<num<<" is:\n";
for(i=1; i<=10; i++)
cout<<num<<setw(3)<<"*"<<setw(4)<<i<<setw(4)<<"="<<setw(4)<<num*i<<"\n";
return 0;
}
The following snapshot shows the initial output produced by the above C++ example program
demonstrating the "setw()" method.
Now supply the input as a number, say 8, to produce the following output:

See how well-organized the output becomes after formatting it. However, if we remove all the
"setw()" methods from the above example, that is, replace the last "cout" statement with the
following:

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
25

cout<<num<<"*"<<i<<"="<<num*i<<"\n";
then the output should look like this:
Enter a number: 8

The multiplication table of 8 is:


8*1=8
8*2=16
8*3=24
8*4=32
8*5=40
8*6=48
8*7=56
8*8=64
8*9=72
8*10=80
Here is another type of C++ program, also demonstrating output formatting in C++.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int i;
long int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"\nMultiplying (by 5) and printing the result ten times in three columns:\n";
for(i=0; i<10; i++)
{
cout<<num<<setw(25)<<num<<setw(25)<<num<<"\n";
num = num * 5;
}
return 0;
}
The following snapshot shows the sample run of this C++ program with the same user input as the
previous program's sample run.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
26

C++ Operators (Operators List and Examples)


In C++, operators are used in a program to perform specific tasks or operations on data. Therefore,
this article was created and published to describe the types of operators available in C++. So without
any further delay, let's start.

C++ Operator Types


C++ supports the following operator types:
• Arithmetic operators
• Relational operators
• Logical operators
• Increment-decrement operators
• Conditional operators
• Bitwise operators

C++ Arithmetic Operators


The arithmetic operators are required when performing an arithmetic task in a program. The two
types of arithmetic operators are as follows:
• Unary operators work on a single operand. For example: +a
• Binary operators operate on double operands. For example: a+b

C++ Unary Operators


Unary operators are operators that only act on one operand. There are two kinds of unary operators:
• Unary plus operator
• Unary minus operator

Unary plus operator


The unary operator "+" comes before an operand. The unary + operator's operand (the value on
which the operator operates) must be of an arithmetic or pointer type, and the result is the argument's
value. In C++, here's an example of the unary plus operator in action.
if a = 5, then +a means 5
if a = 0, then +a means 0
if a = -5, then +a means -5

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
27

Unary minus operator


The unary operator "-" comes before an operand. The unary operator's operand must be of an
arithmetic type, and the result is the inverse of its operand's value. The sign of the operand's value is
reversed by this operator. Here's an example of how to use the unary minus operator in C++.
if a = 5, then -a means -5
if a = 0, then -a means 0 (there is no quantity known as -0)
if a = -5, then -a means 5

C++ Binary Operators


"Binary operators" are operators that operate on two operands. A binary's operand is classified as
either left or right. An expression is made up of the operator and its operand. The binary operators
in C++ are classified as follows.
• Addition operator
• Subtraction operator
• Multiplication operator
• Division operator
• Modulus operator

Addition operator
The arithmetic binary operator + adds the values of its two operands, yielding the sum of their values.
Here's an example of how to use the addition operator in C++.
4 + 10 results in 14
a + 5(a=2) results in 7
a + b(a=4, b=6) results in 10

Subtraction operator
The - operator takes the second operand and subtracts it from the first. Here's an example of how to
use the subtraction operator in C++.
14 - 3 evaluates to 11
a - b(a=7, b=5) evaluates to 2

Multiplication operator
The x operator multiplies the operand values. Here's an example of how to use the multiplication
operator in C++.
3 × 4 evaluates to 12
b × 4(b=6) evaluates to 24
a × c(a=3, c=5) evaluates to 15

Division operator
The / operator divides the first and second operands. Here's an example of how to use the division
operator in C++.
100/5 evaluates to 20
a/2(a=16) evaluates to 8
a/b(a=159, b=3) evaluates to 5.3

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
28

Modulus operator
The % operator calculates the modulus of its first operand in relation to its second. That is, it yields
the remainder of dividing the first operand by the second. Here's an example of how to use the
modulus operator in C++.
19%6 evaluates to 1
Because 6 enters 19 three times with a remainder of one. As a result, the preceding statement
evaluates to 1.

C++ Assignment Operator and Statement


This post was written and published to describe one of the most important operators in C++, the
assignment operator (=). Another subject covered in this post is assignment statement. So, without
further ado, let's get started with the assignment operator.

C++ Assignment Operator


Basically, the assignment operator is used to assign the value of one variable to another. Or assign a
value to a variable. Here is the general form to assign a variable's value or value to a variable:
a = b;
x = 10;
In the above statements, the value of b is assigned to a, and the value 10 is assigned to x. Here is an
example.
#include<iostream>
using namespace std;
int main()
{
int a, b=10, x;
a = b;
x = 10;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"x = "<<x<<endl;
return 0;
}
Here is the sample output of the above C++ program:
a = 10
b = 10
x = 10
C++ Assignment Statement
As you know, an expression is composed of one or more operations. An expression terminated by a
semicolon becomes a statement. Statements from the smallest executable unit within a C++ program
Statements are terminated with a semicolon.
An assignment statement assigns a value to a variable. The value assigned may be constant, variable,
or an expression. The general form of an assignment statement is as follows:
a = cve;

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
29

where a is a variable to whom the value is being assigned, and cve can either be a constant, a
variable, or an expression. Following are some examples of assignment statements:
x = 16;
y = 3.6;
z = x + y;
z = z × x;
a = b + c - d;
I already mentioned that the symbol "=" is known as the assignment operator. The assignment
operator can be used serially, which is a common feature of C++.
The assignment operator = returns the value of the assignment as well as actually assigning the value
to the left-hand operand. Because of that, assignments can be chained together. This can be useful
when assigning the same value to a number of items. For example,
x = y = z = 13
This statement assigns the value 13 to x, y, and z. All the variables in this multiple assignment
statement must be declared before. Such a statement works from right to left. First, 13 is assigned to
z, then the value of z, which is now 13, is assigned to y, and y's value of 13 is assigned to x.

C++ if, if...else, and if...else if...else statements


The following selection statements offered by the "C++ language" allow you to select the set of
instructions to carry out based on the truth value or condition of an expression. This article was
written and published to cover these selection statements.
• if
• if...else
• if...else if...else
• switch
The "switch" will be covered in a separate post after the first three are covered in this one.
C++ if statement
An "if" statement evaluates a specific condition; if the condition is true, action is taken; otherwise,
action is not taken. Action can be thought of as a statement or set of statements. The if statement's
syntax, or general form, is as follows:
if(expression)
{
statement(s);
}
Here, a statement may be a single statement, a block of statements, or nothing (in the case of an
empty statement). The expression must be enclosed in parentheses. If the expression evaluates to
true, i.e., a nonzero value, the statement is executed; otherwise, it is ignored.

C++ if statement example program


The following example program can be considered an example program for the "if" statement in
C++.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
30

#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter the value of 'a': ";
cin>>a;
cout<<"Enter the value of 'b': ";
cin>>b;
if(a>b)
cout<<"\nThe value of 'a' is greater than the value of 'b'";
cout<<endl;
return 0;
}

Now supply the value of "a," say 20, and hit the ENTER key. Type another number, say 10 as the
value of "b," and hit the ENTER key to execute the "if" statement. Based on the same input as I told
you right now, here is the sample run:

The above program is missing one feature: we will not receive any output if the value of "a" is less
than "b." So now is the time to employ the "if...else" statement.

C++ if-else Statement


The "if-else" statement is similar to that of the "if" statement in C++, except that, in this case, we
will have another block, which is called the "else" block, whose given set of statements will be
executed if the specified if's condition evaluates to false. Following is the general form of the "if-
else" statement in C++:
if(expression)
{
// set of statements to execute
// if the "expression" evaluates to true
}
else
{
// set of statements to execute
// if the "expression" evaluates to false
}

C++ if-else statement example program


To create an example program for the "if-else" statement, I just modified the example program given
in the "if" statement's example. So here is the modified version of the previous program.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
31

#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter the value of 'a': ";
cin>>a;
cout<<"Enter the value of 'b': ";
cin>>b;
if(a>b)
cout<<"\nThe value of 'a' is greater than the value of 'b'";
else
cout<<"\nThe value of 'a' is less than the value of 'b'";
cout<<endl;
return 0;
}
The sample run with user inputs of 10 and 20 as the values of "a" and "b" should exactly be:
Enter the value of 'a': 10
Enter the value of 'b': 20
The value of 'a' is less than the value of 'b'

C++ if-else if-else Statement


The "if...else if...else" or "if-else if-else" statement is used when we need to execute the required
block of code based on multiple conditions. That is, when we need to test multiple conditions and
want to execute a single block of code, then we need an "if-else" statement. The following is the
general form:
if(expression1)
{
// block of code to execute
// if the "expression1" evaluates to true
}
else if(expression2)
{
// block of code to execute
// if the "expression2" evaluates to true
}
else if(expression3)
{
// block of code to execute
// if the "expression3" evaluates to true
}
else if(expressionN)
{
// block of code to execute

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
32

// if the "expressionN" evaluates to true


}
else
{
// block of code to execute
// if all expression's condition evaluates to false
}
Starting with "expression1," the condition of each expression will be evaluated. If any expression
evaluates to true, then its block of code will be executed, and all the remaining expressions in the
"else if" statement, including the "else," will be skipped. For example:
#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter the value of 'a': ";
cin>>a;
cout<<"Enter the value of 'b': ";
cin>>b;
if(a>b)
cout<<"\nThe value of 'a' is greater than the value of 'b'";
else if(a<b)
cout<<"\nThe value of 'a' is less than the value of 'b'";
else
cout<<"\nBoth values are equal";
cout<<endl;
return 0;
}
Following is the sample run of the above program with user inputs of 10 and 10 as the values of "a"
and "b":
Enter the value of 'a': 10
Enter the value of 'b': 10
Both values are equal

C++ switch statement


In our C++ program, we use the "switch" statement to implement menu-driven code or to test the
value of an expression against a list of integer or character constants.
The "switch" statement, which is also known as the "multiple-branch selection statement," is utilized
to repeatedly test the value of a specified expression against a list of given integer constants or
character constants. In the event that a match is discovered, the statements connected to the
respective constant will be carried out.
The syntax of the switch statement is as follows:
switch(expression)
{

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
33

case constant1:
// block of code to execute
// if "constant1" matched the "expression"
break;
case constant2:
// block of code to execute
// if "constant2" matched the "expression"
break;
case constant3:
// block of code to execute
// if "constant3" matched the "expression"
break;
case constantN:
// block of code to execute
// if "constantN" matched the "expression"
break;
default:
// block of code to execute
// if no match found
break;
}
After the expression is evaluated, the values that it returns are compared to the values of the constants
that are specified in the case statements. When a match is discovered, the block of code (set of
statements) associated with that case begins to be carried out. This continues until either
the break statement or the end of the switch statement is reached.
If a case statement does not include a break statement, the control will continue on to the next case
statement(s) until either a break statement is encountered or the end of the switch is reached. The
term "falling through" refers to the circumstance that occurs when there is no break in the case
statement. When there is no matching entry, the default statement is the one that is carried out.
The default statement is not required, and if it is not present, there will be no action taken if none of
the matches are successful.

C++ switch case example program


The following example program illustrates the "switch" case with multiple values. This program
prompts the user to enter a week number (1-7) before using the "switch" case to find and print the
equivalent name of the day of the week, such as Sunday, Monday, Tuesday,..., Saturday.
#include<iostream>
using namespace std;
int main()
{
int day;
cout<<"Enter the day number of the week: ";
cin>>day;
switch(day)
{

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
34

case 1:
cout<<"Sunday.";
break;
case 2:
cout<<"Monday.";
break;
case 3:
cout<<"Tuesday.";
break;
case 4:
cout<<"Wednesday.";
break;
case 5:
cout<<"Thursday.";
break;
case 6:
cout<<"Friday.";
break;
case 7:
cout<<"Saturday.";
break;
default:
cout<<"Invalid input!";
break;
}
cout<<endl;
return 0;
}
Now supply the input, say 6, and hit the ENTER key to see the following output:

C++ loops: for, while, and do-while loops with example


programs
This post was written and published on this website to explain one of the most important C++ topics:
"iteration statements." So, without further ado, let's get started.
The iteration statements allow a set of instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called loops or looping statements.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
35

Types of Loops in C++


C++ provides the following three kinds of loops:
• for
• while
• do-while
C++ loop constructs repeat a set of statements until the given condition evaluates to false. A true
condition in all three loop statements is any value that is not zero, and a false condition is any value
that is zero. Before we start describing these three types of C++ loops one by one, I think it will be
great if we discuss the parts of the loop.
Each and every loop has components that control and direct how it is carried out. In most cases, a
loop will consist of four components, each of which serves a distinct function. These are the parts
that make it up:
• Initialization Expression(s): A loop's control variable(s) must be initialized before it can be
entered. The control variable(s) are initialized using the initialization expression (s). The
initialization expression(s) assign the first value to the loop variables. The initialization
expression(s) are only executed once, at the start of the loop.
• Test Expression: The test expression is an expression whose truth value determines whether
or not the loop-body is executed. The loop body is executed if the test expression evaluates
to true, or 1. If the test expression returns false or zero, the loop is terminated. Before exiting
an entry-controlled loop, the test-expression is evaluated. The for and while loops in C++
are entry-controlled loops, while the do-while loop is an exit-controlled loop. Not to worry;
it is explained immediately following this section in this post.
• Update Expression(s): The update expression modifies the value(s) of the loop variable(s).
Following the execution of the loop-body, the update expression(s) are executed.
• Loop's Body: The body of the loop is made up of one or more statements that will be
executed until the test expression evaluates to true. Even if the test expression evaluates to
false in the case of a "do-while" loop, the body of the loop will be executed once on the first
run and then will terminate.
We use "expression(s)" instead of "expression" because the loop in C++ can have multiple
initialization and update expressions. The same can be said for loop variables.

C++ for loop


The for loop is the easiest to understand of the C++ loops. All of its loop-control elements are
gathered in one location, which is at the top of the loop, whereas in C++'s other loop construction,
the loop-control elements are dispersed throughout the program.
The general form of the "for" loop in C++ is as follows:
for(initialization expression(s); test-expression; update expression(s))
{
// body of the loop
}
For example,
for(int i=0; i<10; i++)
{
cout<<"codescracker.com"; }

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
36

indicates that the "for" loop continues the execution of its body, which is the statement,
cout<<"codescracker.com";
until the value of "i" becomes equal to 10. In other words, if the value of "i" becomes equal to 10,
then the condition "i<10" evaluates to false, which makes the loop terminate its execution. Therefore,
the above "for" loop code snippet prints the text "codescracker.com" on the output console 10 times.
C++ for example program
The C++ program can be considered an example program for the "for" loop in C++.
#include<iostream>
using namespace std;
int main()
{
int val, x;
cout<<"Enter a number: ";
cin>>val;

for(int i=1; i<=10; i++)


{
x = val*i;
cout<<val<<" * "<<i<<" = "<<x;
cout<<endl;
}
cout<<endl;
return 0;
}
Now type any number, say "3," and hit the ENTER key to produce the following output:

Now let me explain the above "for" loop section of the above example program:
• Initially, "val = 3" entered by the user.
• Now the execution of the "for" loop begins.
• Since I already told you that the initialization expression executed first and only once, the
value 1 was initialized to "i."

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
37

• I also told you that before entering the body of the loop, the test expression must be evaluated
to true, therefore the given test expression, "i<=10," will be evaluated.
• Since the test expression, which is "i<=10" or "1<=10," evaluates to true, program flow enters
the body of the "for" loop and executes all three written statements, which are "val*i" or
"3*1" or "3," which will be initialized to "x," and using the "cout," "val * i = x" or "3 * 1 =
3" (by putting the values of all three variables) will be printed on the output console.
• Now, after the execution of the loop's body, the update expression evaluates, and therefore
the value of "i" is incremented using "i++." So "i = 2" now.
• Again, before entering the body of the loop, the test expression must be evaluated as true.
• Because this time too, the test expression "i<=10" or "2<=10" evaluates to true, the program
flow again enters the body of the loop and again executes all three statements written in it
with the updated value of "i."
• So, the loop keeps running until the test expression is evaluated as false.

C++ while loop


When we need to execute a block of code or a set of statements multiple times, we use the "while"
loop. However, the "while" loop only accepts "test-expression" as a parameter. The other two are
that the "initialization expression(s)" must be done before starting the "while" loop, and the "update
expression(s)" must be written in the loop's body.
Following is the general form of the "while" loop in C++.
while(test-expression)
{
// body of the loop
}
For example,
int i=0;
while(i<10)
{
cout<<"codescracker.com";
i++;
}
prints the text "codescracker.com" 10 times on the output console. Except for the placement of the
"initialization expression(s)" and the "update expression(s)," everything remains the same as in the
"for" loop.

C++ while loop example program


The following program can be considered an example program for the "while" loop in C++.
#include<iostream>
using namespace std;
int main()
{
int val, i=1, x;
cout<<"Enter a number: ";
cin>>val;
while(i<=10)

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
38

{
x = val*i;
cout<<val<<" * "<<i<<" = "<<x<<endl;
i++;
}
cout<<endl;
return 0;
}
This program does the same job as the program given in the "for" loop section.

C++ do-while loop


The do-while loop, unlike the for and while loops, is a "exit-controlled" loop; that is, it evaluates its
"test-expression" after executing its loop-body statements, which means that if the test-expression
evaluates to false at first, the loop-body will be executed once before the loop is terminated.
Following is the general form of the "do-while" loop in C++.
do
{
// body of the loop
}while(test-expression);
For example,
int i=0;
do
{
cout<<"codescracker.com";
i++;
}while(i<10);
again prints the text "codescracker.com" 10 times on the output console.
C++ do-while loop example program
The following program can be considered an example program for the "do-while" loop in C++.
#include<iostream>
using namespace std;
int main()
{
int val, i=1, x;
cout<<"Enter a number: ";
cin>>val;
do
{
x = val*i;
cout<<val<<" * "<<i<<" = "<<x<<endl;
i++;
} while (i<=10);
cout<<endl;
return 0;
}

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
39

C++ Function Call


A function is called (or invoked, or executed) by providing the function name, followed by the
parameters enclosed in parentheses. For instance, to invoke a function whose prototype looks like
this:
float area(float, float);
The function call statement may look like the one below:
area(x, y);
where "x" and "y" have to be float variables. The syntax of the function call is very similar to that
of the declaration, except that the type specifiers are missing. Whenever a call statement is
encountered, the control (program control) is transferred to the function, the statements in the
function body are executed, and then the control returns to the statement following the function call.

C++ function calling example program


The following program uses function prototyping, function definition, and function calling. This
program prints the cube of a given number using a function. This program demonstrates function
calling in C++.
#include<iostream>
using namespace std;
float cube(float); // function prototype
int main()
{
float num, res;
cout<<"Enter a number to find its cube: ";
cin>>num;
res = cube(num); // function call
cout<<"\nThe cube of "<<num<<" is "<<res;
cout<<endl;
return 0;
}
float cube(float x) // function definition
{
float cb;
cb = x*x*x;
return cb;
}

Now type a number, say 5, and hit the ENTER key to find and print its cube, as shown in the snapshot
given below:

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
40

The above program first declares the function "cube" by providing its prototype. Then, after
accepting the number, it invokes the function "cube" and assigns the return value of it to the variable
"res." As soon as the function call statement is encountered, control gets transferred to the
function body, and all its statements are executed. With the execution of a return statement, control
returns to the statement immediately following the function call statement.

How to call a void function in C++


A function that does not expect any arguments is invoked by specifying empty parentheses. For
instance, if a function "message" does not expect any arguments, it will be invoked as:
message();
#include<iostream>
using namespace std;
void welcomeMsg(void);
int findFactorial(int);
int main()
{
welcomeMsg();
int num, fact;
cout<<"Enter a number: ";
cin>>num;
fact = findFactorial(num);
cout<<"\nFactorial of "<<num<<" = "<<fact;
cout<<endl;
return 0;
}
void welcomeMsg(void)
{
cout<<"----Welcome to the program----\n\n";
}
int findFactorial(int x)
{
int res = 1;
for(int i=x; i>=1; i--)
{
res = res*i;
}
return res;
}

C++ function calling: by value and by reference


A function can be invoked in two ways:
• call by value
• call by reference

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
41

C++ Call by Value


In the call by value method, the value of the actual parameters is copied into the formal parameters.
This means that the function creates its own copy of the argument values, which it then uses.
Please note: When using the call-by-value method, the changes you make will not be reflected back
to the values they were originally set to.
The primary advantage of using the call by value method is that it prevents you from modifying the
variables that are used to call the function. This is because any change that takes place within the
function will have an effect on the copy of the argument value that is used by the function. The
original copy of the value being argued for has been preserved in its entirety.

C++ function call by value example program


The method of function invocation known as "call by value" will be demonstrated in the following
piece of code. The actual parameters to a function call are the ones that are listed in the function call
statement. Formal parameters are those that are listed in the function definition itself.
#include<iostream>
using namespace std;
int change(int);
int main()
{
int orig;
cout<<"Enter a number: ";
cin>>orig;
cout<<"\nThe original value is: "<<orig;
cout<<"\nReturn value of the function change() is: "<<change(orig);
cout<<"\nThe value after the function change() is over: "<<orig;
cout<<endl;
return 0;
}
int change(int a)
{
a = 20;
return a;
}
In the preceding program, the value of the argument to change(), 6 (entered by the user), is copied
onto parameter "a," resulting in a value of 6. When the statement a = 20; takes place, the value of
"a" is changed but not the value of "orig." The "orig" still has a value of 6.
Please remember: It is a copy of the value of the argument that is passed into the function. The
variable used in the function call is not affected by what happens inside the function.
What are arrays in C++
Arrays can be thought of as a user-defined type, but in order to define them in a C++ program, we
have to use pre-defined data types like "int," "float," "char," etc.
In simple words if I define, then an array is a collection of values that can be stored in a single
variable, but all the values must be of the same type. For example:

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
42

int x[10];
the above statement, declares an array named "x" of the type "int" that can store up to 10 numbers
of the "int" type. Therefore, we can say that when we need to store multiple values in a single
variable, we use array.

In C++, declare an array


The general form of an array declaration in C++ is as follows:
dataType arrayName[numberOfElement];
where "dataType" refers to the type of element that should be stored in the array named "arrayName,"
and "numberOfElement" refers to the count. As an example:
char a[10];
declares a character-array with a size of 10, indicating that the array "a" can hold up to 10 characters.

How to initialize arrays in C++


In C++, the general form for initializing arrays is as follows:
type name[size] = {values};
The "type" denotes the "data type," the "name" denotes the "name of the array," the "size" denotes
the number of elements that the array can hold, and the "values" denotes the "comma-separated list
of values." As an example:
int arr[5] = {97, 69, 18, 46, 83};

Note: The number of values between the braces cannot be greater than the array size (here 5).
If you omit the array size, then the array becomes big enough to hold the initialization. Therefore, if
you write:
int arr[] = {97, 69, 18, 46, 83};
The above statement created exactly the same array as the previous one. So, you can also initialize
more or less than 5 values like this:
int arr[] = {10, 12, 23};
or
int arr[] = {12, 23, 34, 35, 45, 33, 10, 2, 54};

Assign values to an array at a specific position in C++


Here is the general form to assign a value to a specific position in an array:
array_name[index_number] = value;
Here is an example of assigning a value of 20 to the fifth index of the array named "arr":
arr[4] = 20;
Note: Since index always starts at 0, index number 4 corresponds to the 5th element in the array.
C++ arrays example program
Now is the time to look at a basic example of arrays in C++ to help clarify the concepts discussed
above. So I wrote a program that prompts the user to enter any five numbers and then prints the
entered five numbers back on the output console.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
43

#include<iostream>
using namespace std;
int main()
{
int arr[5];
cout<<"Enter any five numbers: ";
for(int i=0; i<5; i++)
{
cin>>arr[i];
}
cout<<"\nYou entered: ";
for(int i=0; i<5; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;
return 0;
}
Now type the first number, say 10, and hit the ENTER key; then type the second number, say 12,
and hit the ENTER key; and so on. Following is the sample output after providing the five numbers
one by one.

The dry run of the above program goes this way:

• Using the statement:


int arr[5];
An array named "arr" is declared that can hold up to 5 values of the "int" type. And using
the following first "for" loop, the program receives 5 inputs from the user and stores them
in the array "arr" in such a way that the first element will be stored in "arr[0]," the second
element will be stored in "arr[1]," and so on.
• And using the next "for" loop, I just printed all the elements of the array one by one.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
44

Now let me modify the above program to print all elements of the array along with their indexing.

#include<iostream>
using namespace std;
int main()
{
int arr[5];

cout<<"Enter any five numbers:\n";


for(int i=0; i<5; i++)
cin>>arr[i];

cout<<"\nThe array \"arr\" with their indexing is as follows:\n";


for(int i=0; i<5; i++)
cout<<"arr["<<i<<"] = "<<arr[i]<<endl;

cout<<endl;
return 0;
}
The following snapshots show the sample run of the above program with user inputs 1, 2, 3, 4, and
5 as the five elements of the array:

Calculate Array Size in C++


When the upper bound (UB) and lower bound (LB) of an array are given, then its size can be
calculated as follows:
Array_Size = (UB - LB) + 1
where UB denotes the upper bound and LB denotes the lower bound. For example, if an array has
elements numbered as follows:
-7, -6, -5, ....0, 1, 2, ....15
then its UB is 15 and LB is -7, and the array size can be calculated like this:
= 15 - (-7) + 1
= 15 + 7 + 1

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
45

= 23
Note: In C++, the lower bound is always 0 and the upper bound is size-1. (size specifies the number
of elements in the array.)
In C++, all arrays consist of contiguous memory locations. The lowest address corresponds to the
first element, and the highest address to the last element. Arrays are a way to group a number of
items into the largest possible unit. Arrays can have data items of simple types like int or float or
even of user-defined types like structures and objects.
Types of Arrays in C++
Following are the two types of C++ arrays:
• One-dimensional arrays
• Multi-dimensional arrays
The "one-dimensional" array is discussed in a separate (next) post, whereas the "multi-dimensional"
is going to be covered in this post, right after this paragraph.

C++ multi-dimensional arrays


A multi-dimensional array is defined as a 2-D (two-dimensional) or more than 2-D array. Each
element in a 2-D array can be considered an array (1-D array); in a 3-D array, each element can be
considered a 2-D array; and so on. A 2-D array can be thought of as a matrix. For example:
int mat[4][3];
The above statement declares a 2-D array of size "4x3," where "4" is the "row size" and "3" is the
"column size." It means that the array "mat" is able to store 12 elements, 3 elements in each column,
making a total of 4 rows. For example:
#include<iostream>
using namespace std;
int main()
{
int mat[4][3], i, j;
cout<<"Enter 12 elements for the array: ";
for(i=0; i<4; i++)
{
for(j=0; j<3; j++)
{
cin>>mat[i][j];
}
}
cout<<"\n\nThe given 2-D array should look like:\n";
for(i=0; i<4; i++)
{
for(j=0; j<3; j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<endl;
}
cout<<endl;
return 0;
}

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
46

Now type the first element, say 1, and hit the ENTER key. Then type the second element, say 2, and
hit the ENTER key again. In this way, provide 12 inputs as 12 array elements and hit the ENTER
key finally to produce the following output:

Create a structure in C++


To create a structure in C++, follow the following general form:
struct {
dataType variableName1;
dataType variableName2;
dataType variableName3;

dataType variableNameN;
} structureVariableName;

The keyword "struct" is used to declare a structure in C++, "dataType" is a valid C++ data type,
"variableName1," "variableName2," "variableName3," and "variableNameN" are the names
of variables that are also known as structure members, and "structureVariableName" is the name of
the structure variable that will be used to access the structure members in the program to initialize
and use them. As an example,
struct {
int sno;
long int empId;
string empName;
string empCity;
} codescracker;
The preceding C++ code fragment declares a structure with four members, namely "sno," "empId,"
"empName," and "empCity," of the types "int," "long int," "string," and "string," as well as a structure
variable called "codescracker."
We can have multiple structure variables as well, for example.
struct {
int sno;
long int empId;
string empName;
string empCity;
} a, b, c, d, e;
There is another way to create a structure in C++, which is by creating the structure along with its
name or tag. The following is the general form:
struct name {
type variable1;
type variable2;
type variable3;
} structureVariables;

Through this approach, we can also create structure variables later in the program. You will see an
example of this concept later in this post.

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
47

C++ structure example program


Now that I've defined how to declare, access, and initialize structure, it's time to create and explain
a complete example program demonstrating the structure. As a result, I wrote the following program
to serve as an example of the "C++ structure."

#include<iostream>
using namespace std;
struct {
int sno;
long int empId;
string empName;
string empCity;
} xyz;

int main()
{
xyz.sno = 1;
xyz.empId = 123904;
xyz.empName = "William";
xyz.empCity = "Houston";

cout<<"S.No. = "<<xyz.sno<<endl;
cout<<"ID = "<<xyz.empId<<endl;
cout<<"Name = "<<xyz.empName<<endl;
cout<<"City = "<<xyz.empCity<<endl;

return 0;
}
The output produced by this C++ program illustrating the structures should exactly be:

S.No. = 1
ID = 123904
Name = William
City = Houston

Now let me allow the user to define the values at program runtime. The following program not only
allows the user to enter the values; it also uses multiple structure variables.

#include<iostream>
using namespace std;
struct {
int sno;
long int empId;
string empName;
string empCity;
} a, b;
int main()
{

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
48

cout<<"----Enter the data for the first employee----\n";


cout<<"Enter the Serial Number: ";
cin>>a.sno;
cout<<"Enter the ID: ";
cin>>a.empId;
cout<<"Enter the Name: ";
cin>>a.empName;
cout<<"Enter the City: ";
cin>>a.empCity;

cout<<"\n\n----Enter the data for the second employee----\n";


cout<<"Enter the Serial Number: ";
cin>>b.sno;
cout<<"Enter the ID: ";
cin>>b.empId;
cout<<"Enter the Name: ";
cin>>b.empName;
cout<<"Enter the City: ";
cin>>b.empCity;

cout<<"\n\nData\t\tEmployee 1\t\tEmployee 2";


cout<<"\nS.No.\t\t"<<a.sno<<"\t\t\t"<<b.sno;
cout<<"\nID\t\t"<<a.empId<<"\t\t\t"<<b.empId;
cout<<"\nName\t\t"<<a.empName<<"\t\t\t"<<b.empName;
cout<<"\nCity\t\t"<<a.empCity<<"\t\t\t"<<b.empCity;

cout<<endl;
return 0;
}
Now, let's create the same program using the second method of declaring and defining the structure,
which is by using its name and declaring its variable later in the program; that is, I will declare the
structure variable using its name or tag inside the "main ()" method.

#include<iostream>
using namespace std;

struct myStructure {
int sno;
long int empId;
string empName;
string empCity;
};

int main()
{
myStructure a, b;

cout<<"----Enter the data for the first employee----\n";


cout<<"Enter the Serial Number: ";
cin>>a.sno;

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
49

cout<<"Enter the ID: ";


cin>>a.empId;
cout<<"Enter the Name: ";
cin>>a.empName;
cout<<"Enter the City: ";
cin>>a.empCity;
cout<<"\n\n----Enter the data for the second employee----\n";
cout<<"Enter the Serial Number: ";
cin>>b.sno;
cout<<"Enter the ID: ";
cin>>b.empId;
cout<<"Enter the Name: ";
cin>>b.empName;
cout<<"Enter the City: ";
cin>>b.empCity;

cout<<"\n\nData\t\tEmployee 1\t\tEmployee 2";


cout<<"\nS.No.\t\t"<<a.sno<<"\t\t\t"<<b.sno;
cout<<"\nID\t\t"<<a.empId<<"\t\t\t"<<b.empId;
cout<<"\nName\t\t"<<a.empName<<"\t\t\t"<<b.empName;
cout<<"\nCity\t\t"<<a.empCity<<"\t\t\t"<<b.empCity;

cout<<endl;
return 0;
}

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L
50

Take away Projects, supports and questions


Real world Projects in C++ to help you explore and Communities to help you when stuck.

Beginner level. Intermediate level.


- CGPA Calculator - Snake Game
- Rock Paper Scissor - Text Editor
- Casino Number Guessing Game - Tic-Tac-Toe
- Calculator for Scientific Operations - Minesweeper Game
- Login and Registration System - Phonebook Application
- Student Database Management System - OpenCV Project for Image Blur
- Inventory System - OpenCV to Play a Video
- Payroll System - OpenCV to Blur a Video
- Banking System - Music Player
- Medical Information System - Cryptography Application

Communities/Websites
Visit the following websites/communities for any helpful support in C++ and improve your career
to the professional level.
- https://www.geeksforgeeks.org/
- https://www.tutorialspoint.com/wordpress/index.html
- https://www.tutorialspoint.com/index.htm
- https://olympus.mygreatlearning.com
- https://www.w3schools.com/
- https://codescracker.com/
- https://www.javatpoint.com/

Quick Interview Questions.


1. Write a C++ Program to Check Whether a Number is a Positive or Negative Number.
2. Write a Program to Find the Greatest of the Three Numbers.
3. C++ Program to Check Whether Number is Even Or Odd
4. Write a Program to Check Whether a Character is a Vowel or Consonant
5. Write a Program to Print Check Whether a Character is an Alphabet or Not
6. Write a program to add, subtract, multiply and divide sum of two numbers
7. Write a Program to Find the Sum of the First N Natural Numbers
8. Write a Program to Calculate the Greatest Common Divisor of Two Numbers
9. Write a Program to Calculate the Lowest Common Multiple (LCM) of Two Numbers
10. Write a Program for Finding the Roots of a Quadratic Equation

MonTech #Heart of Experience | Vol. 1


Mr. James Batista A. L

You might also like