0% found this document useful (0 votes)
8 views

COM 313-C-Plus-Plus HND

C++ is an object-oriented programming language developed by Bjarne Stroustrup, designed to improve upon C by offering more control over memory and system resources. Key features of C++ include its simplicity, object-oriented principles, machine independence, and a rich library of built-in functions, making it suitable for both low-level and high-level programming. The document also covers fundamental data types, constants, variables, and operators in C++, providing a comprehensive overview for beginners.

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

COM 313-C-Plus-Plus HND

C++ is an object-oriented programming language developed by Bjarne Stroustrup, designed to improve upon C by offering more control over memory and system resources. Key features of C++ include its simplicity, object-oriented principles, machine independence, and a rich library of built-in functions, making it suitable for both low-level and high-level programming. The document also covers fundamental data types, constants, variables, and operators in C++, providing a comprehensive overview for beginners.

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT 1

THE BASIC CONCEPT OF C++ PROGRAMMING LANGUAGE


Introduction
C++ (said C plus plus) is an object-oriented computer language created by notable computer
scientist Bjarne Stroustrop as part of the evolution of the C family of languages. It was
developed as a cross-platform improvement of C to provide developers with a higher degree of
control over memory and system resources.
Some call C++ “C with classes” because it introduces object-oriented programming principles,
including the use of defined classes, to the C programming language framework.
C++ FEATURES
1. Simple
We expect to understand a new programming language thoroughly when we start using it,
however, C++ is one of the most-simple programming languages. As long as you are familiar
with the C language, moving to C++ will be very easy.
2. Object Oriented
C++ is an Object-Oriented Programming Language (OOP). OOPs are the most important feature
of C++ since they enable easier development and maintenance. C++ follows the following
concept of OOPs to make development and maintenance of the software system easier:
 Polymorphism: Poly means “many” and morphism means “form”. Thus, polymorphism
enhances flexible programming by allowing data to be displayed in more than one form.
 Inheritance: Inheritance is the process of allowing a class to inherit the features or
properties (fields and methods) of another class. As a result, the program is less
redundant, and it is easy to move properties from one class to another.
 Data Encapsulation: Essentially, encapsulation means packaging together relevant
data and its associated methods and functions into a single unit/block.
 Data Abstraction: It refers to the process of displaying only the key
details/information of data to users without including the underlying/background
details or the method used to gather it.
 Data Hiding: It is the process of protecting data from unauthorized access. Essentially,
it secures the data.

3. Machine Independent and Platform-Dependent


C++ is machine-independent, which means programs can be executed on many machines with
little or no changes. C++, however, is not platform-independent, so programs can only be
executed on the platform on which they were developed & compiled. The compiler produces an
.exe file that is OS-dependent, and cannot be run on different operating systems. Suppose you
wrote a program or piece of code that runs on Linux, Windows, and Mac OSX, making it
Machine Independent, but the executable file of the C++ program cannot run on different
Operating systems/platforms.
COM 313 C++ Programming Language

4. Case-Sensitive
C++ is case-sensitive, which means that it treats uppercase and lowercase characters
differently.
5. Mid-level programming language
Having the features of both a low-level (machine-level) language and a high-level language
(user-oriented language that is easily understandable and close to human language), C++ is
termed a mid-level or intermediate programming language. C++ is used to develop low-level
system applications, such as kernels, drivers, etc., and high-level applications, such as GUIs,
desktop applications, etc.
6. Structured Programming Language
C++ is a structured programming language. Programming in C++ is modular i.e. we are able to
break the complex code into smaller pieces (subdividing a computer program into separate
sub-programs) and combine them using functions, classes, and objects. This results in cleaner
code and makes maintenance much easier.
7. Rich Library
C++ provides developers with many built-in functions or libraries that save developers time
and make development faster. Some of the header files include:
 <iostream>: Include C++ standard input and output functions
 <cmath>: Include math library functions
 <cstdlib>: Includes functions that convert numbers to text and vice versa, allocate
memory, create random numbers, and perform various other functions.
 <fstream>: Include functions to create files, write information to files, and read
information from files.
 <iterator>: Include classes for accessing data in the C++ Standard Library containers
8. Compiler-Based
It is not possible to run C++ code without compilation, since it is a compiler based
programming language. To execute our program, we must first compile it using a compiler that
translate the program into machine language which can be understood directly by the system.
The resulting program is therefore highly efficient and faster than most interpreter-based
languages, such as Python and Java.

IMPORTANCE OF C ++ (WHY YOU SHOULD LEARN C++)?


If you want to start learning programming, then C++ can be the best choice to make a good
start, you might be wondering Why?
Following are the advantages of C++ −

 C++ is a highly portable language and is often the language of selection for multi-device,
multi-platform app development.

2
COM 313 C++ Programming Language

 C++ is an object-oriented programming language and includes concepts like classes,


inheritance, polymorphism, data abstraction, and encapsulation which allow code
reusability and makes programs very maintainable.
 C++ use multi-paradigm programming. The Paradigm means the style of programming.
Paradigm is concerned about logics, structure, and procedure of the program. By multi-
paradigm means it follows three paradigm: Generic, Imperative, Object-Oriented.
 It is useful for the low-level programming language and very efficient for general
purpose.
 C++ gives the user complete control over memory management. This can be seen both as
an advantage and a disadvantage as this increases the responsibility of the user to
manage memory rather than it being managed by the Garbage collector.
 The wide range of applications − From GUI applications to 3D graphics for games to real-
time mathematical simulations, C++ is everywhere.
 C++ has a huge community around it. Community size is important, because the larger a
programming language community is, the more support you would be likely to get.
 C++'s greatest strength is how scalable it could be, so apps that are very resource
intensive are usually built with it. As a statically written language, C++ is usually more
performant than the dynamically written languages because the code is type-checked
before it is executed.
 Compatibility with C − C++ is compatible with C and virtually every valid C program is a
valid C++ program.

UNIT 2

THE FUNDAMENTAL DATA TYPES, CONSTANTS AND VARIABLES OF C++

While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer,
floating point, double floating point, boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.
Primitive Built-in Types
C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double

3
COM 313 C++ Programming Language

Valueless void
Wide character wchar_t
Several of the basic types can be modified using one or more of these type modifiers:

 signed
 unsigned
 short
 long
Assignment 1:
Make a list consisting of the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.

User-Defined Data Types


- typedef Declarations
You can create a new name for an existing type using typedef. Following is the simple syntax to
define a new type using typedef −
typedef type newname;
For example, the following tells the compiler that feet is another name for int −
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable
called distance −
feet distance;
Enumerated Types
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant
whose type is the enumeration.
Creating an enumeration requires the use of the keyword enum. The general
form of an enumeration type is −
enum enum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is
comma separated.
For example, the following code defines an enumeration of colors called colors
and the variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c;
c = blue;
By default, the value of the first name is 0, the second name has the value 1,
and the third has the value 2, and so on. But you can give a name, a specific
value by adding an initializer. For example, in the following
enumeration, green will have the value 5.
enum color { red, green = 5, blue };

4
COM 313 C++ Programming Language

Here, blue will have a value of 6 because each name will be one greater than
the one that precedes it.

Variable Definition in C++


A variable definition tells the compiler where and how much storage to create
for the variable. A variable definition specifies a data type, and contains a list of
one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., and variable_list may consist of
one or more identifier names separated by commas. Some valid declarations
are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;

OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C++ is rich in built-in operators and provide the
following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
For convenience, we will examine the arithmetic, relational, logical, bitwise,
assignment and other operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then;
Operato Description Example
r
+ Adds two operands A + B will give 30
- Subtracts second operand A - B will give -10
from the first

5
COM 313 C++ Programming Language

* Multiplies both operands A * B will give 200


/ Divides numerator by de- B / A will give 2
numerator
% Modulus Operator and B % A will give 0
remainder of after an integer
division
++ Increment operator, increases A++ will give 11
integer value by one
-- Decrement operator, A-- will give 9
decreases integer value by
one

Relational Operators
There are following relational operators supported by C++ language
Assuming the same applies to variable A and B as before, then
Operato Description Example
r
== Checks if the values of two operands (A == B) is not true.
are equal or not, if yes then condition
becomes true.
!= Checks if the values of two operands (A != B) is true.
are equal or not, if values are not
equal then condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right
operand, if yes then condition
becomes true.
< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition
becomes true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then;
Operato Description Example
r
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.

6
COM 313 C++ Programming Language

two operands is non-zero, then condition


becomes true.
! Called Logical NOT Operator. Use to !(A && B) is true.
reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following
table. Assume variable A holds 60 and variable B holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the (A & B) will give 12
result if it exists in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it (A | B) will give 61
exists in either operand. which is 0011 1101
^ Binary XOR Operator copies the bit if it (A ^ B) will give 49
is set in one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is (~A ) will give -61
unary and has the effect of 'flipping' which is 1100 0011 in
bits. 2's complement form
due to a signed binary
number.
<< Binary Left Shift Operator. The left A << 2 will give 240
operands value is moved left by the which is 1111 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15
operands value is moved right by the which is 0000 1111
number of bits specified by the right

7
COM 313 C++ Programming Language

operand.

Assignment Operators
There are following assignment operators supported by C++ language −
Operator Description Example
= Simple assignment operator, Assigns C = A + B will assign
values from right side operands to value of A + B into C
left side operand.
+= Add AND assignment operator, It C += A is equivalent to C
adds right operand to the left =C+A
operand and assign the result to left
operand.
-= Subtract AND assignment operator, It C -= A is equivalent to C
subtracts right operand from the left =C-A
operand and assign the result to left
operand.
*= Multiply AND assignment operator, It C *= A is equivalent to C
multiplies right operand with the left =C*A
operand and assign the result to left
operand.
/= Divide AND assignment operator, It C /= A is equivalent to C
divides left operand with the right =C/A
operand and assign the result to left
operand.
%= Modulus AND assignment operator, It C %= A is equivalent to C
takes modulus using two operands =C%A
and assign the result to left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C =
C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C =
C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C
&2
^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C
operator. ^2
|= Bitwise inclusive OR and assignment C |= 2 is same as C = C |
operator. 2

Misc Operators
The following table lists some other operators that C++ supports.
S/No Operator & Description
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a),
where ‘a’ is integer, and will return 4.
2 Condition ? X : Y

8
COM 313 C++ Programming Language

Conditional operator (?). If Condition is true then it returns value of X


otherwise returns value of Y.
3 ,
Comma operator causes a sequence of operations to be performed.
The value of the entire comma expression is the value of the last
expression of the comma-separated list.
4 . (dot) and -> (arrow)
Member operators are used to reference individual members of
classes, structures, and unions.
5 Cast
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
6 &
Pointer operator & returns the address of a variable. For example &a;
will give actual address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will
pointer to a variable var.

Escape Sequence
Escape sequences are special characters used in control strings to modify the
format of the output. These specific characters are translated into another
character or a sequence of characters that may be difficult to represent directly.
For example, if you want to put a line break in the output of a C++ statement
then you will use the “\n” character which is an escape sequence itself.

An escape sequence consists of two or more characters. For all sequences, the
first character will be ”\” i.e. backslash. The other characters determine the
interpretation of the escape sequence. For example, “n” of “\n” tells the cursor
to move to the next line.

Other escape sequence used in C++ programs include:

Tab (\T):
A TAB is equal to eight spaces. Whenever the TAB button is pressed from the
keyboard, then 8 spaces are left blank. This escape sequence performs the
functionality of the TAB key in the output stream. The code given below will
insert a TAB between two words.

cout<<”COMPUTER\tSCIENCE”;

9
COM 313 C++ Programming Language

As you can see after printing “COMPUTER”, 8 spaces are left blank, and then
“SCIENCE” is printed on the screen.

Alert Bell (\A):


This escape sequence is used to play beep during execution. For example:

cout<<”COMPUTER\aSCIENCE”;
First of all, “COMPUTER” is printed then a beep is played and after that
“SCIENCE” is printed.

Backspace (\B):
Whenever we want to delete a single character, we press the button
“backspace” from our keyboard. The same functionality can be achieved in C++
output with this escape sequence. For example:

cout<<”COMPUTER\bSCIENCE”;

Assignment 2.
a) Tabulate the operator precedence chart in C++ language
b) Find out and explain many more escape sequence used by C++

UNIT 3
OBJECTIVE: UNDERSTAND INPUT AND OUTPUT OPERATIONS IN C++

The C++ standard libraries provide an extensive set of input/output capabilities


which we will consider subsequently; meanwhile, we’ll first discuss the basic
and most common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a
device like a keyboard, a disk drive, or a network connection etc. to main
memory, this is called input operation and if bytes flow from main memory to
a device like a display screen, a printer, a disk drive, or a network connection,
etc., this is called output operation.

10
COM 313 C++ Programming Language

I/O Library Header Files


There are following header files important to C++ programs −
Sr.N Header File & Function and Description
o
1 <iostream>
This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.
2 <iomanip>
This file declares services useful for performing formatted I/O
with so-called parameterized stream manipulators, such
as setw and setprecision.
3 <fstream>
This file declares services for user-controlled file processing. We
will discuss about it in detail in File and Stream related unit.

The Standard Output Stream (cout)


The predefined object cout is an instance of ostream class. The cout object is
said to be "connected to" the standard output device, which usually is the
display screen. The cout is used in conjunction with the stream insertion
operator, which is written as << which are two less than signs.
The Standard Input Stream (cin)
The predefined object cin is an instance of istream class. The cin object is said
to be attached to the standard input device, which usually is the keyboard.
The cin is used in conjunction with the stream extraction operator, which is
written as >> which are two greater than signs.
The Standard Error Stream (cerr)
The predefined object cerr is an instance of ostream class. The cerr object is
said to be attached to the standard error device, which is also a display screen
but the object cerr is un-buffered and each stream insertion to cerr causes its
output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator.
The Standard Log Stream (clog)
The predefined object clog is an instance of ostream class. The clog object is
said to be attached to the standard error device, which is also a display screen
but the object clog is buffered. This means that each insertion to clog could

11
COM 313 C++ Programming Language

cause its output to be held in a buffer until the buffer is filled or until the buffer
is flushed.
The clog is also used in conjunction with the stream insertion operator.
You would not be able to see any difference in cout, cerr and clog with these
small examples, but while writing and executing big programs the difference
becomes obvious. So it is good practice to display error messages using cerr
stream and while displaying other log messages then clog should be used.

Classes and Objects in C++


Classes are the prime features of C++ as they support OOPS concepts and are
user defined data types. Classes provide the specification for an object and
contain data variables as well as functions to manipulate the data in a single
package.
Class Definitions
A class definition starts with the keyword class and then the class name. After
that the class body is defined. It is enclosed by curly braces. A class definition
should either contain a semicolon or a list of definitions after it.
An example of a class definition in C++ is as follows.
class student {
int rollno;
char name[50];
float marks;
};

The above class contains the details of a student, namely its roll number, name
and marks.
Object Definitions
When a class is defined, it is only a specification. There is no memory or
storage allocated at that time. So the object is created from the class to access
the data and functions defined in the class. A class can also be called the
blueprint for an object.
The declaration of an object of class student is given as follows.
Student stu1;
A program that demonstrates classes and objects in C++ is obviously given.
See appendixes.

UNIT 4

12
COM 313 C++ Programming Language

UNDERSTAND FUNCTIONS AND LIBRARIES IN C++


Functions
A function is a group of statements that together perform a task. Every C++
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
A function declaration tells the compiler about a function's name, return type,
and parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many
more functions.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body.
Here are all the parts of a function −
 Return Type − A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the return_type
is the keyword void.
 Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements
that define what the function does.

Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For example, the following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is
required, so following is also valid declaration −
int max(int, int);

13
COM 313 C++ Programming Language

Function declaration is required when you define a function in one source file
and you call that function in another file. In such case, you should declare the
function at the top of the file calling the function.
Calling a Function
Function calling is the process of actually implementing or using the function so
declared in a program. To use a function, you will have to call or invoke that
function.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned
value.
While calling a function, there are two ways that arguments can be passed to a
function
Sr.N Call Type & Description
o
1 Call by Value
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the
argument.
2 Call by Pointer
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made
to the parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access
the actual argument used in the call. This means that changes
made to the parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means
that code within a function cannot alter the arguments used to call the function.

C++ Libraries
The C++ Standard Library is a reference for C++ programmer to help them at
every steps of their projects related to system programming. All the C++
functions have been explained in easy to understand way and they can be used
easily in your C++ projects.
Assignment 3
List 20 library classes or functions found in the C++ standard library.

14
COM 313 C++ Programming Language

UNIT 5
CONTROL STURCTURES IN C++
The If_Statement; syntax:
if (condition)
{
//body (codes)
}
1. If the condition inside the parenthesis is evaluated to be true, then its body is executed otherwise
it doesn’t execute.
In the case of if in the place of condition always zero and non-zero value is checked in which zero
means condition is false and non-zero means condition is true.
If_Else Statement in C++ Language
Syntax:
if (conditional stmt)
{
//if condition is true: execute code
}
else
{
//if condition is evaluated to false, execute here
}
Nested If_Statement in C++ Language
Syntax:
if (condition)
{
if(another condition){
//statements…
}
}
a) Nested means one inside another; so one if inside another if is called nested if.
b) In the case of if in the place of condition always zero and non-zero value is checked in
which zero means condition is false and non-zero means condition is true
Sample Code:
#include<iostream>
int main() {
int x = 10;
if(x>5) //checking the condition_1
{
if(x<15)//checking the condition_2
{
cout<”x is greater than 5 and less than 15”;
}
}
}

15
COM 313 C++ Programming Language

In the above program, the outer if condition is true, so its body will execute and the condition of
inner if is also true so the output is: “x is greater than 5 and less than 15”
Assignment:
Change the above sample code but ensure it produces the same results. Hint: make use of the logical
operators: AND, OR, or NOT.
The Switch Statement in C++ Language
The switch statement allows us the opportunity to execute one statement from many statements and
those statements are called case. Actually, in switch statement, inside the body of switch a number of
cases are used and a parameter is passed and from which case this parameter is matched, executed.
Syntax:
switch(parameter){
case 1:
statement_1;
break;
case 2:
statement_2;
break;


case n:
statement_n;
break;
default;
default_statement;
}

1. In the switch statement, a value/number is passed in the place of parameter and that
case will execute; which is equal to that value/number.
2. If no case matched with the parameter(s) then the default case will execute.
Sample Code:

#include<iostream>
int main() {
//assigning parameter’s value
intp=2;
OUTPUT:
switch (p){
case 1: it is case 2
cout<< “it is case1”;
break;
case 2:
cout<< “it is case 2”; Note: this is because P=2, so case
break; 2 will execute
case 3:
cout<< “it is case 3”;
break;
default:
cout<< “No case matched!”;
}
return 0;
}
16
COM 313 C++ Programming Language

Assignment:
Re-write the sample program above to compute students’ grade using the following parameters:
- 75 and above = ‘A’
- 65 – 74 = ‘B’
- 55 – 64 = ‘C’
- 45 – 54 = ‘D’
- 40 – 44 = ‘E’
- 0-39 = default = ‘F’
 Compile your source code and print the output.

For Loop in C++ Language


To run the body or segment of code continuously until a required condition is fulfilled, we use a loop
control structure. When the condition of the loop becomes false, the execution stops.
Syntax:
for (<initialization>; <condition>; <increment/decrement>)
{
//body of the loop
}
The initialization part executes only once. All the three parts of the loop are optional.

Sample:
#include<iostream>
int main()
{
for(inti=1; i<=10; i++)
{
cout<<i<<”\n”;
}
}//the output will generate numbers from 1-10

WhileLoop in C++ Language


Syntax:
while(condition)
{
//body of the loop
}
Its body will continue to execute until the given condition is false.
Do…while Loop in C++ Language
Syntax:

17
COM 313 C++ Programming Language

do {
// body of the loop
}
while(condition);
This type of loop will execute until when a certain condition (given) is true.
Exercises:
1. Re-write the sample program above using the do…while loop as shown in the syntax
above.
2. Establish the distinction between the do...while and the while loops.

UNIT 6
OBJECT ORIENTED PROGRAMMING CONCEPTS
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts: Object; Class; Inheritance;
Polymorphism; Abstraction; and Encapsulation.
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
A Class in C++ is the foundational element that leads to Object-Oriented programming. A class
instance must be created in order to access and use the user-defined data type's data members and
member functions. An object's class acts as its blueprint.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Reusability -
As a result, when we wish to create a new class, but an existing class already contains some of the
code we need, we can generate our new class from the old class thanks to inheritance. This allows us
to utilize the fields and methods of the pre-existing class.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. Data abstraction is the
process of exposing to the outside world only the information that is absolutely necessary while
concealing implementation or background information. For example: phone call, we don't know the
internal processing.

In C++, we use abstract class and interface to achieve abstraction.

18
COM 313 C++ Programming Language

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
Encapsulation is typically understood as the grouping of related pieces of information and data into a
single entity. Encapsulation is the process of tying together data and the functions that work with it in
object-oriented programming.

C++ Class

In C++, class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc.

Some important properties of class are −


 Class is a user-defined data-type.
 A class contains members like data members and member functions.
 Data members are variables of the class.
 Member functions are the methods that are used to manipulate data members.
 Data members define the properties of the class whereas the member functions define the
behaviour of the class.

Let's see an example of C++ class that has three fields only.

1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }

C++ Object and Class Example

Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonen Sewuese";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;

19
COM 313 C++ Programming Language

15. }

EXAMPLE 2
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(01, "Sonnen");
21. s2.insert(02, "Ojieh");
22. s1.display();
23. s2.display();
24. return 0;
25. }
EXAMPLE 3

Store and Display Employee Information

Let's see another example of C++ class where we are storing and displaying employee information
using method.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee

20
COM 313 C++ Programming Language

21. Employee e2; //creating an object of Employee


22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }

EXAMPLE 4

#include<iostream>
using namespace std;
class calculator {
int number1;
int number2;
char symbol;
public :
void add() {
cout<<"The sum is "<<number1 + number2 ;
}
void subtract() {
cout<<"The subtraction is "<<number1 - number2 ;
}
void multiply() {
cout<<"The multiplication is "<<number1 * number2 ;
}
void divide() {
cout<<"The division is "<<number1 / number2 ;
}
calculator (int a , int b , char sym) {
number1 = a;
number2 = b;
symbol = sym;
switch(symbol){
case '+' : add();
break;
case '-' : add();
break;
case '*' : add();
break;
case '/' : add();
break;
default : cout<<"Wrong operator";
}
}
};
int main() {
calculator c1(12 , 34 , '+');
}

UNIT SEVEN
CONTROL STURCTURES IN C++
The If_Statement; syntax:

21
COM 313 C++ Programming Language

if (condition)
{
//body (codes)
}
2. If the condition inside the parenthesis is evaluated to be true, then its body is executed otherwise
it doesn’t execute.
3. In the case of if in the place of condition always zero and non-zero value is checked in which
zero means condition is false and non-zero means condition is true.

If_Else Statement in C++ Language


Syntax:
if (conditional stmt)
{
//if condition is true: execute code
}
else
{
//if condition is evaluated to false, execute here
}

Nested If_Statement in C++ Language


Syntax:
if (condition)
{
if(another condition){
//statements…
}
}
a) Nested means one inside another; so one if inside another if is called nested if.
b) In the case of if in the place of condition always zero and non-zero value is checked in
which zero means condition is false and non-zero means condition is true
The Switch Statement in C++ Language
The switch statement allows us the opportunity to execute one statement from many statements and
those statements are called case. Actually, in switch statement, inside the body of switch a number of
cases are used and a parameter is passed and from which case this parameter is matched, executed.
Syntax:
switch(parameter){
case 1:
statement_1;
break;
case 2:
statement_2;
break;

22
COM 313 C++ Programming Language


case n:
st
atement_n;
break;
default;
default_statement;
}

1. In the switch statement, a value/number is passed in the place of parameter and that
casewill execute; which is equal to that value/number.
2. If no case matched with the parameter(s) then the default case will execute.

For Loop in C++ Language


To run the body or segment of code continuously until a required condition is fulfilled, we use a loop
control structure. When the condition of the loop becomes false, the execution stops.
Syntax:
for (<initialization>; <condition>; <increment/decrement>)
{
//body of the loop
}
The initialization part executes only once. All the three parts of the loop are optional.

While_Loop in C++ Language


Syntax:
while(condition)
{
//body of the loop
}
Its body will continue to execute until the given condition is false.
Do…while Loop in C++ Language
Syntax:
do {
// body of the loop
}
while(condition);
This type of loop will execute until when a certain condition (given) is true.
Exercises:
1. Re-write the sample program above using the do…while loop as shown in the syntax
above.
2. Establish the distinction between the do...while and the while loops.
Nested Loop in C++ Language

23
COM 313 C++ Programming Language

Definition: A loop inside another loop is called nested loop; so one for loop inside another for loop is
called nested for-loop and so on.
Syntax:
for(..; …; …)
{
for(..; …; …)
{//statements
}
//statements
}

POINTERS IN C++ LANGUAGE


What is a Pointer?
1. It is a special type of variable which is used to store the address of another variable.
2. It can store the address of same data type; that means an integer pointer can store the
address of an integer variable, character can store for character, and so on…
3. If we add asterisk(*) symbol with any variable at the time of declaring the variable, then
this variable is marked out to be a pointer variable. E.g. int *p;
4. We use ampersand (&) symbol to get the address of variables
5. *symbol is used to get the value of address which is hold by pointer.

Sample:
#include<iostream.h>
void main() {
int a=10; //normal variable initialized
int *p; //pointer variable declared
p=&a; //address of variable a is assigned to p
cout<<”value of a=”<<a;
cout<<”address of a=”<<&a;
cout<<”value of p=”<<p;
cout<<”address of p=”<<&p;
cout<<”value of *p=”<<*p;
}
### Output ###
Value of a=10
Address of a=8284
Value of p=8284
Address of p=8288
Value of *p=10

UNIT EIGHT (8)


ARRAYS AND POINTERS
What is an Array?
1. It is a collection of data of same data type. This means that an integer array can store only
integer values, and so is character, and so on…
2. It is used to store group of data simultaneously.
3. We cannot fetch data from array directly therefore we use index point.

24
COM 313 C++ Programming Language

4. The indexing of array always start with 0; and must always be an integer number.
5. Array may be of any data type like int, char, float, etc.
Syntax (Array Declaration):
int arr[10];

data type array name array size


- Here; ‘arr’ is the name of the array
- Int is the data type of the array to be collected.
- Size of array is 10; which means it can collect maximum of 10 elements
Initialization of Arrays:
 Method 1:
int a [5] = { 10, 20, 25, 30, 55};
 Method 2:
int a[5];
a[0]=10;
a[1]=20;
a[2]=25;
a[3]=30;
a[4]=55;

Two-Dimension Arrays in C++


Syntax (Declaration):
int arr [3][3]
1) Here, arr is the name of the array;
2) Int is the data type of the array;
3) Size of array is 3x3, meaning we can store maximum of 9 values in this array.
4) The first 3 represent maximum number of rows while the other represents maximum number
of columns
Initialization of 2-dimension Arrays; Method 1:
int arr[3][3] = {{40,50,60},{10,20,30}, {70,80,90}};
The above can be represented in a matrix form as follows:
40 50 60 arr[0][0] arr[0][1] arr[0][2]
10 20 30 arr[1][0] arr[1][1] arr[1][2]
70 80 90 arr[2][0] arr[2][1] arr[2][2]
Method 2: Assignment: use the knowledge gained so far to construct the table of how arrays can be
represented.

UNIT NINE (9)


STRUCTURE AND UNION IN C++ LANGUAGE

25
COM 313 C++ Programming Language

What is Structure?
1) It is a collection of data of different data types
2) It is a user defined data type
3) Data can be int, char, float, double, etc. data types
4) We can access the members of structure by making a variable of structure
5) Struct is the keyword used to create a structure.
Syntax:
Structstructure_name
{//body of structopens(begins)
Data_type var1;
Data_type var2;
……………….
Data_typevar n;
};//body of struct closes and must end with (;)

What is Union?
a) It is a collection of data of different data type
b) It is user defined data type
c) We can access the member of union by making the variable of union.
d) Union is the keyword used to create a union.
e) Union doesn’t support multiple values simultaneously, but can store one value at a time.

Syntax:
unionstructure_name Example:
{ union student {
data_type var1; char name [200];
data_type var2;
introllNo;
………………………..
float marks;
data_typevar n;
};
};

UNIT TEN (10)


C++ FILE HANDLING MECHANISM
1. File handling is a mechanism to store the output of a program into a file and read from a file
on a disk permanently.
2. fstreamheader file is used to perform file operations in C++, this header file provides many
classes (ifstream, ofstream, fstream) to read from a file and write into a file.
3. ofstream: This data type represents the output file stream and is used to create files and to
write information to files.

26
COM 313 C++ Programming Language

4. fstream: This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files and even read
information from files.
The Various Operations on a File
File Opening: modes
In C++, file can be opened in different mode to perform read and write operations on a file. open()
function is used to open a file, open function takes two arguments…
open (const char *filename,ios::openmode mode);
Different file opening modes are given below:

S/NO MODE DESCRIPTION


1 ios:: in Open a file for reading
2 ios::out Open a file for writing
3 ios::app Append data to the end of the file
4 ios::ate File pointer moves to the end of the file but allows to writes
data in any location in the file
5 ios::binary Binary file
6 ios::trunk Deletes the content of the file before opening

UNIT ELEVEN (11)


OBJECT ORIENTED PROGRAMMING IN C++
OOP in C++ is what make the language a subset with varying feature from the original C Language.
The object oriented design of the language is what makes the language more flexible and friendly. In
this section, we shall take a look at some of the features of the language that make it Object Oriented
in nature.
Objects and Classes
What is Object?
Object is having states and behaviours in which state means what does it has and behavior means
what does it do. For example; a pen has:
States: ink, nib, needle, cap, etc.
Behavior: writing.
What is Class?
1. It is a collection of data members and member functions.
2. Data members are the variables used inside a class;
3. Member functions are the functions used inside a class;
4. It is also called User-defined data type.
Syntax of Class in C++

27
COM 313 C++ Programming Language

Important points to remember while making class programs:


 Declare variables with appropriate data type as per your requirement: For example to find the
area of rectangle, three variables are sufficient (height, width, and area)
 Declare function as per your requirements; for example, to find the area of rectangle, a single
function findArea() is sufficient.
 Create instance (object) of class to access the data members and member functions of the
class. Syntax: className objectName;
Example: Rectangle rec; where Rectangle is the name of the class while rec is the
object name.
 Accessing data members and member functions: Data members and member functions of a
class can be accessed using Dot(.) operator. For instance:
rec.height; //accessing data member
rec.findArea;//accessing member function

EXCEPTION HANDLING
Exception
To understand the exception firstly we should know about the error in prgram.Errors in
program can be categorized into two types.

1. Compile Time Errors


2. Run Time Errors

Compile Time Errors:- Errors caught during compiled time is called Compile time errors.
Compile time errors include library reference, syntax error or incorrect class import.
Run Time Errors:- The error that occours during the run time of program is called run time
error.
They are also known as exceptions. Hence we can say that exception is a runtime error that
occours because of user's mistake.
Reasons of Exception

28
COM 313 C++ Programming Language

Mismatched Input :Suppose that we are entering our name in place of age,causing
exception because age is of data type int and name will be string.
File does not exist :Suppose that we are reading a text file easy.txt and that file does not
exist in the system,causing exception.
Exception related to array :Suppose that the array size is 5 and we are inserting more than
5 elements,causing exception.
Divide by zero exception :When a number is divided by zero then the output will be
undefined(infinity).
Exception Handling
The process of handling the exception is called exception handling. There are three main
keywords are used to solve the problem of exception.
try block: It is the place where actual code is written and exception occurs. When the code
will lead to any error, that error/exception will get caught inside the catch block.
catch block: catch block is intended to catch the error and handle the exception condition.
We can have multiple catch blocks to handle different types of exception and perform
different actions when the exceptions occur.
throw statement: It is used to show the user defined message about the exception.

Syntax of try-catch
try{
// protected code
}catch(ExceptionNamee1){
// catch block
}catch(ExceptionNamee2){
// catch block
}catch(ExceptionNameeN){
// catch block
}

29

You might also like