0% found this document useful (0 votes)
46 views66 pages

C++ NOTES 3rd Semester-1

Uploaded by

FARMAN ULLAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views66 pages

C++ NOTES 3rd Semester-1

Uploaded by

FARMAN ULLAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

1

Prepared By: FARMAN ULLAH DEPARTMENT: B.S


Mathematics:
Semester: 3rd instructor : Shaheen Ullah MS
Computer Science
Subject: C++ language
Introduction to Computer Programming
Lecturer 01
What is Programming?
 Programming means telling a computer what to do.
 Provide (a computer or other machine) with coded
instructions for the automatic performance of a task.
 However, computers do not understand arbitrary
instructions written in English, Urdu, French, Spanish,
Chinese, Arabic, etc..
 Instead, computers have their own languages that they
understand.
 Each of these languages is known as a programming
language
What is Programming Language ?
 A programming language have a set of words, rules and
tools that are used to explain (or define) what you are
trying to accomplish.
 There are many different programming languages just as
there are many different "spoken" languages.
 Traditional programming languages were known as
structural programming languages (e.g.,C, Fortran,
Pascal, Cobol)
2

 However, object-oriented programming languages have


become more popular (e.g., JAVA, C++, C#)
Application of Programming in Mathematics
1. Microsoft Mathematics.
 Microsoft Mathematics is a free software offered by
Microsoft that helps math students to be able to solve
complex math problems in no time.
 It especially helps the student with algebra and equips
them with a graphic calculator to be able to draw 2D and
3D diagrams.
 It also helps them to solve a complex equation in a step by
step manner.
 Overall, this software helps students with elementary math
and science.

2. Math Editor
 Math Editor can be the right solution for you as this
powerful freeware can help you to create mathematical
equations with Greek symbols, alpha, beta, square root and
other symbols in a matter of minutes and smoothly.
3

3.Photo math
 It is one of the most useful and awesome android app.
 Solve complex math equations and large calculations by
just taking a Picture via this app.
 It supports quadratic equations and inequalities problems
also.
 You can also check the history of past solved math
problems by the app.
 Add to it, it also gives steps of solving the problem.
4

4.Free Universal Algebra Equation Solver


 Free Universal Algebra Equation Solver is a boon on earth.
 Get step by step guidance on those complex algebraic
equations that vary from logarithmic, holding absolute
value, ration, irrational, with parameters or exponential.
 This free program covers all you Algebra problems in
Algebra 1, Algebra 2 and Algebra 3 classes
 You get complete guidance for any complexity level n
verbal and written explanations.

History of C++ (see plus plus)

 In 1967. BCPL(basic combined programming


language)as developed by Master Martin Richards.
 The BCPL Language was used to write operating
systems and compilers.
5

 After two years, Ken Thomson developed B


programming language.
 B programing language had advance features as
compared to BCPL.
 The UNIX operating system was first developed in B in
1970 at Bell Laboratory.
 Both B and BCPL were type less languages.
 In 1972 Dennis Ritche developed C language at Bell
Laboratory.
 The C language was an advanced version of B language.
 It had many Important concepts of BCPL and B
languages.
 Like data typing, classes etc.
 The next version of UNIX operating system was revised
and written in C.
 A program written in C can be run on any computer.
 In early 1980s, C++ was developed by Bjarne
Stroustrup
 In early 1980s, C++ was developed by Bjarne
Stroustrup.
 It was an extension of C.
 It enabled programmers to improve the quality of code .
 It included Object Oriented Programing.
Structure of C++ Programs
A C++ program consist of three main parts. They are:
1. Preprocessor Directives
2. The main() function
3. C++ statements
1. Preprocessor Directives
6

 The instruction that are given to the compiler before the


beginning of the actual program are called Preprocessor
Directives.
 These are also called Compiler Directives.
 The preprocessor directives consist of instruction for the
compiler.
 The compilers adds special instructions or code from
these directives into the program at the time of
compilation
These preprocessor directives normally start with a number sign
(#) and keyword (include) or (Define).
For example.
#include<iostream.h>
#include<conio.h>
Header File
Header file in C++ source file that contains definitions of
library function/objects.
Header files are added into the program at the time of
compilation of the program.
The Preprocessor directive “include” is used to add a
header file into the program.

The name of the file is written in angle brackets (<>)after the


#include directive .
7

For example:
#include<iostream.h>
#include<conio.h>
#include<math.h>

2. Main () function.
o The main() function indicates the beginning of the C++
program.
o The main() function must be included in every C++
program.
o When a C++ is executed the control goes to the main()
function.
o The statement within this function are the main body of
the C++ program.
o If main() function is not included the program is not
compiled and error message is generated.
The syntax of main function is:
Void main()
{
Statement….
}
3. C++ Statements
 The statement of the program are written under the void
main() function between the curly braces { }.
 Each statement in C++ ends with a semicolon(;).
 C++ is a case sensitive language.
8

 The C++ statement are normally written in lowercase


letters but in some cases can also written in uppercase.
Void main()
{
C++ Statement….
}

Flowchart
What is Flowchart?
 A flowchart is a type of diagram that represents an
algorithm.
 It represents the steps of an algorithm with the help of
shapes
 and their order by arrows connecting the shapes.
It consist on following components.
1. Process
2. Rectangle
3. Diamond
4. Arrows
5. oval
Flowchart Symbols in C++
Input / Output:(Parallelogram)
 Parallelogram symbol is used to represent an input or
output step.
 Input statement is used to get input from the user.
9

 Output statement is used to display a message to the


user or display a value

COUT CIN

Process:
 Rectangle symbol is used to represents a process step.
 A process may be a complex or simply an assignment
statement.

Sum=c + d

Selection
 Diamond symbol is used to represent a selection.
 A condition is given in the diamond.
 The flow of control from diamond may be go in two
directions.
 one direction if the condition is true and the second
direction if the condition is false.
10

M>6

Start / End
Oval used to represent the start or end of the flow chart.

Start End

Flow Lines(Arrow symbols).


Used to represent the direction of flow in the flowchart.
Four types of flow lines.

Connector (circle symbol).


used to combine different flow lines.
It is used when two or more flow symbols comes from different
directions and move to one direction.
11

START

INPUT ab

The following flowchart represent step by steps adding


two numbers
SUM a+b
Statement Terminator
 Each C++ statement is terminated by a symbol,
called a semicolon (;). DISPLAY SUM

 It represents the end of the statements in the


programming codes to the compiler.
END

Comments and their syntax in C++


Comments are parts of the source code ignored by the
compiler.
It is used to allow the programmers to insert notes or
descriptions within the source code.
C++ supports two types of comments.
Single ling comments e.g. //

Multiline comments e.g. /* */


Variables in C++
Variable
 A name of memory location which are used to store data
called variables.
12

 It is the basic storage unit in programming.


 When a variable is declared, a block of memory is allocated
for that variables.
Variables declarations `.
 The process of specifying name and its types called
variable declaration.
 Variable must be declared before they are used in the
program.
 It can be declared anywhere in the program before its use.
 Declaration of the variable provides the information to the
compiler about the variable.
Syntax:
Data_ type variable _name;
Variable initialization
 The process of assigning a value to variable at the time of
declaration called variable initialization.
 The equal sign = is used to initialize a variable.
 Variable name is given on the left side and value is given
on the right side of equal sign.
Syntax:
Type _name variable= value
Rules for writing Variables Names.
1. The first of variable name character must be an
alphabetic character. e.g. x, abc, X, ABC
2. Underscore can be used as first character of variable
name or in the middle of variable name. e.g. _marks,
total marks.
13

3. Blank spaces are not allowed in a variable name. e.g.


total marks
4. Special characters such as arithmetic operators, +,* #,>
cannot be used in a variable name.
5. Reserve words cannot be used as variable names.eg.
cout, int, void etc.
6. Same variable names cannot declared.

LECTURE 4
CONSTANT
What is Constant?
Constants is a quantity that can not be changed during
program execution.
Types
1. String constant
2. Numeric constant
3. Character constant
1. String constant?
It is sequence of alphabetic characters, digits and special
symbols written in double quotation marks.
Maximum length is 256 characters.
Examples:
“Pakistan”
“5454”
“44_street Hayatabad Peshawar”
2. What is numeric constant?
It consist of positive and negative numeric values.
Types
1. Integer
2. Floating point constant
3. Decimal constant
14

4. Hexadecimal constant
3. Character constant?
Any character written in single quotes is called
character constants.
All alphabetic characters, digits and special symbols
can be used as a character constant.
Examples:
‘A’,
‘1’
What is datatype?
All variables use data-type during declaration to
restrict that type of data to be stored.
Data types describe the nature of the variable
Primitive data Types:
These data types are built-in or predefined data
types and can be used directly by the user to declare
variables.
Integer Datatypes:
 Integer datatype used to store numeric values
with no decimal point.
 It include positive and negative values.
 It takes two or four bytes in memory.
Types:
Int 2bytes
15

Short int 2bytes


Long int 4bytes
Float/real datatypes:
The numeric values with decimal point is called
float/real data types.
It include both positive and negative values.
Types
Float 4 bytes
Double 8 bytes
Long double 10 bytes
Character Datatypes
 It is used to store character values.
 It takes 1 byte in memory.
 It is used to represent letters, numbers or
punctuation marks and a few others symbol

Keywords
16

Reserved Or Keywords:
The words that are used by the language for special purpose are
called keywords or reserved words.
Examples:
Int
void.
If
While etc.
Escape
What is Escape Sequence?
 Escape sequence are special character in control string to
modify the format of the output.
 These character are not displayed in the output.
 The character are used in combination with backslash “\”.
 The backslash “\” is called escape character,
Different escape sequences used in C/C++ languages are as
follows.

Example Escape sequence Purpose

\a Alarm

\b Backspace

\n New line

\r Carriage return

\t Tab

\’ Single quote

\” Double quote
17

Input and Output


Input
 The process of giving something to computer is know is
input.
 The input is mostly is given by keyboard.
 A program may need certain inputs from the user for
working properly.
 The term standard input refers to the input via keyboard.
Eg.
Cin>>marks;
Output
 The process of gating something from computer is know is
output.
 The output is mostly displayed on monitor.
 The term standard output refers to the output displayed on
monitor.
 The result of a program is the output of that program.
Eg.
Cout<<“Pakistan Zindabad”;
Arithmetic operators ( +, -, *, /, % )
18

Assignment statement
What is Assignment statement?
A statement that assign a value to a variable is called assignment
statement.
Syntax
variable=expression
 Examples:
 A=3
 B=5
 C=a+b
19

Compound assignment statement


What is Compound assignment statement?
An assignment statement that assign a value to many variables is
called compound assignment statement.
Examples:
A=b=5
X=y=x=5
C++ provides compound assignment operators that combine
assignment operator with arithmetic operators.
Syntax:
Variable op=expression;
Examples:
N+=10 is equivalent to N=N+10;
N-=10 is equivalent to N=N-10;
N*=10 is equivalent to N=N*10;
N%=10 is equivalent to N=N%10;
N/=10 is equivalent to N=N+10;
Example
20

Increment operator
What is an increment operator?
 The operator that is used to increase the value of a
variable by 1 is called increment operator.
 It is denoted by symbol ++.
 It is also called unary operator that works on a single
value.
Decrement operator
What is decrement operator?
 The operator that is used to decrease the value of a
variable by 1 is called decrement operator.
 It is denoted by a symbol --
 Two forms of increment operators
 Prefix form
 Postfix form
21

Two forms
Prefix form
In prefix form, the increment operator is written before variable
as follows.
E.g. ++a;
Postfix form
In postfix form, the increment operator is written after the
variable is follows.
E.g. a ++;
Difference between postfix and prefix increment
When increment operator used independently, prefix and
postfix form work similarly.
For example the result of a++ and ++a is same.
But when increment operator used in a large expression
with other operators, prefix and postfix form work
differently.
For Example the results of a=b++ and a=++ b are different.
 The statement a=++b contains on two operators ++ and =.
It works in following order.
1. It increment value of b by 1.
2. It assign the vale of b to a.
 The above statement is equivalent to the following two
statements.
1. ++b;
22

2. a=b;
 In postfix form the statement a=b++ works in the fowling
order.
 It assigns the value of b to a.
 It increments the value of b by 1.
 The above statement is equivalent to the following two
statements,
 a=b;
 b++

Conditional Statements
Conditional Statements
The statement of a computer program are executed one
after the other in the order in which they are written. This is
known as sequential execution of the program.
The order of execution of the statements in a program can
be changed.
This is done the help of conditional statements.
The conditional statements are used to execute (or ignore) a
set of statements after testing a condition.

Types of Conditional Statements


1. “If” statement
2. “If else” statement”
3. “switch” Statement

1. “if statement”
What is “If” statement ?
23

The “if statement” is used to execute a set of statement


after testing a condition.
The “if statement ” evaluates a condition .
If the condition is true, the statements (or set of statements)
following the “if statement” is executed.
If the given condition is false, the statement (or set of
statements) following the “if statement” is ignored and the
control transfers to the next statement.
The syntax of the “if statement”
If (condition)
statements
The general syntax for more than one statement.
If (condition)
{
Statement-1
Statement-2
Statement-3
}
Statement—n
Program example
 #include<iostream>
 using namespace std;
 int main()
{
 int a, b;
 a=10;
 b=50;
24


 if (a>b)
 cout<<"welcome to GDC Dir upper"<<endl;
 cout<<"Okay";}
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"enter your age\n";
cin>>age;
if (age<20)
cout<<"your are under age";
}

2. “if else statement”


 “if else statement” is another type of if statement.
 It executes one block of statements when the condition is
true and other when it is false.
 In any situation, one block is executed and the other is
skipped.
 Both blocks of statement can never be executed.
 Both blocks of statements can never be skipped.
Syntax for single if-else statement
25

If (condition)
{
Statement;
Else;
Statement;
}
Syntax for Multiple if-else statement
{
Statement 1
Statement 2………..statement N;
}
else
{
Statement 1;
Statement 2……statement N;
}
examples
1. Program that inputs a year and finds whether it is leaf
year or not using “if else statement” for single if-els
structure.
#include<iostream>
using namespace std;
26

int main()
{
int year;
cout<<"enter the name of the year\n";
cin>>year;
if (year %4==0)
cout<<"this the leaf year\n";
else
cout<<"this is not the leaf year";
}
2. Program that inputs a number and finds whether it is
even or odd using “if else statement” for multiple
statement.
#include<iostream>
using namespace std;
int main()
{
int num;
cout<<"enter your number\n";
cin>>num;
if (num %2==0)
cout<<"you are entered an even number\n";
27

Cout<<num<<“ is an even number”<<endl;


}
else
{
cout<<"you are entered the odd number";
cout<<num<<“is an odd number“<<endl;
}
Assignment:
Write a program that inputs salary and grade. It adds 70% bonus
if the grade is greater than 17. It adds 35% bonus if the grade is
16 or less and then shows the total salary.
Submission date: today 12:00 pm

3. switch statement”
 “switch statement” is used when multiple choices are given
and one choice is to be selected.
 The “nested if-else” structure becomes complicated in
multiple choices.
 The “switch statement” is used in such situations.
 Only one condition is given in the ““switch statement” and
multiple choices are given inside the main body as cases.
 The “switch statement” evaluated an expression and returns
a value.
 One of the choices or cases in the “switch statement” is
executed depending upon the value returned by the
expression.
28

 The returned value is compared with the constant values


given in the class.
 If the returned value matches the case value, the statements
under that case are executed.
Syntax switch statement
Switch (expression)
{
Case const-1:
statements;
Break;
Case const-2:
statements
Break;
Case const-n:
statements;
}
 #include<iostream>
using namespace std;
int main()
{
char grade= 'C';

switch (grade)
29

case 'A':
cout<<" Excellent!"<<endl;
break;
case 'B':

cout<<" Outstanding!"<<endl;
break;

case 'C':
cout<<" Good"<<endl;
break;

case 'D':
cout<<" can do better"<<endl;
break;
case 'E':
cout<<" just passed"<<endl;
break;
case 'F':
30

cout<<" Failed"<<endl;
break;
default:
cout<<" invalid grade"<<endl;

}
cout<<"ok"<<endl;
}

LOOP
A loop is a control structure that repeatedly execute a sequence
of statement until condition is true. Loops are also called
repetition control structures in c++.
There are three types of loops in c++ which are for, while and
do while.
1. For loop
A for loop is used to execute one or more statement for a
specific number of times. It is also known as counter loop.
Syntax
For(initialization; condition; increment/decrement)
{
Block of statement
}
31

2. While loop
What is While loop?
 It is a conditional loop statement.
 It is used to execute a statement or a set of statements as
long as the given condition remains true.
 When “while loops statement is executed the computer first
evaluates the given condition. if the given condition is true
the statement or set of statements in the body of the while is
executed again and again until the condition become false.
when condition become false the control go outside of the
body.
Syntax:
while (condition)
{
Statement;
}

#include<iostream>
using namespace std;
int main()
{
32

int i= 1;
while(i<=10)
{
cout<<"how are you"<<endl;;
i++;
}
3. do while loop
 do while loop is a conditional loop statement that executes
a block of statement at least once, and then repeatedly
executes the block, or not, depending on a given condition
at the end of the block.
 First, the code within the block is executed, and then the
condition is evaluated.
 If the condition is true the code within the block is executed
again.
 This repeats until the condition becomes false. Because do
while loops check the condition after the block is executed,
the control
structure is
often also
known as
a post-test.
Syntax
Do
{
Statements;
33

}
While (condition

Program
#include<iostream>
using namespace std;
int main()
{
int j= 6;
do{

cout<<j<<endl;
j++;
}
while(j<=5);
}

Functions
What is Function?
34

 A function is a set of statement that take input, do some


specific computation and produce output.
 A Function is name of block of code that performs some
action.
 The statement are executed what it is ‘called’ by its name.
 Each function has a unique name.
 The function are used to accomplish the similar kinds of
tasks again and again without writing the same code again
Advantages of Functions:
 A large program is divided into smaller logical blocks.
 This approach will make the code clean and easy to
understand.
 Reuse same piece of code multiple times, which saves time
and reduces code lines.
 Individual code can easily be tested.
 In case of any change in the program, the programmer don't
need to change the whole program.
Two types of functions.
1.User defined functions.
2. Built in Functions.
1.User Defined functions.
A type of function written by programmer is known is user
defined functions.
User defined function has a unique name .
A program may have many user defined functions.
2. Built in Functions.
35

A type of function that are available as a part of language is


known as built in function or library functions. These
function are ready made programs.
These functions are stored in different header files
Built In Functions Examples:
M e tho d De sc rip tio n Exa m p le
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
Fig . 3.2 M a th lib ra ry func tio ns.

A user defined functions consist of the following.


1. Function declaration
2. function definition

Function declaration or function prototype:


 Function declaration is a model of a function.it is also
called function prototype.
36

 Its provides information to the compiler about the structure


of the function to be used in program.
 Its ends with a semicolon (;).
 Function declaration consist of the following parts.
 Return type function name (parameters);
Syntax:
return-type Function-name(parameters);
E.g: int sum(int a,int b);

Function Definition
 A set of statements that explains what a function does is
called function definition.
 The function definition can be written Before main
function, After main function or in separate file.

Function definition consist of two parts:


37

1.Function header:
2. Function call
1.Function header:
The first line of function definition is known as function
header or function declarator.
It is similar to function prototype.
The only difference is that it is not terminated with
semicolon.
1.Function Body:
The set of statement which executed inside the function is
know is function body.
The body of function appears after the function declarator.
38
39

Lecture 12

Basic terminology
40

One Dimensional array


41
42
43

Two Dimensional's Arrays


44
45

Strings
what is Strings
The sequence of characters enclosed in quotation marks and is
used to handle non numeric data i.e. name, address etc. are
called Strings.
In computer programing strings are attached to variables.
General syntax
data type name – of - string [size of string];
examples
char str[20];
46

Types of Strings
47
48

Lecture 14
Structure
What is Structure
 A structure is a collection of multiple data types that can be
referenced with single name.
 It many contain similar or different data types.
 The data items in a structure are called structure elements,
members or fields.
 the difference between an array and structure is that array
consists of a set of variables of same data type.
 However a structure may cost of different data types.
Declaring a Structure.
 A structure is declared by using the keyword struct
followed by the struct name.
 The structure members are defined with their type inside
the opening and closing braces {}.
General syntax.
Struct Sruct__name
49

{
Data – type 1 identifier 1;
Data _type2 identifier 2;
}
Example.
struct Student
{
Int RollNo, Marks,
float Average;
char Grade;
};
Defining Structure Variable
The structure variable can be defined after the declaration of a
structure.
General syntax
Struct_Name identifier;
Example
Student Ali;
Accessing Members of Structure Variable
Any member of a structure variable can be accessed by using
dot operator.
50

The name of the structure variable is written the left side of the
dot.
The name of member variable is written on right side of the dot.
The dot operator is also called member access operator.
Syntax
struct _variable member_ varaible
Example
Student Ali
Ali .RollNo=33;
Ali .Marks= 877;
Ali. Average=66.8;
Ali. Grade=‘A’;
Example
#include<iostream>
using namespace std;

struct Student
{
51

int RollNo;
int Marks;
float avg;
char grade;
};

What is Pointer
 A Pointer is a variable in C++ that holds the address of
another variable.
 The reference operator is used to access the memory
address of a variable and store it in a pointer.
 In memory, each and every variable has an address
assigned to it by the compiler and if a programmer wants to
access that address, another variable called “pointer” is
needed.
Declaring a pointer
The method of declaring a pointer is same as declaring a simple
variable.
An asteric ‘*’ is used in the decoration that indicated that the
variable is a pointer variable.
General syntax
Data type *variable;
Examples
int *p;
52

char *p;
Reference operator &
 To understand C++ pointers, you must understand how
computer stores data.
 When you create a variable in your C++ program, some
space of space of the compute memory is assigned to it.
 The value of this variable is stored in the assigned location.
 To know the location in the computer memory where the
data is stored, C++ provides the & reference operator.
 This operator returns the address of the variable.
 For example, if X is a variable, &x returns the address of
the variable.
 Example code
 float x=3;
 Float *fPointer;
 fPpointer =&x; // assign address of x to fPointer;
Program example
#include<iostream>
using namespace std;
int main()
{
float x;
float *fPointer;
fPointer= &x;
cout<<"the address of x="<<&x<<endl;
cout<<"the value of x="<<x<<endl;
53

cout<<"the value of fPointer="<<fPointer;


}
Dereference Operator *
 Pointers are used to store the address of another variable.
 If we want to store the value of the variable through the
pointer, then we need a special type of operator called
dereference operator denoted by asterick *.
 To use dereferce operator, Precede the pointer variable with
asterick * symbol.
 This operator can be read as “value pointed by”.
Example
#include<iostream>
using namespace std;
int main()
{
int n;
int *pn; // defines a pointer to n
pn=&n; // pn stores the address of n
int valueN;
valueN= *pn;
cout<<"the address of n="<<&n<<endl;
cout<<"the value of n="<<n<<endl;
cout<<"the value of pn="<<pn<<endl;
54

cout<<"the value of *pn="<<*pn<<endl;


}

What is OOP
 Object Oriented Programming (OOP) is a programming
technique in which a program is written on the basis of
objects.
 An object is a collection of data and functions.
 Object may represent person, thing or place in the real
world.
 In OOP, data and all possible functions on data are
grouped together .
 OOP is a powerful technique to develop a software.
 Examples
C++, Smalltalk and java etc.

Feature of Object-oriented programming


Objects
OOP provides the facility of programming based on objects.
Objects is an entity that consist of data and functions.
Classes
55

Classes are designed for creating objects. OOP provides the


facility to design classes for creating different objects . All
properties and functions of an object are specified in classes.
Real World Modeling
OOP is based on the real-world modeling. As in real world
things have properties and working capabilities. Similarly,
objects have data and functions. Data represents properties and
functions represents working of objects.
Reusability
 OOP provides ways of reusing the data and code.
 Inheritance is a technique that allows a programmer to use
code of existing program to create a new program.
 Information Hiding
 OOP allows the programmer to hide important data from
the user. It is represented by encapsulation.
Polymorphism
Polymorphism is an ability of an object to behave in multiple
ways.
Objects
What is Object
 An object represents an entity in the real world such as
person, things or concept etc. an object consist on the
following two things.
 Properties: the characteristic of an object
56

 Functions: are the actions that can perform by an object.


 Examples:
 Physical objects such as car, bus , truck etc.
 Properties: name, model, color, year etc.
 Functions: start, stop accelerate and reverse etc.
Classes
What is Class
 A collection of objects
 A class is a blueprint for creating an objects.
 It is logical constructs that represents the physical objects.
 with same properties and functions is known as class. A
class is used to define the characteristics of the objects. It is
used as a model for creating different objects of same type.
 For example a class person can be used to define the
characteristics and functions of a person.
 It can be used to define many objects of a person such as
Asad, usman etc.
Classes and Objects
57

Declaring a Class
A class is declared in the same way as structured decelerated.
General syntax
Class identifier
{
Body of the class
58

};
Example
Class Test{
Int n;
Char c;
}
Program
Example

What is File?
 Bytes stored on Hard disk (secondary storage device).
 Text files
 Image files
 Audio files
 Video files
59

 Excel files etc.


 File is a collection of related records.
 Records are stored through file in hard disks permanently.
What is File Handling?
1. File handling concept in C++ programming language is
used for store a data permanently in computer.
2. Using file handling we can store our data in secondary
memory (Hard disk).
Why use File Handling?
1. Memory is volatile.
2. Any data that you key in by keyboard while program is
running is also volatile.
3. For permanent storage.
4. The transfer of input data or output data from one
computer to another can be easily done by using files.
60

File Operations
Operations on File
1. Create
2. Open
3. Read
4. Write
5. Close
Classication of File Handling
61

Basic Structure
 #include<iostream>
 Step1
 #include<fstream.h>
 \\ ifstream, ofstream
 Using namespace std;
 Int main()
{
 Step 2
 Ofstream rizawanfile;
 Myfile.open(“D:\\ali.txt”);
 \\cout<<“Hello”;
62

 rizwanfile<<“Hello”;
Opening a file
How open a File in C++?
Syntax:
Header file <fstream>
Ifstream object name; (ofstream, fstream)
Ifstream: open to read only
Ofstream: output to a file on disk
Fstream : both input and output
 General syntax
 Object name. Open(“file name”)
 E.g myfile.open(“shaheen”)
 Open funtion is used to open file.
 My file is the name of object.
Modes of Opening a File
 While opening a file, we tell the compiler what we want to
do with it.
 We want to read the file or write into the file or want to
modify it.
63

 In order to open a file in any desired mode the member


function open() should take mode as an argument along
with the file name.
Syntax:
open(filename, mode);
Different Modes of Opening a file
 Ios::In (reading a file)
 Ios:: out (writing a file)
 Ios:: ate (move control to the end of file)
 Ios:: app (append output to end of the file)
Ios:: trunc (remove contents before opening
 Combining two modes
 OR operator (|)
 For example
 Open(“file.txt”, ios:: out | ios::trunc)
 Open(“file.txt”, ios:: out | io)

Default Modes
 Ifstream ios::in
 Ofstream ios::out
64

 Fstream ios::in | ios::out


Reading a File
How to Read a File in C++?
For example: write a program to read from file.
1. Read first word.
2. Read multiple words
3. Read all the text
Program example to read single words in c++
 #include<iostream>
 #include<fstream>
 Using namespacd std;
 Int main()
{
 Char file
 Ifstream college;
 College.open(“filename”);
 College>>file;
 Cout<<file;
}
Program example read multiple words in c++
65

#include<iostream>
#include<fstream>
Using namespacd std;
Int main()
{
Char file[40];
Char file1[40];
Ifstream college;
College.open(“filename”);
College>>file>>file1;
Cout<<file<<“ ”<<<<file2;
}
Program example read all the text in c++
#include<iostream>
#include<fstream>
#include<string>
Using namespacd std;
Int main()
{
string file[40];
66

Ifstream college;
College.open(“filename”);
getline(college, file)
Cout<<file<<;
}

You might also like