Professional Documents
Culture Documents
Module - Unit-2 C++ Basics
Module - Unit-2 C++ Basics
UNIT
2 C++
BASICS
1. C++ fully supports object-oriented programming, including the four pillars of object-oriented
development.
LESSON 1:
An Overview of C++
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 2 hours
C++ fully supports object-oriented programming, which includes the four pillars of
object-oriented development: encapsulation, abstraction/data hiding, inheritance, and
polymorphism.
For example, once you send an email to someone, you click send, and you get
the success message. What happens when you click send, how data is
transmitted over the network to the recipient is hidden from you (because it is
irrelevant to you).
Standard Libraries
▪ The core language is giving all the building blocks, including variables, data
types, literals, etc.
▪ The C++ Standard Library is giving a rich set of functions operating files,
strings, etc.
▪ The Standard Template Library (STL) provides a rich set of methods for
operating data structures, etc.
ANSI is the American member of ISO, the international standards organization. Since
1998, C++ has an international standard, a sort of a treaty between compiler vendors
from all around the world on what language features they all agree to implement. C++,
as defined by that standard, is known as ISO C++. The ANSI standard is an aim to
ensure that C++ is portable -- that code you write or compose for Microsoft compiler
will be compiled without errors, using a compiler on Mac, UNIX, Windows box, or an
Alpha.
Use of C++
▪ C++ is highly used to write device drivers and other software that rely on direct
manipulation of hardware under real-time constraints.
▪ C++ is broadly used for teaching and research because it is clean enough to
successfully teach basic concepts.
LESSON 2:
Basic Elements of a Program
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 3 hours
Symbols
Comment symbol
The program that you write should be direct not only to you but also to the reader itself.
Part of good programming is the including of comments in the program. Generally,
comments can be used to explain the program’s purpose or explain the meaning of
key statements in the program. The compiler ignores these comments when it
translates the program into executable code.
For example:
For example:
Reserved Word
The second category of tokens is a reserved word. Reserved words are also called
keywords that cannot be redefined within any program; that is, they cannot be applied
for anything other than their expected use. Some of the essential reserved words are
given below:
The reserved words of C++ may be strategically located in some groups. In the first
group, were also present in the C programming language and have been continued
over into C++. There are 32 such reserved words:
There are other 30 reserved words that were not in C, are therefore new to C++:
The following 11 C++ reserved words are not vital when the standard ASCII character
set is being used. Still, they have been added to give more readable alternatives for
some of the C++ operators, and also to encourage programming with character sets
that lack characters needed by C++.
A specific compiler may not be completely modern, which implies that some (and possibly many) of the
reserved words in the lead up to two groups may not yet be actualized.
There is a differentiation between reserved words and predefined identifiers, which are once in a while
collectively referred to as keywords. Nonetheless, be aware that the terminology is nonstandard. As an
illustration, some authors use keywords in the same sense that others use the reserved word.
Identifier
The third category of tokens is the identifier. Identifier refers to the names of variables,
constants, functions, and other objects defined in a C++ program. It allows us to name
data and other objects in the program. Each identified object in the computer is stored
at a unique address. If we did not have identifiers that we could use to represent data
locations symbolically, we would have to know and use the object's addresses.
Instead, we simply give data identifiers and let the compiler keep track of where they
are physically located. Different programming languages use different syntactical rules
to form identifiers.
▪ The only valid name symbols are the capital letters A through Z, the lowercase
letters a through z ,digits 0 – 9, and underscore.
▪ The first character cannot be a digit or an underscore.
▪ An identifier cannot contain punctuation marks, math symbols, or other special
symbols.
▪ ANSI guarantees only the first 32 characters to be significant.
▪ C++ identifier is case-sensitive,
▪ The last rule is that the name we create cannot be keywords. Keywords are
also known as reserved words.
Example:
Data Types
A data type of a variable in the operating system assigns memory and decides what
can be stored in the reserved memory.
Some of the basic types can be modified using one or more of these type modifiers:
▪ signed
▪ unsigned
▪ short
▪ long
The following table shows the type of variable, how much memory it takes to store
the value in memory, and the maximum and minimum value stored in such variables.
The data type string is a computer programmer-defined type of data. Unlike primitive
data type, a string cannot be directly available for use in a program. To use this type,
you need to access program components from the C++ library.
Variable
A variable is used to hold data. The data stored in a variable is called its value.
datatype identifier;
int x;
float rate;
char answer;
IT 103: COMPUTER PROGRAMMING 1 69
UNIT 2: C++ Basics
Note:
The sizes of variables might be different from those shown in the above table
depending on the compiler and the computer you are using.
Operators
▪ Assignment Operator
▪ Arithmetic Operators
▪ Relational Operators
▪ Logical Operators
Assignment Operator
The assignment operator (=) is used in the assignment statement, which takes the
following form:
variable = expression;
To evaluate assignment statement, the expression on the right-hand side of the equal
sign is assessed first, and then the variable on the left-hand side is set to this value.
A variable needs to be initialized the first time a value is placed in the variable,
int x =10;
double pi = 3.14;
char ans = ‘y’;
Arithmetic Operator
Symbol Name Example Definition
It is taking two or more numbers
and adding them together. The
+ Addition x+y
result of an addition is called
sum.
represents the operation of
removing objects from a
- Subtraction x–y
collection. The result of
subtraction is called a difference.
one of the four basic operations
of arithmetic gives the result of
* Multiplication x* y combining groups of equal sizes.
The result of a multiplication is
called a product.
It is a method of distributing a
/ Division x/y
group of things into equal parts.
It is placed between
two expressions that have the
= Equal x=y same value, or for which one
studies the conditions under
which they have the same value
Modulus or It is the remainder after dividing
% x%y
Modulo one number by another.
++ Increment x ++ or ++ x Increases the value of x by 1
-- Decrement y ++ or -- y Decreases the value of x by 1
+ (unary) Positive +x The value of x
- (unary Negative -x The arithmetic negation of x
The modulo operator, represented by a percentage sign (%), gives the remainder of a
division process.
For example:
x = 10 % 3;
Order of precedence
It is likely to build mathematical expressions with several operators. When more than
one arithmetic operator is used in an expression, C++ uses the operator precedence
rules to assess the expression. In line with the order of precedence rules for arithmetic
operators,
However, when operators have the same level, the operations are performed from
left to right.
What value will be stored in x? The answer is 14 because the order of operations
dictates that the division operator works before the addition operator does.
Expression Value
5 + 2 *4 13
10 / 2 – 3 2
8 + 12 * 2 – 4 28
6–3*2+7–1 6
(5 + 2) * 4 28
10 / (5 – 3) 5
8 + 12 * (6 – 2) 56
(6 – 3) * (2 + 7) / 3 9
You probably remember from algebra class that the expression 2xy is understood to
mean 2 times x times y. in math, you do not always use an operator for multiplication.
Programming languages, however, require an operator for any mathematical
operation.
Programming
Algebraic Expression
Expression
6B 6*B
(3)(12) 3 * 12
4xy 4*x*y
𝑥
y = 32 y=x/2*3
z = 3bc + 4 z = 3 * b *c + 4
𝑥+2
a = 𝑎−1 a = (x + 2) / (a – 1)
Increment (++) and Decrement (--) operators are placed either in front or after the
operand. The statements
++x; or ++x;
- -y; or y- -;
When used in assignment statements, however, placing the operators after the
variable takes a different meaning.
In the assignment statement for the variables y and z, the increment and decrement
operators are placed after the variable operands. As such, the operators are called
post-increment and post-decrement operators, respectively. This means that the
variable operands will be incremented/decremented after the expressions have been
thoroughly evaluated. In the statement
y=x++;
The value of the variable x is assigned first to the variable y before it is incremented.
Thus, after the statement is executed, x=6, and y=5. In the statement
z=y- -*2;
Example 1 Example 2
x=4;
y=++x; // x contains x=5;
5, y contains y=x++;// x contains
5 6, y contains 5
x += 2; x = x + 2;
y - = 5; y = y - 5;
a /= 2; a = a / 2;
b * = c; b = b * c;
z %=10 z = z % 10;
Relational Operators
Two expressions can be collated using relational operators. For example, to know if
two values are equal or if one is less than the other.
The result of such an operation is either true or false (i.e., a Boolean Value)
Relational Operator
Symbol Name Example Definition
Compares if the value of the
< Less than x<y left operand is less than the
value of the right operand.
Compares if the value of the
left operand is greater than
> Greater than x>y
the value of the right
operand.
Compares if the value of the
left operand is less than or
<= Less than or equal to x <= y
equal to the value of the
right operand.
Compares if the value of the
Greater than or equal left operand is greater than
>= x>=y
to or equal to the value of the
right operand.
Compares if the values of
== Equal to x == y two operands are equal or
not.
Compares if the values of
!= Not Equal x != y two operands are equal or
not.
Boolean Expressions
(7 == 5) // false
(5 > 4) // true
(3 != 2) // true
(6 >= 6) // true
(5 < 5) // false
Of course, it is not only numeric constants that can be linked but only any value,
including variables.
// false,
(a = = 4)
since a is not equal to 4
// true,
(a * b >= c)
since (2*3 >= 6) is true
// false,
( b+4 > a)
since (3+4 > 2*6) is false
Logical Operator
Symbol Name Example Definition
((a == 5) && (b> 6)) Logical AND operator. If
// evaluates to false both the operands are non-
&& And
zero, then the condition
( true && false )
becomes true.
((a == 5) || (c>8)) Logical OR Operator. If
any of the two operands is
|| Or // evaluates to true
( true || false ) non-zero, then condition
becomes true.
!(a == 5)
// evaluates to false Logical NOT Operator.
because the Use to reverses the logical
state of its operand. If a
! Not expression at its
condition is true, then
right (a == 5) is
Logical NOT operator will
true make false.
LESSON 3:
Code Blocks Environment
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 2 hours
Code Blocks
Editor
In the above outline, a source named hello.c is opened with syntax highlighting
in the editor.
CodeSnippets
can be displayed via the menu ’View’ →’CodeSnippets’ . Here you can
accomplish text modules, links to files, and links to URLs.
Toolbars
These messy strips, embellished with different command buttons, cling to the
top of the Code::Blocks window. There are eight toolbars, which you can
improve, show, or cover-up. Try not to play with them until you get settled with
the interface.
CodeSnippets
Management
Toolbars
Editor
Logs and
Others
Note:
In the active editor, the user can select the context menu properties. In the appearing
dialog in the tab 'General' the option 'File is read-only' can be chosen. This alternative
will bring in a read-only access of the relating document within CodeBlocks, but the
original read and write characteristics of the file on the filesystem are not changed.
The View menu controls the visibility of every item displayed in the window.
Choose the proper command, such as Manager, from the View menu to show or hide
that item and Control toolbars by using the View→Toolbars submenu.
The most significant thing to recall about the Code::Blocks interface isn't to
let it overwhelm you. An IDE, for example, Code::Blocks can be exceptionally scary,
in any event, when you see yourself as experienced at programming. Try not to
stress: You'll before long feel right comfortable.
▪ Maximize the Code::Blocks program window so that it fills the screen. You
need all that real estate.
▪ Each of the various areas on the screen -- Management, Editor, Logs -- can
be resized: Position the mouse pointer between two areas. When the pointer
changes to a double-arrow thingy, you can drag the mouse to change an
area’s size.
Opening C::B
▪ The 1st time it is opened C::B will search for compilers it can use.
▪ A dialog box will open. Select GCC if there are multiple options. See
Figure 3.
Step 1. Create a project from the File menu or the Start Here tab.
Step 2: Choose the Console category and then the Console Application and
click Go.
Step 3: Click Next on the “Welcome to the new console application wizard!”
screen.
cccc
Step 5: Enter a project title. Let C::B fill in the other fields for you. If you like you
can change the default folder to hold the project. Click Next.
Step 6: Choose the compiler. Choose GNU GCC as the compiler. Click Next.
Step 7: Right click on your project name and choose Build options
▪ Check off the C++ 11 option. Click Release on the left and do the
same there as well.
▪ Do this anytime we create a project in C::B
Step 8: Your project is now created! Click on Sources in the left column, then
double-click main.cpp.
▪ Click the icon in the toolbar or press F9 to compile and run the
program.
LESSON 4:
Basic Input and Output Statement
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 3 hours
Program lines beginning with a hash sign (#) are directives read and interpreted by
what is known as the preprocessor.
These are the lines deciphered before the arrangement of the program itself starts.
For example, the directive #include <iostream>, instructs the preprocessor to include
a section of standard C++ code, known as header iostream, for standard input and
output operations, such as displaying the output of the program to the screen.
# include <iostream>
iostream is the name of the library that contains the definitions of the routines that
handle basic input/output operation.
int main()
The line int main() means that the main body of the program starts here. It is referred
to as the main() function.
The execution of all C++ programs starts with the main() function, regardless of where
the function is situated inside the code.
{}
The braces { and } mark the start/beginning and end/finish of the main body of the
program. Everything between the braces is the function body that defines what
happens when the main is called. All functions use braces to demonstrate the start
and end of their definitions.
The statements within the braces are the instructions that are followed by the
computer, often called executable statements. Program statements are executed in
the order that they appear within a function body.
return 0;
The next line returns 0; terminates main()function, and causes it to return the value 0
to the calling process.
There are C++ codes where std::cout is being used instead of cout alone.
cout is part of the standard C++ library, and all elements in the standard C++ library
are declared within what is called a namespace: the namespace std. Accessing the
elements in the std namespace is by means of using declarations:
This will allow all elements in the std namespace to be accessed without the std::
prefix).
Let us look at the two sample codes that would print the words Hello World.
Example 1
#include <iostream>
Sample Output
int main()
Hello World!
{
std::cout<<”Hello World”;
return 0;
Example 2
#include <iostream>
Sample Output
using namespace std;
Hello World!
int main()
{
cout<<”Hello World”;
return 0;
}
C++ uses a suitable abstraction called streams to complete input and output
operations. A stream is an entity where a computer program can either insert or extract
characters to/from. This is a source /destination of characters and that these
characters are provided/accepted sequentially (i.e., one after another).
The predefined object cout is an instance of stream class. The cout object is said to
be "connected to" the standard output device, which usually is the display screen. The
cout is used together with the stream insertion operator written as << (two less than
signs)
This statement means that the expression is evaluated, its value is printed, and
manipulators are used to formatting the output. Examples of manipulators will be
discussed in the later section of this lesson.
Example 1
#include <iostream> Sample Output
using namespace std;
Hello World!
int main()
{
cout<<”Hello World!”;
return 0;
}
To have formatted output operations, cout is used together with the insertion operator,
which is written as << (i.e., two "less than" signs)
The << operator inserts the data that follows it into the stream that precedes it
This technique is especially useful to mix literals and variables in a single statement:
age = 18;
cout<< “I am”<< age << “years old”;
x=5; y=10;
cout<< “The sum of “<<x<< “and” <<y<< “ is” <<x+y;
Escape Sequence
The backslash (\) is known as the escape character in the ASCII character set. The
escape character is used in the C++ language to tell the computer that a special
character follows.
The escape sequence is typed in as two characters with no space between symbols.
Several escape sequences are shown in the table below:
The output would be in a single line without any line breaks in between.
To insert a line break in the output, a newline character (\n) is inserted in the exact
position, and the line should be broken.
Hello!
Have a nice day!
For example:
cout<< "Hello!"<<endl;;
cout<< "Have a nice day!"<<endl;
You can use the manipulator setprecision to control the output of floating-point
numbers.
setprecision(n);
You can use setprecision manipulator with cout and insertion operator. For example,
the statement,
cout<<setprecision(2);
It formats the output of floating-point numbers to two decimal places. The number of
decimal places or the precision value is passed as an argument to setprecision.
To use the manipulator setprecision an iomanip header file must be included in the
program. Thus, the following include statement is required:
#include <iomanip>
Example:
double pi=3.14159265;
cout<< setprecision(2);
cout<< pi;
Or
cout<< setprecision(2)<< pi;
// prints 3.14
The cin object is an instance of an iostream class and attached to the standard input
device, usually keyboard. It is used with the stream extraction operator(>>).
int age;
cout<<"Please enter your age: ";
cin>>age;
cout<<"You are"<< age<<“years old” <<endl;
When the above code is executed, it will prompt you to enter your age. You enter a
value and then press the enter key to see the result something as follows:
The C++ compiler also checked the data type of the entered value and selected the
appropriate stream extraction operator to extract the value and store it in the given
variables.
The stream extraction operator >> may be used more than once in a single statement.
To request more than one data, you can use the following:
int num1,num2;
cout<< “Enter two numbers: ”;
cin>> num1>>num2;
cin>>num1;
cin>>num2;
In sequential structure, Basic I/O program statements are executed one after another,
in the order by which they appear in the program.
Start
Initialization
Input
Process
/Compute
Output
End
Example 1
#include <iostream>
using namespace std; Sample Output
prod=num1*num2;
Example 2
#include <iostream> Sample Output
using namespace std;
main()
{ Enter the First Number: 1
Enter the Second Number: 1
int num1; Sum:2
int num2; Product:2
int sum; Difference:0
int prod; Quotient:1
int diff;
float quo;
sum=num1+num2;
prod=num1*num2;
diff=num1-num2;
quo=num1/num2;