Chapter 3
Programming Constructs
C++ is a popular object oriented language. It is fast and efficient. C++ is derived from a
language called C. A C++ program is constructed using a mix of one or more functions and one
or more objects. In this course, we will learn about C++.
The best way to learn a programming language is by writing programs. Typically, the first
program beginners write is a program called "Hello World", which simply prints "Hello World"
to your computer screen. Although it is very simple, it contains all the fundamental components
C++ programs have:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
We will discuss the meaning of each line in the coming sections.
3.1 Process of compiling and running programs
You will be writing programs in C++. But a computer cannot directly run a C++ program. First,
the program needs to be translated to machine language, which is the language that the
computer's processor understands. A tool that does tha translation is called a compiler.
There are two kinds of machine language file.
An executable file is a complete program in machine language. You can run it in a
command simply by typing its name (or a path) as a command.
An object file is a partial machine language program. It is designed to be linked to other
object files to produce an executable file.
Machine language files are also called binaries since they use binary notation. They do not
contain text that you can read.
We use an IDE (Integrated development environment) to write, compile and run our C++
programs. There are various types of C++ IDEs. You can use any of these IDEs to write, compile
1
and run your C++ program in your desktop computer. Some IDEs that can be downloaded for
free include:
Intel C++ and many supporting tool
Microsoft Visual C++.
Oracle C++.
Quincy C++
Even, there are also Android Apps that help you write and run C++ programs in your smart
phones. Examples are
Cxxdroid - C++ compiler IDE for mobile development
CppDroid - C/C++ IDE
Mobile C [ C/C++ Compiler ]
You can download these apps and test the C++ codes in your smart phone.
Once you install the IDE, you can open the IDE (Integrated Development Environment), type the
C++ code, and compile it. If there is any error, correct it. After the code successfully compiled,
run it. Then you can enter input (if needed) and view the result.
3.2 Basic syntax and semantics of C++
A C++ program is constructed using a mix of one or more functions and one or more objects. Let
us start our programming with the traditional Hello World! program. Here is the classic
Helloworld program using C++ :
/* A Hello World program in C++ */
#include <iostream >
using namespace std;
int main()
{
cout << "Hello, world!\n";
return 0;
}
The output of the program is:
Hello, world!
The above program has one function called main and it uses an object called cout. Let us have a
detailed look at the meaning of each line.
2
Internal Details of the Helloworld program
First line of the program is comment, which in C++ starts with /* and are terminated with
*/. They can span multiple lines. Single line comment starts with //.
Second line is inclusion of a standard library which defines the procedures for
input/output. Header files contain the information necessary to use these libraries, such as
function declarations and macros. Most of C++’s functionality comes from
libraries. Don't forget to include this line to make your program run. Do not add space
between # and include.
Third line tells the compiler that it should look in the std namespace for any identifier we
haven’t defined. If we do this, we can omit the std:: prefix when writing cout as in
example presented just after this discussion. But, this is the recommended practice.
Forth line is the heading of function main. A function in C++ has two parts: heading and
body. The heading part has three sections: return type, function name and argument list.
Program execution starts from main function. It comes in two forms:
int main() or int main(void)
int main(int argc, char *argv[])
The first takes no arguments, and the second receives command-line arguments from the
environment in which the program was executed—typically a command-shell.
Line 5 and 8 represents the start and end of the program scope. The braces { and }
delineate the extent of the function block.
Line 6 and 7 are the statements of the program. Line 6 prints Hello, World! by calling the
standard library object cout, which prints a character string to standard output (usually the
screen). In this case, the cout object takes one argument (or input parameter): the
string constant "Hello World!\n". The \n at the end of the string is an escape character to
start a new line. Finally, the statement is terminated with a semicolon (;).
C++ is a free-form language with program meaning unaffected by whitespace in
most circumstances. Thus, statements are terminated by ; not by a new line.
When a function completes, the program returns to the calling function. In the case
of main(), the program terminates and control returns to the environment in which the
program was executed. The integer return value of main() indicates the program’s exit
3
status to the environment, with 0 meaning normal termination. Line 7 represents that
function main returns 0 which indicates the successful termination of the program.
Another important thing we should keep in mind is that everything in C++ is case
sensitive: someName is not the same as SomeName. Similarly, main() is not same as Main().
Here is another version of above program with same output.
// A Hello World program in C++
#include <iostream >
int main(){
std::cout << "Hello, world!\n";
return 0;
}
Here only the difference is std:: in front of cout. And, we’re telling the compiler to look
for cout in the std namespace, in which many standard C++ identifiers are defined.
Note
A mistake in a program is usually called a bug, and the process of eliminating bugs is
called debugging. The compiler will catch certain kinds of mistakes and will write out an
error message when it finds a mistake. It will detect what are called syntax errors,
because they are, by and large, violation of the syntax (that is, the grammar rules) of the
programming language, such as omitting a semicolon.
In C or C++, we face different kinds of errors. These errors can be categorized into five different
types. These are like below −
Syntax Error
Run-Time Error
Linker Error
Logical Error
Semantic Error
Let us see these errors one by one −
Syntax error
These kinds of errors are occurred, when it violates the rule of C++ writing techniques or
syntaxes. These kinds of errors are generally indicated by the compiler during compilation.
Sometimes these are known as compile time error.
4
Rumtime error
These kinds of errors are occurred, when the program is executing. As this is not compilation
error, so the compilation will be successfully done. One example for run time error is division by
0. If we have a program that performs division, and if the input for the denominator is 0, run time
error will happen.
Linker error
These kinds of errors are occurred, when the program is compiled successfully, and trying to link
the different object file with the main object file. When this error is occurred, the executable is
not generated, For example some wrong function prototyping, incorrect header file etc. If the
main() is written as Main(), this will generate linked error.
Logical error
Sometimes, we may not get the desired output. If the syntax and other things are correct, then
also, we may not get correct output due to some logical issues. These are called the logical error.
Sometimes, we put a semicolon after a loop, that is syntactically correct, but will create one
blank loop. In that case, it will show desired output.
Semantic error
This kind of error occurs when it is syntactically correct but has no meaning. This is like
grammatical mistakes. If some expression is given at the left side of assignment operator, this
may generate semantic error.
Note
Learning to code can be a frustrating endeavor because you are destined to encounter many red
errors along the way. What makes a programmer successful isn’t avoiding errors — no
programmer can avoid them. Great programmers understand that errors are part of the process,
and they know how to find the solution to each while learning something new from them.
3.3 Basic Elements of Programming
There are five basic elements of programming that are present in essentially all languages.
Variables: represent data. They can range from something very simple, such as the age of
a person, to something very complex, such as a record of university students holding their
names, ages, addresses, what courses they have taken, and the marks obtained.
Loops: allow us to carry out execution of a group of commands a certain number of
times.
5
Conditionals: specify execution of a group of statements depending on whether or not
some condition is satisfied.
Input/Output: This will allow interaction of the program with external entities. This might
be as simple as printing something out to the terminal screen, or capturing some text the
user types on the keyboard, or it can involve reading and/or writing to files.
Subroutines and functions: allow you to put frequently used snippets of code into one
location which can then be used over and over again.
3.3.1 Variables, data types, identifiers, keywords, constants, literals, comments, operators,
expressions and statements
Variables represent data. They have unique names and types. They hold values that are assigned
to them. The type of the variable determines the way the variable is stored in the computer
memory and the value it can contain. A variable must be declared before it is used. Syntax to
declare a variable is as shown below.
type varName;
A variable can be assigned a value at the time of declaration. This is called initialization.
int x = 100;
Multiple variables having the same type can be declared as follows
int a, b, c;
C++ is a typed language. That means, each variable is given a specific type which defines what
values it can represent, how its data is stored in memory, and what operations can be performed
on it. So, a type of a variable is a formal description of what kind of data its value is. For
instance,0 is an integer, 3.142 is a floating-point (decimal) number, and "Hello, world!\n" is a
string value (a sequence of characters). By forcing the programmer to explicitly define a type for
all variables and interfaces, the type system enables the compiler to catch type-mismatch errors,
thereby preventing a significant source of bugs.
Basic Data Types
Basic data types are basic types implemented directly by the language that represent the basic
storage units supported natively by most systems. They can mainly be classified into:
Character types: They can represent a single character, such as 'A' or '$'. The most basic
type is char, which is a one-byte character. The other is string. A string is a variable that
stores a sequence of letters or other characters, such as "Hello" or "May 10th is my
6
birthday!". Just like the other data types, to create a string we first declare it, then we can
store a value in it.
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.
The following table lists the data types and their storage sizes.
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
bool 1 byte Just true (1)or false (0).
Note: Nearly all current machines represent an int with at least 32-bits and many now use 64-
bits. The size of an int generally represents the natural word-size of a machine; the native size
with which the CPU handles instructions and data.
All C++ variables must be identified with unique names. These unique names are
called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).It is recommended to use descriptive names in order to create understandable
and maintainable code.
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits and underscores
7
Names must begin with a letter or an underscore (_)
Names are case sensitive (myVar and myvar are different variables)
Names cannot contain whitespaces or special characters like !, #, %, etc.
Reserved words (like C++ keywords, such as int) cannot be used as names. 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:
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
Constants and Literals
Constants refer to fixed values that the program may not alter. Constants can be of any of the
basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters,
Strings and Boolean Values. Again, constants are treated just like regular variables except that
their values cannot be modified after their definition.
In C/C++ program we can define constants in two ways as shown below:
Using #define preprocessor directive
Using a const keyword
The values assigned to each constant variable are referred to as the literals.
Syntax
#define identifierName value
-OR-
const identifierName = value;
Comments
Comments are a vital element of a program that is used to increase the readability of a program
and to describe its functioning. Comments are not executable statements and hence, do not
8
increase the size of a file. C++ supports two comment styles: single line comment and multiline
comment. Single line comments are used to define line-by-line descriptions. Double slash (//) is
used to represent single line comments. Anything after the double slash up to the end of the line
is a comment and will be ignored by the compiler. Multiline comments are used to write
comments that span more than one line. Multiline comments start with /* and end with */.
Anything between these two symbols will be ignored by the compiler.
Operators
Operator represents an action. For example + is an operator that represents addition. An operator
works on one or more operands and produces an output. Based on the number of operands,
operators can be grouped into
unary – has only one operand
binary – has two operands
tertiary – has three operands
Based on their operation, operators in C++ can be grouped into
1. Arithmetic Operators
2. Assignment Operators
9
3. Auto-increment and Auto-decrement Operators
4. Logical Operators
5. Comparison (relational) operators
6. Bitwise Operators
7. Ternary Operator
1) Arithmetic Operators
Arithmetic operators are: +, -, *, /, %
+ is for addition.
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0
2) Assignment Operators
Assignments operators in C++ are: =, +=, -=, *=, /=, %=
num2 = num1; would assign value of variable num1 to the variable num2.
num2+=num1; is equal to num2 = num2+num1
num2-=num1; is equal to num2 = num2-num1
num2*=num1; is equal to num2 = num2*num1
num2/=num1; is equal to num2 = num2/num1
num2%=num1; is equal to num2 = num2%num1
3) Auto-increment and Auto-decrement Operators
++ and - -
num++ is equivalent to num=num+1;
num–- is equivalent to num=num-1;
4) Logical Operators
Logical Operators are used with boolean variables. They are mainly used in conditional
statements and loops for evaluating a condition.
Logical operators in C++ are: &&, ||, and !
Let’s say we have two boolean variables b1 and b2.
b1 && b2 will return true if both b1 and b2 are true else it would return false.
10
b1 || b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and
it would return false if b1 is true.
5) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.
num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both
bits are equal, else it returns 0. In our case it would return: 2 which is 00000010 because
in the binary form of num1 and num2 only second last bits are matching.
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either
bit is 1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they
are not equal, else it returns 0. In our example it would return 29 which is equivalent to
00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our
example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to
00101100
Note: In the example below we are providing 2 at the right side of this shift operator that
is the reason bits are moving two places to the left side. We can change this number and
11
bits would be moved by the number of bits specified on the right side of the operator.
Same applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit,
and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to
00000010
7) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:
variable num1 = (expression) ? value if true : value if false
If the expression results true then the first value before the colon (:) is assigned to the
variable num1 else the second value is assigned to the num1.
Operator precedence chart
When two or more operators are found in a given expression, the evaluation will be determined
by their precedence and associativity similar to the rule in mathematics. The below table
describes the precedence order and associativity of operators in C / C++. Precedence of operator
decreases from top to bottom.
OPERATOR DESCRIPTION ASSOCIATIVITY
() Parentheses (function call) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++/– Postfix increment/decrement
++/– Prefix increment/decrement right-to-left
+/- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
12
sizeof Determine size in bytes on this implementation
*,/,% Multiplication/division/modulus left-to-right
+/- Addition/subtraction left-to-right
<< , >> Bitwise shift left, Bitwise shift right left-to-right
< , <= Relational less than/less than or equal to left-to-right
> , >= Relational greater than/greater than or equal to left-to-right
== , != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= , -= Addition/subtraction assignment
*= , /= Multiplication/division assignment
%= , &= Modulus/bitwise AND assignment
^= , |= Bitwise exclusive/inclusive OR assignment
<>= Bitwise shift left/right assignment
, expression separator left-to-right
Expression and Statement
C++ expression consists of operators, constants, and variables which are arranged according to
the rules of the language. It can also contain function calls which return values. An expression
can consist of one or more operands, zero or more operators to compute a value. Every
expression produces some value which is assigned to the variable with the help of an assignment
operator.
Examples of C++ expression:
13
(a+b) - c
(x/y) -z
4*a2 – 5*b +c
(a+b) * (x+y)
Any expression followed by a semicolon is a statement, e.g.:
x= y + z;
y= f(x + z) * 3.5;
A single semicolon is an empty statement.
3.4 Structure (Anatomy) of C++ program
C++ program structure is divided into various sections, namely, headers, class definition,
member functions definitions and main function.
Note that C++ provides the flexibility of writing a program with or without a class and its
member functions definitions. A simple C++ program (without a class) includes comments,
headers, namespace, main() and input/output statements as we have seen in section 3.2. In this
course, we will not cover C++ classes. Classes will be covered when you learn the course object
oriented programming.
For many years, C++ applied C-style headers, that is, .h extension in the headers. However, the
standard C++ library introduced new-style headers that include only header name. Hence, the
most modern compilers do not require any extension, though they support the older .h extension.
In older compilers we need to add the .h extension. Also old compilers do not support
namespace. Hence, we will not write the statement using namespace std; in old computers.
Some of C-style headers and their equivalent C++ style headers are listed in Table.
14
Since its creation, C++ has gone through many changes by the C++ Standards Committee. One
of the new features added to this language is namespace. A namespace permits grouping of
various entities like classes, objects, functions and various C++ tokens, etc., under a single name.
Different users can create separate namespaces and thus can use similar names of the entities.
This avoids compile-time error that may exist due to identical-name conflicts.
3.5 Input/output Statements
C++ comes with libraries which provide 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.
Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard)
to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device (display screen) then this process is called output.
Header files available in C++ for Input/Output operations are:
1. iostream: iostream stands for standard input-output stream. This header file contains
definitions to objects like cin, cout, cerr etc.
2. iomanip: iomanip stands for input output manipulators. The methods declared in this files
are used for manipulating streams. This file contains definitions of setw, setprecision etc.
3. fstream: This header file mainly describes the file stream. This header file is used to handle
the data being read from a file as input or data being written into the file as output.
The C++ cout statement is the instance of the ostream class. It is used to produce output on the
standard output device which is usually the display screen. The data needed to be displayed on
15
the screen is inserted in the standard output stream (cout) using the insertion operator(<<).C++
cin statement is the instance of the class istream and is used to read input from the standard input
device which is usually a keyboard. The extraction operator(>>) is used along with the
object cin for reading inputs. The extraction operator extracts the data from the object cin which
is entered using the keyboard.
The C++ cerr is the standard error stream which is used to output the errors. This is also an
instance of the iostream class. As cerr in C++ is un-buffered so it is used when one needs to
display the error message immediately. It does not have any buffer to store the error message and
display later.
Escape Sequences
The backslash, \, preceding a character tells the compiler that the character following the \ does
not have the same meaning as the character appearing by itself. Such a sequence is called an
escape sequence. The sequence is typed in as two characters with no space between the symbols.
Several escape sequences are defined in C++.
new line \n
horizontal tab \t
alert \a
backslash \\
double quote \"
If you wish to insert a blank line in the output, you can output the newline character \n by itself:
cout << "\n";
Another way to output a blank line is to use endl, which means essentially the same thing as "\n".
So you can also output a blank line as follows:
cout << endl;
Although "\n" and endl mean the same thing, they are used slightly differently; \n must always
be inside of quotes and endl should not be placed in quotes.
16
Examples
1. Write a C++ program that accepts two numbers from the user and calculates their sum.
The following code is the implementation written in Cxxdroid app.
2. Write a C++ program that accepts radius of a circle and calculates its circumference, area and
diameter. Formula is given below.
diameter = 2 * radius circumference = 2 * П * radius area = П * radius2
The following code is the implementation written in Cxxdroid app.
3. Write a C++ program that accepts name of a person and greets him/her by saying
Hello, Person Name
The following code is the implementation written in Cxxdroid app.
17
4. Write a C++ program that outputs the following tabular data.
A 10 IT
B 11 IS
C 12 ARCH
D 13 IS
The following code is the implementation written in Cxxdroid app.
18