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

HSSC II Computer Notes Theory

The document provides a comprehensive overview of operating systems, detailing their functions, types, and differences, including Command Line Interface (CLI) and Graphical User Interface (GUI). It also covers the System Development Life Cycle (SDLC), outlining its phases, importance, and stakeholders involved in system development. Key concepts such as process management, memory management, and the distinctions between single-user and multi-user operating systems are discussed.

Uploaded by

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

HSSC II Computer Notes Theory

The document provides a comprehensive overview of operating systems, detailing their functions, types, and differences, including Command Line Interface (CLI) and Graphical User Interface (GUI). It also covers the System Development Life Cycle (SDLC), outlining its phases, importance, and stakeholders involved in system development. Key concepts such as process management, memory management, and the distinctions between single-user and multi-user operating systems are discussed.

Uploaded by

sarakhanahson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Punjab College H-11/4, Islamabad HSSC-II

Chapter # 01: Operating System


Operating System
• It is a program that manages the resources (software & hardware) of computer
system.
• It controls the executing of application programs.
• It acts as an interface between user and hardware.
• Example: DOS, Windows, Macintosh, Unix
• Tasks:
o Load and execute software.
o Controls the operation of storage devices.
o Manage the files and folder.
o Manages the I/O devices.
o Performs network operations.
o Detects hardware failure.
o Provide security.
o Allow multitasking.

Command Line Interface (CLI)


• Had to enter command for executing tasks.
• Difficult to memorize commands.
• Also called Text based interface.
• Now it is the part of an operating system.
• Example: DOS

Graphical User Interface (GUI)


• In GUI, user give commands through icons, menus and buttons.
• It is user friendly.
• It is easy to use and learn.
• No need to memorize commands.
• Example: Windows 10, Mac OS X

DOS
• 1970s
• Microsoft, Inc.
• Disk operating System
• Command line interface
• Single tasking
• Single user
Command Description
DIR To display list of files or folder
COPY To copy file or folder
CD To change folder

Department of Computer Science 1 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

RENAME To rename a file

FORMAT To format a disk


DEL Delete a file or folder
Windows
• 1980s
• Microsoft, Inc.
• Graphical user interface
• Multitasking
• Multiuser
• Most commonly used.
• Windows 10, windows xp

Macintosh
• Developed by Apple Inc.
• Installed on Apple computers.
• More secure than windows
• Hardware and software work together
• Latest version is OS X
• More expensive
• Limited application software's
• Not widely used OS

UNIX
• Early 1970
• Bell laborites
• Ken Thompson & Dennis Ritchie
• Developed in c
• Greater processing power
• Better security
• Available for microcomputers to mainframe computers

Difference between dos and windows


DOS Windows
CLI GUI
Single user Multiuser
1970 1980
Not user friendly User friendly
Commands are entered Commands through icons, menus and buttons
Single tasking Multi-tasking
Small in size → need less space in Big in size → need more space in memory
memory
Need to memorize commands No need to memorize commands
Fast in execution Slow in execution

Department of Computer Science 2 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

More secure Less secure

Department of Computer Science 3 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Types of Operating System


Batch Operating System
• It is software that groups together same type of jobs in batches and automatically
executes them one by one in given sequence.
• Easy & Efficient way for executing same types of jobs.
• Example: Bank statements etc.

Multiprogramming Operating System


• It is software that loads multiple programs in main memory and executes them one
by one.
• Other programs wait until running program is terminated or blocked.
• If first program is busy it will execute the second program in queue.
• Does not minimize the response time of CPU.
• Process may not get equal chance of execution.
• Example
o User loads MS word and c compiler but it will run only one at a time
• Advantages
o Save users time by loading programs in main memory
o Runs program quickly.
o Effective utilization of CPU
• Disadvantage
o Need more RAM.

Multitasking Operating System


• It is software that loads multiple programs into the memory and executes them at the
same time by rapidly switching the cpu between them
• OS keep track of the process previous status during switching without losing
information
• It is extension of multiprogramming.
• Look likes all programs are executing at same time
• Maximum utilize the CPU time.
• Minimize the response time of CPU.
• Process gets equal chance of execution.

Time Sharing Operating System


• It is software that shares CPU time between multiple programs.
• Give short period of time to each program (time slice or quantum)
• All users get the impression of having their own CPU
• Used in mini and mainframe computer.
• Advantages
o Memory is better managed.
o Programs can run in background.
o User can run multiple programs at the same time.
• Disadvantages
o Limitation of memory

Department of Computer Science 4 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

o CPU heat up.

Difference between Multiprogramming and Time Sharing/Multitasking OS


Multiprogramming OS Time Sharing/Multitasking OS
Loads multiple programs and executes them Loads multiple programs and executes by
one by one. rapidly switching between them.

Does not Minimize the response time of CPU. Minimize the response time of CPU.

Process may not get equal chance of Process gets equal chance of execution.
execution.

Real Time Operating System


• It is software that run real time applications which required an immediate response
Executes special applications within specified time with high reliability.
• Example: space research program, traffic signals

Multiprocessor Operating System


• It is software that control and manages the operations of two or more processors
within single computer system.
• All CPUs share same main memory and i/o devices.
• All CPUs executes a single program.
• Improve processing speed.
• Its architecture is difficult to design.

Parallel Processing Operating System


• It is software that executes programs developed in parallel programming language.
• Uses many processes at the same time.
• Calculations are divided into small tasks and processed by multiple processors at same
times
• Used in super computers (thousands of processors to perform complex calculations)

Distributed Operating System


• It is software that manages the operation of distributed systems
• In distributed system, the operations of big task are distributed on different
computers in a network.
• Automatically balance the load on different computers
• Fast execution of programs

Embedded Operating System


• It is built in operating system for performing specific task.
• Embedded in hardware of device at time of manufacturing.
• Control operation of devices
• Run automatically when device is turned on.

Department of Computer Science 5 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Examples: ATM, digital washing machines, digital clocks etc.

Difference between Single User and Multiuser OS


Single User Operating System Multiuser Operating System
Only one user interacts at a time Multiple users interact at a time
One user can access the resources Multiple users can access the resources
from different terminals
Can’t become part of network Can directly become part of network
Used on microcomputer Used on minicomputer and mainframe
Example: dos, windows 3.X, windows 95 Example: Unix, windows 7, mac os x
etc.

Functions of Operating System

Process Management
• A process is a program in execution.
• Every process needs resources for completing its task.
• Resources: I/O devices, CPU, memory etc.
• Process management is part of OS.
• It manages the allocation of resources to process in main memory.
• It also describe the state and resource ownership.

As the average time of BCA is minimum so the CPU sent the processes in this sequence.

Memory Management
• It is a part of OS.
• Control the operations of main memory.
• Manage the Allocation and deallocation of memory space.
• Provide protection to all programs.
• Swap In: loading of program from secondary storage to main memory.
• Swap Out: program is taken out from main memory to secondary storage

Department of Computer Science 6 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Secondary Storage Management


• It is also part of operating system
• Manage the free space and data on secondary storage devices
• Manage the allocation or deallocation of storage space.
• Example: Program A is ready to be stored in Hard disk(HD), Storage manager will look
for free space in HD and assign space to it. If space is not available, it will prompt user
to empty some space.

File Management
• It is a part of operating system.
• Manages the files and folders on storage devices.
• Allow the user to perform different operations → file manipulation.
• File manipulation → create, copy, rename, delete etc.
• Allow user to read, write, open or close file or folder

I/O Management
• It is also part of operating system
• Control all the input/output operations during execution.
• Manages the input output devices.
• Improve the performance of computer system.
• Example: printer

Protection system
• It is a part of os.
• Protect resources from unauthorized access.
• Ensures that each resource is used according to privileges.
• Allow administrator to create different user accounts.
• Enforce restrictions.
• Provide security by providing passwords.

Network Management
• It is the part of a computer operating system.
• Monitor and manages the resources of computer network.

Department of Computer Science 7 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Allow to create user groups and Assign privileges to them


• Shares resources among different users
• Detects and fixes the network problems

Command Interpreter
• It is a part of os
• Protect resources from unauthorized access.
• Ensures that each resource is used according to privileges.
• Allow administrator to create different user accounts.
• Enforce restrictions.
• Provide security by providing passwords.

Process
• Executable source code written in high level language saved on disk is called program.
• Part of program in execution
• Scheduled and controlled by operating system.
• Represent basic unit of work.
• Need resources to complete task.
• Process is dynamic instance of program.
New
This is the first state when process is created.
Ready
In this state process is admitted to RAM and waiting to be assigned to the processor.
Running
In this state process is dispatched and being executing by the processor.
Waiting/blocked
In this state process is waiting for some resources like I/O device or file.
Terminated
In this state process is terminating after completing its execution.

Thread
• Basic unit of execution

Department of Computer Science 8 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Also called lightweight process


• Behave like a process within a process.
• Set of instruction within process executes independently.
• Every process has at least one thread
• Processes may have multiple threads.

Difference between Process and Thread


Process Thread
Program in execution Subset of process
Has its own copy of data segment Direct access to data segment of process
Change in process does not affect other Change in thread may affect other threads
processes
Run in separate memory Run in shared memory
Controlled by OS Controlled by programmer
Independent Dependent on parent process

Multithreading
• It allows single process to run multiple threads at the same time.
• Threads within process execute independently from each other.
• The main purpose of multithreading is to execute two or more parts of a program, to
maximize the utilization of CPU.
• Example:
o MS word runs multiple threads i.e., typing a paragraph, checking spelling
mistakes etc.
o Web servers handles every request by different thread.

Multiprocessing
o Execute more than one process on multiple processor machine at the same
time.
o Uses more than one CPU’s time.
o Increase the processing speed of the computer

Difference between multiprogramming and multithreading


Multiprogramming Multithreading
Loads multiple programs and executes them Executes multiple threads at a time
one by one
Fast switching between different programs Single process run multiple threads
Allow execution of complete program Allow execution of part of program
Effectively utilize the CPU time Maxima utilize the CPU time
Example Example

Department of Computer Science 9 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 02: System Development Life Cycle

System Development Life Cycle (SDLC)


• It is the problem-solving process for creating or altering information systems.
• It consists of models and methodologies that experts used to develop alter and maintain the systems.
• It produces the system with highest quality and lowest cost in the shortest time.

A System
• A system is a set of components that is used for collecting, creating, storing, processing and
distributing information.
• It may have following components: Hardware, Software, Users, Data
• It can be developed by applying a set of methods and procedures in a proper sequence to carry out
some specific task.

Importance/Purpose/Objectives of SDLC
• It delivers high quality software which meet the user requirements
• It delivers cost-effective system.
• It maximizes the productivity.
• Provide strong management controls over the projects.

Stakeholders of SDLC
• They are the entities or groups which are either within the organization or outside the organization
who sponsor, plan, develop or use a project.
• They may be a manager, programmer, customer and user.
• Management team identifies the stakeholders and their requirement.

SDLC Phases
There are ten phases/steps in SDLC.
i. Defining Phase
ii. Planning Phase
iii. Feasibility
iv. Analysis Phase
v. Requirement Engineering
vi. Design phase
vii. Construction/Coding Phase
viii. Testing/Verification Phase
ix. Deployment/Implementation Phase
x. Maintenance/Support Phase

Defining Phase
• In this phase the problem is clearly defined against which a system is to be developed.
• It includes all the requirements of the product which has to be developed.
• All the problems are documented and approved from the customer

Example: Students’ Examination System Development.

Department of Computer Science 10 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Defining the problem: A Students’ Examination system is needed to be developed that cover all the aspects
of Examination till results generation.

Planning Phase
• In this phase, plan is created to guide team through execution to ending phases.
• Activities involved:
o Objective of the project is defined.
o An estimate of resources is prepared.
o Analyze the alternate solutions.

Example: In the Students’ Examination system development project planning will be made to set the
ultimate goals and an estimate of resources.

Feasibility
• In this phase the weakness and strengths of a proposed solution is analyzed and evaluated.
• It has following forms:
o Technical feasibility: It determines whether the technologies required for the system
are available.
o Economic feasibility: It determines whether system can be developed in offered
budget.
o Operational feasibility: It determines whether software will operate according to the
user’s requirement.
o Legal feasibility: It determines the ethical and cyber issues related to the system..
o Schedule feasibility: It determines whether system can be developed in given time
period.

Example: Students’ Examination system is assessed for all types of feasibilities and presented to
management for final approval.

Analysis Phase
• It is the important step of SDLC as it determines whether the project goes forward with available
resources, or it should be terminated.
• In this phase, the working and problems of existing system is analyzed.
• It focuses on following questions:
o Will this system improve the organization?
o Does the existing system need to be replaced?
o Can the proposed system be developed with the available resources and budget?

Example: For Students’ Examination system development project the existing examination system of
college is analyzed.

Requirement Engineering
• In this phase the requirements of user are described in detail along with the framework.
• It consists of following steps:
o Requirement Gathering

Department of Computer Science 11 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

▪ In this, project team begins to understand what customer wants from the
project.
▪ Meetings are arranged with customer to collect their requirements.
▪ The requirements are of two types.
• Functional Requirements
• Non- Functional Requirements

Functional Requirements Non- Functional Requirements

It describes the services of system required by It describes the constraint and properties of the
customer. system.

It describes the behavior of the system. It describes the characteristics of system.

It describes what the system should do. It describes how the system will do it.

They are easy to test. They are difficult to test.

o Requirements Validation
▪ It is performed to check whether the requirements will meet the expectations
of the stakeholders.
▪ It also checks whether the requirements are complete and accurate.

o Requirements Management
▪ It is performed to ensure that system meet the expectations of stakeholders.
▪ It also gathers new requirements from changing expectations, new regulations
etc.
Example: For Students’ Examination system, the team will gather information by interviewing or
giving questionnaire to users.

Design Phase
• It is also called “architectural” phase.
• In this phase the logical model of project has been designed for data processing, flow, and storage.
• It also represents the user interface which help the developer to write code.
• It consists of two structures:

o Algorithms
▪ It is a step-by-step procedure for finding the solution of a problem.
▪ Example: (Page 29)

o Flow charts
▪ It is graphical representation of the algorithm.
▪ It shows each step of algorithm with the help of shape.

Department of Computer Science 12 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

▪ This chart helps in every stage of SDLC.


▪ Example: (Page 30)

Connector A
A circle represents.
a jump from one
point to another.

Construction/Coding Phase
• In this phase, the design is converted into code using programming languages for developing the
system.
• Coding is also called computer programing.
• Single programmer or team of programmers also use different tools for the development.
• Example: (Page 31)

Testing/Verification Phase
• In this phase, all aspects of the system are tested for functionality and performance.
• It determines whether the system meets required results.
• The execution of programming modules for finding errors is called testing and the process of finding
errors in programming modules is called debugging.
• Example: In students examination system, following test cases can be used for checking the
performance of code.

Deployment/Implementation Phase
• It is a set of activities that are used to make the software available for use.
• In involves following activities:
o Installation of hardware and software
o Training of operation personals
o Conversion: the process of changing from the old system to the new one.

Department of Computer Science 13 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Example: The students examination system is implemented in the relevant college.

Methods of Implementation
• Direct Implementation: (Riskiest)
o It referred as immediate replacement.
o In this method, the new system is implemented completely and at the same time the old
system is dropped.
• Parallel Implementation: (Safest)
o The new system runs with the old for a given period of time.
o If a problem occurs in new system, the data will not be lost in this case.

• Phased Implementation:
o The new system is implemented gradually in phases.
o The old system is progressively discarded.

• Pilot Implementation:
o The new system is installed for a small number of users.
o If performance is satisfactory, is installed and used by all.

Maintenance/Support Phase
• It is an ongoing process.
• In this phase, the performance of system is continuously monitored, according to user’s
requirements.
• It can either be modification or enhancement in the existing system.
• It continues until a complete solution is provided to customer.
• Example: The students examination system, is monitored according to the user’s requirement.

Personnel involved in SDLC and their Roles.


• The individual or group of individuals who perform the activities of SDLC are called personnel.
• They are professional in performing their particular jobs.
• The types of different personnel are as following:

1. Management Personnel/Team
• These are the professionals who have the ability to satisfy the customers and acquirers of the system.
• Responsibilities:
o Provide consistency of success of system with regard to time, cost and quality
objectives.
o Collect data/information for future use.
o Ensure all requirements of customer is met.
o Reduce risk associated with the project.

2. Project Manager
• He is a professional responsible for planning, executing and closing a project.
• Responsibilities:
o Developing the project plan.

Department of Computer Science 14 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

o Managing the project budget.


o Managing the project stakeholders.
o Managing the project team
o Managing the project risk
o Managing the project schedule
o Managing the project conflicts

3. System Analyst
• He is a professional who studies the problem, plans a solution and coordinates with the team and
customer.
• Responsible for:
o Plan a system flow.
o Interact with customers to learn and document requirements.
o Define technical requirements.
o Interact with designers to understand system limitations.
o Help programmers during system development phase.
o Manage system testing.
o Contribute to user manuals.

4. Programmer
• He is a technical professional who writes programs in programming language to develop software.
• Responsible for:
o Writing, testing and maintaining the instructions of programs.
o Updating, modifying, and expanding existing programs
o Testing the code to ensure its correctness.
o Preparing graphs and charts for showing progress of a program.

5. Software Tester
• He is a professional having specialty in testing the computer program using different testing
techniques.
• Responsible for:
o Creating test scenarios and scripts.
o Preparing and executing test data.
o Analyze results.
o Report defects.
o Submit the report to management team.

6. Customer
• He is an individual or an organization that is a current or potential buyer or user of the product.
• They are also called clients.
• The only difference between the two is, customer buy products and client buy services.
• They are the real evaluators of a product.
• They use the product and identify its merits and demerits.

Department of Computer Science 15 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Department of Computer Science 16 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 03: Object Oriented Programming in C++


Computer Program:
• It is a set of instruction that performs a specific task when executed by a computer.
• High level language is used to write a computer program.
• It must be translated into machine language before execution by compiler.
• For example, Microsoft Word is a program that allows computer users to create
documents.

History of C++ Language:


Developed In: 1980
Developed By: Bjarne Stroustrup
Developed at: Bell Laboratories
Based on: C language
Object Oriented Language

Steps to prepare C++ program.


Step Name Definition Extension
Creating and Editing a Source Writing a source program in text
1
Program editor
2 Saving a Source Program Saving a source program on a disk .cpp
Converting source program to
3 Compiling a Source Program .obj
object code
Object file is linked with the
4 Linking .exe
library files
Loading of files from hard disk to
5 Loading
RAM
6 Executing Running a file

Preprocessor Directive:
• It is not a normal program instruction to be executed by the CPU.
• It give instructions to compiler to preprocess the information before actual
compilation starts.
• It starts with a number sign (#).
• It has two types: include and define.

include Preprocessor Directive:


• It is used to include a header file at the beginning of the source program.
• Syntax: #include <name of header file>
• Example: #include <iostream.h>

Department of Computer Science 17 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

define Preprocessor Directive:


• It is used to assign a constant quantity to an identifier.
• Syntax: #define identifier constant
• Example: #define PIE 3.14

Basic Structure of Program:


• Syntax/example

main() function:
• It is a group of statements that perform specific task.
• It is a point from where execution of program started.
• It is called by operating system to execute a code.
• Its body is written within the curly braces called delimiters.

Header file:
• It contains definition of different functions that are being used in the program.
• It is included at the beginning of program using include preprocessor directives.
• It is stored in standard library of C++.
• It has .h extension.
• Syntax: name of header file.h
• Example: iostream.h, conio.h, math.h

Types of Header Files:


Name Full Form Purpose Provides Function
iostream.h Input Output Manages basic input/output cin, cout
Stream operations.
conio.h Console Input and Manages input/output on console- getch(),
Output based applications. getche()
math.h Mathematic Manages mathematical operations. pow(), sqrt()
string.h String Manages string manipulation Strcmp(),
functions. strcpy()
iomanip.h Input Output Manages input/ output manipulation setw(),
Manipulators functions. setprecision()
time.h Time Manages date and time operations. date(), time()

Source Code:
A program written in high level language is called source code/ program.
Object Code:
The compiler converts source code into equivalent machine code called object code/
program.
Source Code Object Code
Definition
It is a program written in high level language It is equivalent machine code converted by compiler
Language

Department of Computer Science 18 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

It is written in high level language Its in machine language consists of 0’s and 1’s
Execution
It can’t be directly executed by computer. It is directly executed by computer.
Extension
.cpp .obj
Example
Example.cpp Example.obj

Reserved Words:
• These are predefined words that are used by programming language for special
purposes.
• They are also called Keywords.
• They are always written in lower case letters.
• They cannot be used as variable name.
• There are about 80 reserved words in C++.
• Example: if, void, case, break

Statement Terminator:
• In C++, semicolon (;) is used as a statement terminator.
• It indicates the end of the statement.
• Every C++ statement in a program must end with it.
• Example: cout<<” Information Technology”;

Comments:
• These are non-executable statement, compiler ignores it.
• They are used to add remarks or comments in program.
• They help in understanding the source code.
• It can be entered anywhere in the program.
• It has two types:
o Single Line Comment Statement:
▪ (//) is used to start it.
▪ The end of line indicates the end of single line comment too.
▪ Example: cout<<” Hello World”; // this is a output statement.
o Multiline Comment Statement:
▪ (/*) is used to start it.
▪ (*/) is used to end it.
▪ Example: cout<<” Hello World”; /* This is a output statement and
it is my first program*/

Department of Computer Science 19 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Constants:
• It is a quantity whose value does not change during execution of program.
• A constant can be a number, a character, or a character string.
• Example: 42,7.25, ‘s’, “Computer”
• It has four types which are as following:
o Integer Constants:
▪ A numerical value without a decimal point or fraction is called integer
constant.
▪ It may be positive or negative.
▪ Example: 1000, -87 etc.
o Floating Point Constants:
▪ A numerical value with a decimal point or fraction is called integer
constant.
▪ It may be positive or negative.
▪ Example: 85.00, -3.14 etc.
o Character Constants:
▪ A single character enclosed in single quotation marks is called character
constant.
▪ Example: ‘d’, ‘+’, ‘5’ etc.
o String Constants:
▪ A collection of characters is called string
▪ It consists of alphabets, digits or special characters.
▪ It enclosed in double quotation marks.
▪ Example: “Pakistan”, “P-21” etc.

Constant Qualifier (const):


• It defines a variable whose value cannot be changed during execution of program.
• A variable define with the const qualifier must be assigned some value
• Syntax: const datatype variable = constant;
• Example: const int AGE = 34;

Variable:
• A quantity whose value may change during execution of program.
• It may be numeric or non-numeric.
• They are also called reserved memory location as it reserves space in memory.
• It has three components:
o Variable Name: It refers to the user defined identifier that is assigned to a
specific memory location.
o Variable Content: It refers to the value stored in the memory location.
o Variable Address: It refers to the address of memory location assigned to a
variable.
• Syntax: datatype variable = value;
• Example: int AGE = 34;

Department of Computer Science 20 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Variable Declaration:
• Specifying the name of variable with its data type is called declaration of variable.
• Variable must be declared in the program before use.
• Syntax: datatype variable;
• Example: int age;

Variable Initialization:
• Assigning a value to a variable at the time of its declaration is called initialization of
variables.
• Syntax: datatype variable = initial value;
• Example: int x=4, y=5;

Rules for Specifying Variable Names:


1. It may consist of alphabets, digits, and the underscore (_).
2. The first character of a variable name must be an alphabet or an underscore.
3. Blank spaces are not allowed in variable name.
4. Special characters except underscore cannot be used in a variable name.
5. A variable name declared with one datatype cannot be used for another datatype.
6. Upper case letters is considered different form a lower-case letter.
7. Reserved words and keywords of C++ are not allowed to be used as a variable name.

Data Types:
• It is declaration of variable for storing various types of data.
• It must be defined before assigning it a value.
• Every datatype has different storage capacity.
• Types: Integer, Floating Point, Character

Integer:
• It is datatype used to store whole numbers without decimal point or fraction.
• Its’s short form is int.
• Example: -3,0,2081 etc.
Integer Type No of Bytes Range Range
int 4 bytes -2147483648 to 2147483648 231 to (231 -1)
unsigned int 4 bytes 0 to 4294967295 0 to (232 -1)
short int 2 bytes -32768 to 32767 215 to (215 -1)
unsigned short int 2 bytes 0 to 65535 0 to (216 -1)
long int 4 bytes -2147483648 to 2147483648 231 to (231 -1)
unsigned long int 4 bytes 0 to 4294967295 0 to (232 -1)

Floating-Point:
• It is datatype used to store real numbers with decimal point or fraction.
• Its’s short form is float.
• Example: -3.1,0.9,2.081 etc.

Floating Point Type No of Bytes Range Precision
float 4 bytes 10-38 to 1038 6 digits

Department of Computer Science 21 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

double 8 bytes 10-308 to 10308 15 digits


long double 10 bytes 10-4932 to 104932 18 digits

Character:
• It is datatype used to store only a single character.
• It can be alphabet, digit or special character.
• It takes one byte in memory.
• Its’s short form is char.
• It must be written in single quotation marks.
• Example: ‘a’,’+’, ‘0’ etc.

Type Casting:
• Conversion of datatype of numeric value into another datatype during arithmetic
operation is called type casting.
• Types: Implicit and Explicit Type Casting

Implicit Type Casting:


• It automatically converts a data type into another.
• Conversion is done by compiler.
• The operands in arithmetic operations must be of similar datatype.
• The value of lower datatype is converted into higher data type.
Long double → double → float → long → int
• Example: int q;
q = 15/6;
q = 2;

Explicit Type Casting:


• It needs a special operator to convert a data type into another.
• Conversion is done by programmer.
• The value of higher datatype is converted into lower data type.
• Syntax: (datatype) expression;
• Example: float q=5.25;
cout<<(int)q;
q=5;

Implicit Type Casting Explicit Type Casting


Definition
It converts automatically from one datatype to It converts a special operator to convert from one
another. datatype to another.
Datatype
Lower datatype is converted into higher Higher datatype is converted into lower data
data type type
Conversion
Conversion is done by compiler. Conversion is done by programmer.
Example
int q; int q=5.25;
q = 15/6; cout<<(float)q;
q = 2; q=5;

Department of Computer Science 22 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Input/Output Handling:
• Providing data into a program from outside source is known as input.
• Displaying data on screen or saving in a storage device is known as output.
• In C++, I/O is performed by using streams.
• The “cin” and “cout” are the standard I/O statements.
• iostream.h header file is used for handling I/O operations.

The cout Statement:


• The cout statement is used to display text or value on the screen.
• Insertion (<<) operator is used with cout.
• Header File: iostream.h Write a program that
• Syntax: cout<< string/variable; initialized two variables and
• More than one insertion operator can be used in a print their sum.
single cout statement.
• Example: cout<<”The value of a is”<<a ;

The cin Statement:


• The cin statement is used to take input from user and assign it to variable.
• Enter key is pressed after entering a value.
• Extraction (>>) operator is used with cin. Write a program that read
two variables and print their
• Header File: iostream.h
sum.
• Syntax: cin>> variable;
• More than one extraction operator can be used in a single cin statement.
• Example: cin>>a>>b;

The getch() Function:


• It is character input function.
• It is used to read a single character without pressing enter key.
• Entered character is not displayed on screen.
• Header File: conio.h
• Syntax: [var=]getch();
• Example: ch=getch();

The getche() Function:


• It is character input function.
• It is used to read a single character without pressing enter key.
• Entered character is displayed on screen.
• Header File: conio.h
• Syntax: [var=]getche();
• Example: ch=getche();

Difference between cin Statement and getch()/getche() Function:


cin Statement getch()/getche() Function

Department of Computer Science 23 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Input Data
It is used to input all type of data i.e., It is used to input single character.
characters, number.
Enter Key
Enter key is pressed after entering a value. Enter key is not pressed after entering a
value.
Variable(s)
It can take values for more than one It takes value for one variable at a time.
variable at a time.
Header File
iostream.h conio.h
Syntax
cin>>var; var=getch();
Example
cin>>a; ch=getch();

Escape Sequence:
• It is used to control output look and print special character on output screen.
• It begins with backslash (\) [control character] followed by a code character.
• They are used inside the output statement.
• Backslash causes an escape from the normal way characters are interpreted in C++.
• Syntax: \character
• Example: \n, \\, \t, \”

Department of Computer Science 24 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Types of Escape sequences:


Escape Purpose Example Output
Sequence
\a Produce alert (beep) cout<<”Hello\aWorld”; Hello(beep)World
sound.
\b Move cursor one cout<<”Hello\bWorld”; HellWorld
position backward.
\n Move cursor to cout<<”Hello\nWorld”; Hello
beginning of next line. World
\r Move cursor to cout<<”Hello\rWorld”; World
beginning of current
line.
\t Move cursor to next cout<<”Hello\tWorld”; Hello World
tabular position.
\\ Print a single backslash. cout<<”Hello\\World”; Hello\World
\’ Print a single quote. cout<<”\’HelloWorld \’”; ‘Hello World’
\” Print a double quote. cout<<”\”HelloWorld\””; “Hello World”

Manipulators:
• It is a command that is used for modifying output in many ways.
• They are used inside the output statement.
• Header File: iomanip.h
• Example: setw(), setprecision()

The endl manipulator:


• It is used to shift control on the next line.
• Its header file is iomanip.h but it can be used without it.
• Example: cout<<”Hello”<<endl<<”world”;

The setw() manipulator:


• It is used to set the minimum field width for output.
• Field width is the number of column spaces use to display text or value.
• The number or text is right justified within the set field width.
• Header File: iomanip.h
• Syntax: setw(n)
• Example: cout<<”Hello”<<setw(10)<<”World”<<endl;

Expression:
• It is a combination of constants, variables and operators.
• Constants and variables are operands.
• It has three types:

Arithmetic Expression:
• It contains arithmetic operators to perform mathematical operation on operands.
• Arithmetic operators such as +,-,*,/,%

Department of Computer Science 25 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Example: a*(b-c), 3*a + 8-b

Relational Expression:
• It contains relational operators to compare values of same type.
• These are used to specify conditions in program.
• The result is either TRUE or FALSE.
• Relational operators such as ==,!=,>,<,>=,<=
• Example: (a>b), (x==y)

Logical Expression:
• It combines two or more conditions using logical operators.
• It is also called compound expression.
• The result is either TRUE or FALSE.
• Logical operators such as &&,||,!
• Example: (a>b)&&(a==10)

Operators:
• It is a symbol to perform specific operation on data.
• It has following types:

Types of Operators:
Assignment Operator:
• It is used to assign value of an expression to a variable.
• Equal sign (=) is used as assignment operator.
• Syntax: variable = expression/variable/constant;
• Example: a= 25+b;

Arithmetic Operator:
• It is used perform mathematical operation on numerical values.
• It includes addition (+), subtraction (-), multiplication (*), division (/), modulo (%)
• Example:
Operator Expression Results
+ 2+3 5
- 3-2 1
* 3*2 6
/ 3.0/2=1 1
% 2%3 2
Arithmetic Assignment Operator:
• When an assignment operator is used with arithmetic operator then it is called
arithmetic assignment operator.
• It includes addition(+=), subtraction(-=), multiplication(*=), division(/=), modulo (%=)
• Syntax: variable op = variable;
• Example: a+=b;

Increment Operator:
• (++) is used as increment operator.

Department of Computer Science 26 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• It is a unary operator.
• It is used to add one to the value of variable.
• It is only used with a variable.
• Types:
o Prefix: Increment operator is written before the variable. It increments value
before using it.
o Syntax: ++variable; b=++a;
o Example: ++a; 1. a=a+1;
2. b=a;
o Postfix: Increment operator is written after the variable. It
increments value after using it.
o Syntax: variable++; b=a++;
o Example: a++; 1. b=a;
2. a=a+1;
Decrement Operator:
• (--) is used as decrement operator.
• It is unary operator.
• It is used to subtract one from the value of variable.
• It is only used with a variable.
• Types:
o Prefix: Decrement operator is written before the variable. b=--a;
It decrements value before using it. 1. a=a-1;
o Syntax: --variable; 2. b=a;
o Example: --a; b=a--;
o Postfix: Decrement operator is written after the variable. It 1. b=a;
decrements value after using it. 2. a=a-1;
o Syntax: variable--;
o Example: a--;

Prefix Increment Operator Postfix Increment Operator


Definition
Increment operator is written before the Increment operator is written after the
variable. It increments value before using it. variable. It increments value after using it.
syntax
++variable; variable++;
Example
a=5; a=5;
b=++a; b=a++;
b=6; b=5;

Relational Operator:
• It is used compare two values of same type.
• It is used to specify condition in program.
• The result is either TRUE or FALSE.
• It includes equal to(==), not equal to(!=), less than(<), greater than(>), less than and
equal to(<=), greater than and equal to(>=),
• Example: a>b, a==10

Department of Computer Science 27 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Logical Operator:
• It is used to form compound condition.
• The condition in which two or more relational expressions are compared is called
compound condition.
• The result is either TRUE or FALSE.
• It includes AND(&&), OR(||), NOT(!)
• Example: (a>b)&&(a==10)

Logical AND Operator:


• If both expressions are true, then it is considered as true otherwise false.
• (&&) is AND operator.
• Example: (x+y)&&(x==10)

Logical OR Operator:
• If both expressions are false, then it is considered as false otherwise true.
• (||) is OR operator.
• Example: (x+y)||(x==10)

Logical NOT Operator:


• It is used with single expression, so it is a unary operator.
• If the expression is true, then it is considered as false and vice versa.
• (!) is NOT operator.
• Example: !(x>y)

Conditional Operator:
• (? ) is a conditional operator.
• It is also known as ternary operator.
• It is used to return one of two values depending on result of a condition.
• Syntax: Condition? expression 1 : expression 2;
• Example: (marks>=33) ? cout<<”Pass”:cout<<”Fail”;

Types of Operators: (w.r.t operands)


Unary Operators:
• It works on a single operand.
• It includes increment (++), decrement (--), NOT (!)
• Example: --a, !b

Binary Operators:
• It works on two operands.
• It includes arithmetic assignment, relational, logical AND etc.
• Example: a+=b, x>y

Ternary Operators:
• It works on three operands.
• It includes conditional operator (? :).

Department of Computer Science 28 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Example: (marks>=33) ? cout<<”Pass” cout<<”Fail”;

Operator precedence:
• It describes the order in which the operations of operators are to be performed in an
expression.

Precedence Operators
1 *, /, %
Arithmetic
2 +, -
3 >, <, >=, <=
Relational
4 ==, !=
5 !
6 Logical &&
7 ||
8 Assignment =, +=, -+,*=, /=, %=

Department of Computer Science 29 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 04: Control Structures


Control Structures:
• It is used to control the flow of program execution.
• It has three types:

1. Sequential Structure
• It is used to execute statements one by one in sequence they appear in program.
• It is the default structure of program.

2. Repetition Structure
• It is also called Iteration structure or Loop.
• It is used to execute one or more statements many times until the condition is true.
• Example: for, while, do while

3. Conditional Structure
• It is also called Decision Making Structure.
• It is used to execute one or more statements based on conditions.
• Example: if, if-else, else-if, switch statement

The if Statement
It is used to execute or ignore a block of statements based on a condition.
Syntax:
if (condition) {
Body of if
}

Working:
1. The condition is checked.
2. If the condition is true, body of if, is executed.
3. If the condition is false, body of if, is ignored.
4. And then the control is transferred to the next statement after the body of if.

The if else Statement


It is used to execute a block of statement based on a condition from two blocks.
Syntax:
if (condition) {
Body of if
}
else {
Body of else
}

Working:
1. The condition is checked.
2. If the condition is true, body of if, is executed and body of else is ignored.
3. If the condition is false, body of else, is executed and body of if is ignored.

Department of Computer Science 30 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

4. And then the control is transferred to the next statement after the body of if-else.

ELSE IF Statement
• It is also called “if-else-if”.
• It is used to execute a block of statement from many blocks based on conditions.
Syntax:
if(condition 1)
{
Block of condition1
}
else if(condition 2)
{
Block of condition2
}
.
.
else
{
Block of else
}

Working:
1. The condition-1 is checked.
2. If the condition-1 is true, body of current if, is executed and all other blocks are
ignored.
3. If the condition-1 is false, control is transferred to next condition.
4. In this way all conditions are checked one by one.
5. If none of condition is true, the body of else is executed. (else is optional)
6. The control is transferred to the next statement after else-if in each case.

Difference between IF ELSE and ELSE IF statement:


IF ELSE Statement ELSE IF Statement
It selects one block of statement from two. It selects one block of statement from many.
It checks only one condition. It checks many conditions.
Syntax Syntax
Example Example

SWITCH Statement:
• It is used to execute a block of statement from many blocks based on one expression.
• It works like ELSE IF statement.
• break statement is used to terminate a case in switch statement.
Syntax:
switch(expression/variable) {
case constant-1: block of statements
break;
case constant-2: block of statements

Department of Computer Science 31 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

break;
case constant-3: block of statements
.
.
.
default: block of statements
break;
}

DEFAULT:
• It is optional in switch statement.
• It is executed when condition does not match with any case.
Syntax:
switch(expression/variable) {
case constant-1: block of statements
break;
.
.
.
default: block of statements
break;
}

Difference between SWITCH and ELSE IF statement:


SWITCH ELSE IF Statement

Execution of statements depends on single Execution of statements depends on multiple


expression. conditions.

It tests only for equality. It tests for all type of relational operator.
It is fast. It is slow.
If condition does not match with any case then If none of the condition is true then ELSE statement is
default () statement is executed. executed.

NESTED Selection Structure:


• When selection structure, used inside, another selection structure is known as nested
selection structure.
• The C++ allows to nest if, if else or else if inside another selection structure.
• The first selection structure is called outer selection structure and the one used inside
is called inner selection structure.
Syntax:
if(condition) //outer selection structure
{
if(condition) //inner selection structure
{
block of statements
}

Department of Computer Science 32 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

FOR Loop:
• It is used to execute one or more statements for a specific number of times until the
condition is true.
• It is used when the number of iterations is known in advance.
• It is also called counter loop.
Syntax:
for (initialization; condition; increment/decrement) {
Body of loop
}

Working:
1. The counter variable is initialized. (Only once)
2. After initialization, the condition is checked. If the condition is true, body of loop is
executed, and control is transferred to increment/decrement part.
3. The condition is checked again, if it is true the process goes on until the condition
becomes false.
4. If the condition is false, loop is terminated, and control is transferred to next
statement after the body of loop.

WHILE Loop
• It is used to execute one or more statements many times based on a given condition.
• It is used when the number of iterations is not known in advance.
• It is also called conditional loop.
• Condition is checked at the beginning of the loop.
Syntax:
while(condition) {
body of loop
}

Working:
1. The condition is checked.
2. If the condition is true, body of loop is executed, and control is transferred again to
the condition.
3. The condition is checked again, if it is true the process goes on until the condition
becomes false.
4. If the condition is false, loop is terminated, and control is transferred to next
statement after the body of loop.

Difference between WHILE and FOR statement:


FOR WHILE
It is a counter loop. It is a conditional loop.
It is used to execute one or more statements It is used to execute one or more statements
for a specific number of times. many times based on a given condition.

Department of Computer Science 33 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Number of iterations is known in advance. Number of iterations is not known in


advance.
Execution is not only dependent on Execution is dependent on condition.
condition.
After the execution of statements control is After the execution of statements control is
transferred to increment/decrement part. transferred to the condition.

DO-WHILE Loop
• It is used to execute one or more statements many times based on a given condition.
• It is similar to while loop except that the condition is checked at the end of the loop.
• It is executed at least once even if the condition is false.
Syntax:
do {
body of loop
} while(condition);

Working:
1. The block of statements following the keyword do is executed.
2. The condition at the end is checked.
3. If the condition is true, control is transferred back to the beginning of the loop.
4. After executing the body, condition is checked again, if it is true the process goes on
until the condition becomes false.
5. If the condition is false, loop is terminated, and control is transferred to next
statement after the body of loop.

Difference between WHILE and DO-WHILE statement:


WHILE DO-WHILE
It is pre-tested loop as the condition is checked It is post tested loop as the condition is checked in the
in the start. end.
It is called entry-controlled loop. It is called exit-controlled loop.
The body statements never execute if the The body statements execute atleast once even if the
condition is false. condition is false.
There is no semicolon at the end of while There is semicolon at the end of do-while statement.
statement.

The BREAK Statement:


• It is used inside loop or cases of switch statement.
• It is used in switch statement to terminate a case and program execution continues
from the next statement following the switch statement.
• It is used inside a loop to terminate a it and program execution continues from the
next statement following the loop.
• If it is not used at the end of the case, then the statements of other cases that come
after, will also be executed.
Syntax:
break;

Department of Computer Science 34 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

The CONTINUE Statement:


• It is used inside loop.
• It is used to transfer control to the beginning of loop, skipping the remaining
statements.
Syntax:
continue;

The EXIT () Function:


• It is used to terminate a program before its normal termination.
• It requires the standard library header file stdlib.h.
• The value in exit is known as exit code.
• Exit code is an integer value or integer variable.
exit (0): Indicate the compiler that no error is occurred.
exit (1): Indicate the compiler that an error is occurred.
Syntax:
exit(value);
Example:
exit (0);

Difference between break statement and exit () function statement:


BREAK Statement EXIT () Function
It is used to terminate a loop or case. It is used to terminate a program.
It is used in loop or switch. It is used in anywhere in program.
It doesn’t have a header file. Header File: stdlib.h
Syntax: break; Syntax: exit(value)

NESTED Loop:
• A loop inside another loop is known as nested loop.
• The C++ allows nest a for, while or do-while inside another for, while or do-while.
• The following points can be considered for writing nested loops:
o Nesting can be done at any level.
o Any loop structure can be placed within other loop structure.
• Syntax:
for (initialization; condition; increment/decrement)
{
for (initialization; condition; increment/decrement)
{
body of the loop
}
}

Department of Computer Science 35 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 05: Arrays and Strings


Array:
• An array is collection of same type of elements stored in contiguous memory locations
represented by single variable name.
• The total number of elements in an array is called array size.
• The position of element in an array is called index or subscript.
• Index is always written in square bracket.
• Index is used to access specific element of the array.
• It is always an integer value.
• First element of the array has index 0 and last element has index one less than the size
of the array.
• Types: It has two types.
o One Dimensional Array (List)
o Two-Dimensional Array (Matrix or Table)
• Example: marks (variable name)
45
67
50
79
58
36

Advantages of Array:
• It is used to represent multiple values of same type by single name.
• Values are stored in contiguous memory location.
• It reduces the program size.
• It provides easy way to handle list, table or matrix.
• It makes computer programing task simple and easy.
One Dimensional Array:
• A single index number is used to position each element in array.

Declaring One Dimensional Array:


• It means specifying the data_type and size of an array.
• It allows compiler to decide how many locations should be reserved9 in memory.
• Syntax: data_type array_name[array_size];
• Example: int marks[6];
float weight[8];

Initialization of One-Dimensional Array:


• It means assigning values to the elements of list at the time of declaration.
• When initializing an array it is not necessary to mention an array size as compiler can
find out by counting values in the bracket.
• Syntax: data_type array_name[array_size]={values};
• Example: int marks[6]={12,14,13,16,18,19};

Department of Computer Science 36 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Two-Dimensional Array:
• It has two dimensions i.e. vertical represent rows and horizontal represent columns.

Declaring Two-Dimensional Array:


• It means specifying the data_type and size of row and column in an array.
• It allows compiler to decide how many locations should be reserve in memory.
• Syntax: data_type array_name[row_size][column_size];
• Example: int marks[3][4];
float weight[6][4];

Initialization of Two Dimensional Array:


• It means assigning values to the elements of table at the time of declaration.
• Syntax: data_type array_name[row_size][column_size]={values};
• Example: int marks[2][3]={{12,14,13},{16,18,19}};

Accessing and Filling Two Dimensional Array:


• Data can be accessed in table by specifying the index of row and column.
• Syntax: array_name[row][column]=value;
• Example: arr[3][4]=15;

The sizeof() Function:


• It returns the number of bytes occupied by data type or variable in memory.
• It is used to determine the amount of storage reserved by them.
• Syntax: sizeof(data_type/variable);
• Example: sizeof(int), sizeof(arr), size(a)

Why index is necessary in array?


As there is a single array name for all elements so each element is uniquely identify by its
position in the array which is called array.

Difference between One and Two Dimensional Array:


One Dimensional Array Two Dimensional Array
It stores element in the form of list. It stores element in the form of table.
Elements can be accessed by specifying Elements can be accessed by specifying row
single index along with array name. and column index along with array name.
It is also known as list or linear array. It is also known as table or matrix.
Syntax:data_type array_name[array_size]; Syntax: data_type
array_name[row_size][column_size];

String:
• It is a sequence of characters enclosed in double quotes.
• It may consist of alphabetic characters, digits and special symbols.
• It is stored in a one-dimensional array of char data type. Each element of
character string holds one character.

Department of Computer Science 37 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• All strings end with a special character, known as null character and it is
represented by ‘\0’. The null character is automatically appended at the end of
string.
• Syntax: char stringname[stringsize];
• Example: char weekday[10];

String Functions:
• String functions used string.h header file.

cin.get() Function:
• It is an input function to get data from keyboard.
• It reads a string that may contain blank spaces.
• Syntax: cin.get(stringname,stringsize);
• Example: cin.get(name,20);

strcpy() Function:
• It copies contents of a string variable or string constant to another string variable.
• Syntax: strcpy(string2, string1);
• Example: char str1[10]=”Hello”,str2[10],str3[10];
strcpy(str2, str1);
strcpy(str3, “World”);

strcat() Function:
• It is used for concatenation or joining of two strings.
• Syntax: strcat(string1, string2);
• Example: char str1[10]= “HOME”,str2[10] = ”WORK”;
strcat(string1, string2);

strlen() Function:
• It is used to return the length (number of characters) of a string.
• Syntax: strlen(string);
• Example: char string[10] = “COMPUTER”;
strlen(string);

strcmp() Function:
• It compares two strings and return an integer value.
• The comparison is based on ASCII codes of characters.
• Syntax: strcmp(string1,string2);
o Return 0, if both strings are equal.
o Return 1, if first string is greater than second.
o Return -1, if first string is less than second.

Difference between cin Statement and cin.get Function:


cin Statement cin.get() Function
It is an input statement to get data from keyboard. It is an input function to get data from keyboard.
It reads a string, character, integer etc. It reads only string that may contain blank spaces.

Department of Computer Science 38 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

It considers blank space in string as terminating It considers blank space in string as normal character.
character.
It reads more than one variable in single It reads only one variable in single statement.
statement.
Header File: iostream.h Header File: string.h
Syntax: cin>>variable; Syntax: cin.get(stringname,stringsize);

Difference between strcpy() and strcmp() Function:


strcpy() Function strcmp() Function
It copies contents of a string variable or string It compares two strings and return an integer value
constant to another string variable. based on the result of comparison.
Syntax: strcpy(string2, string1); Syntax: strcmp(string1, string2);
Example Example

Difference between strlen() and strcat() Function:


strlen()Function strcat() Function
It is used to return the length (number of It is used for concatenation or joining of two strings.
characters) of a string.

Syntax: strlen(string); Syntax: strcat(string1, string2);


Example Example

Department of Computer Science 39 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 06: Function


Function:
• It is group of statements that together performs a task.
• Every C++ program has atleast one function, i.e. main().
• It is a complete and independent program.
• It provides modularity to a program.
• It has two types.

Built-in Function:
• It is also called library function.
• Functions that are predefined in C++ are called built-in function.
• They are defined in header files which must be included in a program.
• They are called directly without writing code for them.
• Examples: sqrt(), strcmp(), getch()

User Defined Function:


• It is also called programmer defined function.
• Functions that are defined by programmer according to his needs are called user
defined function.
• Syntax: return_type function_name(parameters)
{
Body of function
}
• Examples: int sum(int a, int b){
return a+b;
}

Advantages of Using Function:


• It allows user to write a piece of code once and use it multiple times.
• It makes writing and testing of program easier.
• It is easy to modify a code, without changing the structure of program.
• It divides the program into logical modules which are easy to understand.
• It reduces the length of the code.

Function Signature:
• It is also known as Function header.
• It has three parts:
• Function Name: It is a name of function. It is used for calling it in a program.
• Parameters/Arguments: These are the variables and values appear in function call or
function prototype (written in parenthesis).
• Return Type: It is the type of value returned by function i.e. int, char, float etc.
• Example: int sum(int a, int b)
o Function Name: sum
o Parameters: int a, int b
o Return Type: int

Department of Computer Science 40 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Function Components:

Function Declaration:
• It is also known as Function prototype.
• Specifying the name, return type, parameters etc. of function is known as function
declaration.
• It tells the compiler about the existence of the function.
• Function is declared before the main().
• It has a semicolon (;) at the end.
• Syntax: return_type function_name(parameters);
• Example: int sum(int , int );

Function Definition:
• It is actual code of the function.
• It consists of set of statements that together perform some specific task.
• It has two parts: Header and Function Body
• It don’t has a semicolon(;) at the end.
• Syntax: return_type function_name(parameters){
Bofy of function }
• Example: int sum(int a, int b){
return a+b;
}

Difference between Function Declaration and Definition:


Function Declaration Function Definition
Function is declared before the main(). Function is defined anywhere.
It has a semicolon (;) at the end. It doesn’t have a semicolon (;) at the end.
It may or may not have the variables name It has the variables name for the parameter.
for the parameter.
Example: int sum(int , int ); Example: int sum(int a, int b)

Function Call:
• It is a statement to invoke(execute) a function.
• It is used in the main() function or in any other function of program.
• Function is called by its name and passing necessary parameters.
• Syntax: function_name(parameters);
• Example: sum(a,b);

Scope of Variables:
• It specifies the scope of variables within program.
• It also specifies in which parts the variables are accessed.
• It has three types.

Local Variables:
• It is also known as Automatic variable.
• It is declared within a main function or inside any user defined function.

Department of Computer Science 41 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• It can only be accessed within the function in which they are declared.
• It remains in memory until the end of function.
• It is preceded by the keyword auto.
• Example: auto int a; or int a;

Global Variables:
• It is declared at the top of a program before main() function.
• It is accessible by every function of a program.
• It remains in memory until the end of program.

Local Function Global Function


It is defined within a main function It is defined at the top of a
or inside any user defined program before main() function.
function.

They can only be accessed within They are accessible by every


the function in which they are function of a program.
declared.
It remains in memory until the end It remains in memory until the end
of function. of program.

Static Variables:
• It is declared within a main function or inside any user defined function.
• It can only be accessed within the function in which they are declared.
• It remains in memory until the end of program.
• It preserves the last value a function returned.
• It initializes only once.
• It is preceded by the keyword static.
• Example: static int a;
Parameters:
• These are the variables and values appear in function call or function prototype
(written in parenthesis).
• They are passed to a function for processing.
• They are also called Arguments.
• It has two types.

Actual Parameters:
• They appear in function call.
• They can be fixed values or variables without datatype.
• Example: sum(a,b);

Formal Parameters:
• They appear in function declaration or header.

Department of Computer Science 42 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• They are variables along with datatype.


• Example: int sum(int a, int b);

Scope of Functions:
• It specifies the scope of function within program.
• It also specifies in which parts the functions are accessed.
• It has two types.

Local Functions:
• It is declared inside the block of another function.
• They can only be accessed within the function in which they are declared.

Global Functions:
• It is declared outside any function.
• It can be accessed from any part of the program.

Inline Function:
• It is preceded by the keyword inline.
• It replaces the function call by the copy of the contents of function itself at the compile
time.
• Advantage:
o It removes the function call.
o It removes shifting control overhead.
o It provides enhanced program speed.
• Disadvantage:
o It makes the compiled code much larger.
o It may cause thrashing in memory.
o It may also cause lots of cache miss.
• Syntax: inline return type function name (parameters);
• Example: inline int sum(int a, int b);
Passing Argument:
• To execute a function, arguments are passed.
• The result is produced within the function body and returned to the calling program.
• It has three methods:
• Passing arguments by Constants
• Passing arguments by Values
• Passing arguments by Reference

Passing Argument by constants:


• The actual constant values are passed in it instead of variable.
• Values can be character or number etc.

Passing Argument by values:


• The copy of the argument is passed in it using variables.
• The function operates on the copy of the argument.

Department of Computer Science 43 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Passing Argument by reference:


• The reference to the function argument is passed in it instead of the copy.
• As a result, the value of actual parameter can be changed within calling function.
• The ampersand sign (&) is used with original variable.
• Advantages: This method allow to:
• Return multiple values.
• To change the value of argument in function.
• Pass and process values quickly.

Default Argument:
• A default argument is a parameter with a default value provided in a function
declaration or definition.
• It must be right most parameter in a function parameter list.
• If a value for that parameter is not passed during calling a function, default value is
used.
• If a value for that parameter is passed during calling a function, default value is
ignored.
• Syntax: return type function name (parameter1=value ….)
• Example: int divide (int a=2, int b=3)

Return Statement:
• It is used in the function body to return the result of function.
• It can be expression, constants, or variable.
• If it is used in program then a function has valid datatype i.e. float, int, char etc.
• It can only return a single value at a time.
• Syntax: return expression/constants/variable;
• Example: return x; return x+y; return 5;

Function Overloading:
• It is a feature of C++ that allows creating multiple functions with the same name but
with different type and number of parameters.
Advantages of Function Overloading:
• Multiple functions with the same name having different purpose can be declared.
• As multiple functions have same name so it’s easy to remember.
• It reduces the complexity of program.
• It exhibits the behavior of polymorphism.
• It increases the readability of program.

Use of Function Overloading:


• Number of Argument: It allows creating multiple functions with the same name but
with different number of arguments.
• Data_type of Argument: It allows creating multiple functions with the same name but
with different type of argument.
Return Type: It doesn’t allow creating multiple functions with the same name but with
different return type. It will generate error message in this case.

Department of Computer Science 44 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Department of Computer Science 45 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 07: Pointer


Pointer:
• Pointer is a variable that points to specific address of another variable in the memory.
• Syntax: data_type *variable_name;
• Example: int *p;

Advantages of Pointer:
• It provides direct and fast access to memory address.
• It provides better memory manipulation capabilities.
• It increases the execution speed of program.
• It saves the space in computer memory.

void Pointer:
• It is a special type of pointer.
• It is also called generic pointer.
• It is used to point any type of variable i.e. int, char etc.
• Syntax: void *variable_name;
• Example: void *sum;

null Pointer:
• The pointer variable which is initialize with zero is called null pointer.
• They do not point to anything.
• They are used in dynamic memory allocation.
• Syntax: data_type *variable_name = 0;
• Example: int *p = 0;

Declaration:
• It is similar to regular variable only a asterisk(*) symbol between data type and
variable name is used.
• Data type in declaration is the type of data the pointer points to.
• The asterick(*) is used anywhere between data type and variable name.
• Syntax: data_type *variable_name;
• Example: int *sum; float * height; char* name;

Initialization:
• Assigning values to pointers at the time of declaration is called pointer initialization.
• Pointer initialization is must.
• The address of variable can be accessed by using reference operator (&) before the
name of variable.
• Syntax: data_type *variable_name = &variable;
• Example: int sum;
int *s = &sum;

Reference Operator (&):


• It is used to store the address of variable.

Department of Computer Science 46 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• It is also called Address Operator.


• The (&) is used before the variable name.
• It is a unary operator.
• Example: cout << &ptr; \\it will print the address of variable saved in pointer ptr.

Dereference Operator (*):


• It is used to get the value of variable pointed by a pointer.
• It is a unary operator.
• This (*) is used in the declaration of pointer between datatype and pointer name.
• Example: cout << *ptr; \\it will print the value pointed by pointer variable ptr.

Difference between Reference and Dereference Operator:


Reference Operator Dereference Operator
(&) is called the reference operator. (*) is called the dereference operator.
It is used to store/access the address of It is used to get the value of variable pointed
variable. by a pointer.
Example: cout << &ptr; \\it will print the Example: cout << *ptr; \\it will print the
address of variable saved in pointer ptr. value pointed by pointer variable ptr.

Difference between Simple and Pointer Variable:


Simple Variable Pointer Variable
It is used to store the value of any datatype. It is used to store the address of simple
variable.
No operator is used during its declaration. Derefrence operator(*) is used between
datatype and variable during declaration.
Syntax: Syntax:

Department of Computer Science 47 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 08: Classes and Objects


Class:
• Class is a user defined data type.
• It has two types of member: Data Member & Member Function
• Members are used within the access specifier.
• It is accessed and used by creating instances also called object.
• It is not used without creating an object.
• The definition of class does not occupy any memory.
• Syntax: class class_name
{
access specifier:
member1;
access specfier:
member 2;

};
Object:
• It is variable of type class.
• It is also called the instance of that class.
• Declaring a variable of type class is called instantiating.
• More than one object can be declared in single statement.
• When object is declared then memory is reserved for data member and function
member of that class.
• Syntax: class_name object_name;
• Example: CRectangle R1;

Accessing Member of Class:


• (.) Dot is used to access the data member or member function.
• Object name and member name is concatenated with dot (.).
• Syntax: object_name.member_name
• Example: r.area();

Data Member:
• These are attributes of the class.
• These are variables declared inside the body of class.
• They are mostly declared within the private access specifier.
• Example

Member Function:
• Function performs operation on the data members.
• These are the functions declared or defined inside the body of class.
• They are mostly declared within the public access specifier.
• Example
Access Specifiers:
• It defines how a member of a class is accessed.
• It determines in which part of program a member is accessible.

Department of Computer Science 48 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• There are 3 types of access specifier in c++.

private Access Specifier:


• It defines that a member of a class is accessible only within the class and friend
function.
• They are not accessible outside of the class.

public Access Specifier:


• It defines that a member of a class is accessible from anywhere in program.
• i.e. within the class, derived class and in main function.

protected Access Specifier:


• It defines that a member of a class is accessible only within the class, derived class and
friend function.

Data Hiding:
• It is the feature in C++, to protect members of class against illegal access.
• It is facility to hide member using different access levels i.e. private, protected, public.
• It is also called encapsulation.
Access public private protected
In the same class Yes Yes Yes
In the derived class Yes No Yes
In friend function Yes Yes Yes
In main() function Yes No No
Constructor:
• It is special member function of a class.
• It executes automatically when object is created.
• Its purpose is to initialize an object.
• Rules:
o It has same name as of class.
o It doesn’t have any return type.
o It is always public.
• Types:
o Implicit Constructor
o Explicit Constructor

Implicit Constructor:
• It is also called default constructor.
• It is without arguments or has default value for every argument.
• If no constructor is declared in class definition, then compiler provides the default
constructor with no arguments.

Explicit Constructor:
• It is also called user defined constructor.
• It is declared by user mostly for initialization of variables.
• Objects should be declared according to the constructor parameters.

Department of Computer Science 49 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Constructor Overloading:
• Using more than one constructor in the same class having same name but different
types or numbers of parameter is called constructor overloading.
• In overloading, constructor is executed whose parameters match with the arguments
passed in object declaration.

Destructor:
• It is special member function of a class.
• It is executed when an object is destroyed.
• It de-allocates the memory allocated to an object during its creation.
• Rules:
o It has same name as that of class.
o It preceded by a tilde symbol (~).
o It doesn’t have any return type.
o It can’t take arguments.
o It is always public.

Inheritance:
• It is ability to reuse a code by creating
new classes based on existing classes.
Example
• It uses the parent and child class.
• The class from which other class is 2
derived are called Parent or Base class.
• The class which is derived from another
class is called Child or Derived or Sub
class.
• Child class inherits the features of the
parent class.
• When a class is derived from more than
one parent class then the phenomena is
called multiple inheritances.
• Example 1: A new car model has inherited the features of old car model like break or
navigation system.
• Syntax: class A
{
};
class B: public A
{
};
Polymorphism:
• It is ability to use a single operator or function in multiple ways.
• It gives multiple functionalities to the operator or function.
• It can be achieved by:
o Function overloading
o Operator overloading
o Virtual Function

Department of Computer Science 50 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Function overloading means using same function with different types or numbers of
parameter.
Example: void sum(int a, int b);
void sum(float a, float b);
void sum(int a, int b, int c);
• Operator overloading means using same operator for multiple purposes i.e. ‘+’ is used
for adding two integers and also to concatenate two strings.
Example: 2+3 = 5
“Hello” + “World” = HelloWorld
• A virtual function a member function which is declared within base class and is re-
defined (Overridden) by derived class.
Example:

class shape { //Parent Class



void area(); //Virtual Function
};

class rectangle: public shape { //Child Class



void area() {
cout<<”Area=”<<l*w;
}
};

Department of Computer Science 51 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

Chapter # 09: File Handling


File:
• It is a collection of bytes stored on a secondary storage device like hard disk.
• These bytes can be characters, words or lines from a textual document or pixels from
graphical image.
• The structure and operations determine the type of file.

File Handling:
• The process of performing different operations on files is called file handling.
• It provides mechanism to write output or read input from file.
• It includes following operations:
o Opening a file
o Reading data from file or writing data to file
o Closing a file

Types of Files:
• There are two types of files based on how they store data.

Text File:
• In text file, data is processed as stream of characters.
• Characters are processed sequentially and in forward direction.
• It is usually open for read, write or append operation.
• It read/write data one character at a time.

Binary File:
• In binary file, data is processed in binary format.
• It is sequence of bytes and each byte consist of 8 bits.
• It is transferred to or from the disk unprocessed.
• It can be processed sequentially or randomly based on an operation.

Stream:
• A logical interface between program and a file is called stream.
• It is flow of data.
• A sequence of characters from an input device to computer is called input stream.
• A sequence of characters from computer to an output device is called output stream.
• A stream is associated with a file using an open operation and it is disassociated from
a file using a close operation.

Text Stream Binary Stream


It is sequence of character. It is sequence of bytes.
Translation occurs in text stream. No translation occurs in binary stream.
It is less efficient than binary stream. It is more efficient than text stream.
It can be used only for text data. It can be used for different types of data.

Data files: Why data files are required in any programing language?

Department of Computer Science 52 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• A data file is collection of related records.


• A record contains data about an entity.
• Data files are used to save any type of data.
• It is stored on secondary storage permanently.
• Computer programs need large amount of input data.
• It is very difficult to input data from keyboard each time the program is executed.
• A slight mistake in data can produce incorrect results and the entire data must be
entered again.
• To solve this problem, the input data is stored in a file on the disk.
• The computer program reads data from the data file.

Opening a File:
• The open() function is used to open a file in c++.
• This function makes a logical stream between I/O device and the memory.
• It opens a file for different operations i.e., write, read, append etc.
• It is member function of fstream class.
• Syntax: object.open(file_name/file path,mode);
• Example: ifstream myfile;
myfile.open(“example.txt”,ios::in);

Closing a File:
• The close() function is used to close a file in c++.
• This function disassociates a logical stream between I/O device and the memory.
• It is member function of fstream class.
• Syntax: object.close();
• Example: myfile.close();

File Access Modes:


• It determines the type of operation to be performed on file.
• It comes as an argument along with file name in open function.

Mode Description
ios::in Open for input operations (reading a file)
ios::out Open for output operations (writing a file)
ios::binary Open in binary mode.
ios::ate Open for output operation and move control to the end of file.
ios::app Open for append at the end of file.
ios::trunc Open for output operations, existing contents are deleted and replaced by
new one.

Class Default Mode Parameter


ofstream ios::out
ifstream ios::in

Department of Computer Science 53 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

fstream ios::in|ios::out
Opening File in Binary mode:
• The open() function along with ios::binary mode is used to open a file in binary mode.
• “write” method is used to write in binary file. It is member function of fstream class.
• Syntax: object.open(file_name/file path,ios::binary);
• Example: ifstream myfile;
myfile.open(“example.txt”,ios::binary);
Writing into File(Output Stream):
• To write into file in c++ insertion operator is used with object name.
• Syntax: object_name <<string/variable;
• Example: myfile<<”This is example program.”;

Reading a File(Input Stream):


• To read data from file in c++ extraction operator(>>) is used with object name.
• One variable read only one word because it will stop reading after space.
• More than one variable can be used for reading.
• Syntax: object_name >>variable;
• Example: myfile>>ch>>n;

End of File Function eof():


• This function returns true if the current position of the pointer is at the end of file and
false otherwise.
• It is member function of fstream class.
• It tells the position of cursor to the compiler.
• Syntax: object_name.eof();
• Example: myfile.eof();

Beginning of File Function bof():


• This function returns true if the current position of the pointer is at the start of file and
false otherwise.
• It tells the position of cursor to the compiler.
• It is member function of fstream class.
• Syntax: object_name.bof();
• Example: myfile.bof();

The get() Function:


• It is used to read data character by character from file.
• It is member function of ifstream class.
• Syntax: object_name.get(variable);
• Example: myfile.get(ch);

The put() Function:


• It is used to write data character by character in file.
• It is member function of ofstream class.
• Syntax: object_name.put(variable);

Department of Computer Science 54 Prof. Affefah Qureshi


Punjab College H-11/4, Islamabad HSSC-II

• Example: myfile.put(ch);

The getline() Function:


• It is used to read string from file.
• It is member function of string class.
• Syntax: getline(variable,size);
• Example: getline(ch,20);

Department of Computer Science 55 Prof. Affefah Qureshi

You might also like