0% found this document useful (0 votes)
6 views67 pages

10 Comp Notes

Uploaded by

doxici9828
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)
6 views67 pages

10 Comp Notes

Uploaded by

doxici9828
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/ 67

Computer Science

for Grade X
According to New Syllabus – Sindh Textbook Board(STBB)

Shehzaib Yousuf Khan 2024 Computer Science


Class X: Computer

Table of Contents
0 CONTENTS
0 Contents ......................................................................................................................... i
1 PROBLEM SOLVING AND ALGORITHM DESIGNING .......................................................... 1
1.1 Problem Solving ..................................................................................................... 1
1.1.1 Problem Solving Process:.................................................................................... 1
1.1.2 Problem Solving Example Related to Real Life: ..................................................... 1
1.1.3 Problem Solving Example Related to Computer Programming: ............................. 2
1.2 Algorithm ............................................................................................................... 3
1.2.1 Use of Algorithm in Problem Solving .................................................................... 3
1.2.2 Qualities of a Good Algorithm.............................................................................. 3
1.2.3 Examples of Algorithm ........................................................................................ 4
1.3 Flowchart ............................................................................................................... 6
1.3.1 Use of Flowchart in Problem Solving .................................................................... 6
1.4 Data Structure ........................................................................................................ 8
1.4.1 Linear Data Structures ........................................................................................ 8
1.4.2 Non-linear Data Structures ............................................................................... 11
2 BASICS OF PROGRAMMING IN C++ ............................................................................... 14
2.1 Computer Program ............................................................................................... 14
2.1.1 Syntax: ............................................................................................................. 14
2.1.2 Programming Language: ................................................................................... 15
2.1.3 Language Translator: ........................................................................................ 18
2.1.4 Errors: .............................................................................................................. 20
2.2 Integrated Development Environment ................................................................... 21
2.2.1 Benefits of IDE .................................................................................................. 21
2.2.2 Components of IDE........................................................................................... 21
2.3 C++ Programming Language ................................................................................. 22
2.3.1 Reserved words ................................................................................................ 23
2.3.2 Data Types ....................................................................................................... 24
2.3.3 Identifier: Constant and Variable ....................................................................... 24
2.3.4 String in C++ ..................................................................................................... 26
3 INPUT/OUTPUT HANDLING IN C++ ................................................................................ 27
3.1 Basic Structure of C++ .......................................................................................... 27

P a g e |i Shehzaib Yousuf Khan ©


Class X: Computer

3.1.1 Pre-processor Directives:.................................................................................. 27


3.1.2 Main Function Header:...................................................................................... 27
3.1.3 Body of the Program:......................................................................................... 27
3.2 Comment statement in C++ .................................................................................. 28
3.2.1 Single-line comment ......................................................................................... 28
3.2.2 Multi-line comment .......................................................................................... 28
3.3 Input and Output Handling .................................................................................... 29
3.3.1 Input and Output Libraries in C++ ...................................................................... 29
3.3.2 Input and Output Libraries in C .......................................................................... 29
3.3.3 Output Stream .................................................................................................. 30
3.3.4 Input Stream .................................................................................................... 30
3.4 Operators:............................................................................................................ 32
3.4.1 Arithmetic Operator: ......................................................................................... 32
3.4.2 Relational Operator: ......................................................................................... 33
3.4.3 Assignment Operator ........................................................................................ 34
3.4.4 Increment Operator: ......................................................................................... 35
3.4.5 Decrement Operator:........................................................................................ 35
3.4.6 Logical Operator: .............................................................................................. 37
3.4.7 Arithmetic Assignment Operator: ...................................................................... 38
3.5 Escape Sequence: ................................................................................................ 39
4 CONTROL STRUCTURE IN C++ ...................................................................................... 42
4.1 Program Structure ................................................................................................ 42
4.2 CONTROL STRUCTURE ......................................................................................... 42
4.2.1 DECISION STATEMENT ..................................................................................... 43
4.2.2 LOOP STATEMENT ............................................................................................ 48
4.2.3 JUMP STATEMENT ............................................................................................. 51
What is the purpose of the default statement in C++? .................................................. 54
Why do we make a block of statements using braces { }? ............................................. 54
5 FUNCTIONS IN C++....................................................................................................... 55
5.1 Pre-defined Functions .......................................................................................... 55
5.1.1 Features of pre-defined functions: .................................................................... 55
5.1.2 Examples of pre-defined functions: ................................................................... 56
5.2 User-defined Functions ........................................................................................ 57
5.2.1 Function declaration......................................................................................... 57
5.2.2 Function definition............................................................................................ 58
5.2.3 Function calling ................................................................................................ 58

P a g e | ii Shehzaib Yousuf Khan ©


Class X: Computer

5.3 Local and Global Variable ..................................................................................... 60


5.3.1 Local Variable................................................................................................... 60
5.3.2 Global Variable ................................................................................................. 60
5.3.3 Examples of user-defined functions: ................................................................. 59
5.4 Header Files in C++ .............................................................................................. 62

P a g e | iii Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

1 PROBLEM SOLVING AND ALGORITHM DESIGNING

1.1 PROBLEM SOLVING


“The process of identifying a challenge, analyzing it, and developing and
implementing a solution to achieve a desired outcome is called problem
solving.”

It involves logical thinking, creativity, and decision-making.

Problem:
“A situation or task that requires a solution, typically involving data processing,
analysis, or decision-making to meet certain requirements or achieve a desired
outcome is called a problem.”

1.1.1 Problem Solving Process:


Problem-solving is an essential skill that contributes to individual success, organizational
efficiency, and overall societal advancement.

Importance of Problem Solving:


1. It encourages analytical thinking and helps individuals assess situations logically,
improving their decision-making skills.
2. Problem-solving often leads to the development of new ideas, products, or processes,
driving creativity and innovation in various fields, including technology and business.
3. Successfully solving problems increases confidence, encouraging individuals to take on
new challenges.

1.1.2 Problem Solving Example Related to Real Life:


1. Define the Problem:

Clearly describe what the problem is and what needs to be solved.

Example:

The car won’t start, and the battery appears to be dead.

P a g e |1 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

2. Generate Alternative Solutions:

Think of different ways to solve the problem.

Example:

• Solution 1: Jump-start the car using jumper cables and another car.

• Solution 2: Replace the battery with a new one.

• Solution 3: Check if the battery terminals are corroded and clean them.

3. Evaluate and Select an Alternative:

Analyze the advantages and disadvantages of each solution, and pick the best
one based on factors like efficiency and simplicity.

Example:

• Solution 1: jump-start is quick and affordable if the battery is just temporarily


drained.

• Solution 2: replace battery is more expensive and only necessary if the battery is
fully dead.

• Solution 3: clean terminals is simple and might solve the problem if corrosion is the
issue.

Choose Solution 1 (jump-start) first, as it’s quick and might resolve the issue without
major effort.

4. Implement and Follow Up on the Solution:

Execute the chosen solution and ensure it works as expected.

Example:

Use jumper cables to connect to another car and start your vehicle. Once started, let it
run to charge the battery. Afterward, monitor the battery’s performance to see if it holds
a charge.

1.1.3 Problem Solving Example Related to Computer Programming:


1. Define the Problem:

Clearly describe what the problem is and what needs to be solved.

Example: A student needs to write a program to calculate the total price of items in a
shopping cart.

2. Generate Alternative Solutions:

Think of different ways to solve the problem.

Example:

• Solution 1: Write a simple program using a loop to add the price of each item.

• Solution 2: Use an in-built function to calculate the total from a list of prices.

P a g e |2 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

3. Evaluate and Select an Alternative:

Analyze the pros and cons of each solution, and pick the best one based on
factors like efficiency and simplicity.

Example:

• Solution 1 (loop): Suitable for beginners but may take more time.

• Solution 2 (in-built function): Faster and simpler to implement.


Chosen: Solution 2, because it’s quicker and more efficient.

4. Implement and Follow Up on the Solution:

Execute the chosen solution and ensure it works as expected.

Example:

The student writes the program using an in-built function and tests it with different
shopping cart values to ensure the total price is calculated correctly.

1.2 ALGORITHM
“A step-by-step procedure or set of rules designed to perform a specific task or
solve a particular problem is called algorithm.”

It consists of a finite sequence of well-defined instructions, which can be executed in a specific


order to achieve the desired outcome.

1.2.1 Use of Algorithm in Problem Solving


Algorithms are essential in program solving for several reasons:

1. Structure and Clarity:


Algorithms provide a clear framework for understanding the problem which help
programmers to think logically about how to approach a problem.

2. Efficiency:
Well-designed algorithms improve the usage of resource, such as time and memory,
leading to faster and more efficient programs.

3. Problem Breakdown:
Algorithms help break complex problems into smaller, manageable tasks, making it
easier to implement solutions systematically.

1.2.2 Qualities of a Good Algorithm


1. Correctness:
A good algorithm must produce the correct output for all valid inputs.

2. Efficiency:
The algorithm should make the best use of resources, such as time and memory. It
should run quickly and use minimal space.

P a g e |3 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

3. Simplicity:
A simple algorithm is easier to understand, implement, and maintain. It should avoid
the actual computer code.

4. Generality:
A good algorithm should be applicable to a wide range of problems, not just one specific
case. It should work for different inputs and situations.

1.2.3 Examples of Algorithm

Example 1: Sum of Two Numbers

1. Start: Begin the process.

2. Get the First Number: Ask for the first number.

3. Get the Second Number: Ask for the second number.

4. Add the Two Numbers: Combine both numbers together.

5. Show the Result: Tell the user the total (the sum).

6. End: Finish the process.

Example 2: Average of Three Numbers

1. Start: Begin the process.

2. Get the First Number: Ask for the first number.

3. Get the Second Number: Ask for the second number.

4. Get the Third Number: Ask for the third number.

5. Add All Three Numbers Together: Combine all three numbers.

6. Divide by Three: Split the total by three to find the average.

7. Show the Result: Tell the user the average.

8. End: Finish the process.

Example 3: Volume of a Box

1. Start: Begin the process.

2. Get the Length: Ask for the length of the box.

3. Get the Width: Ask for the width of the box.

4. Get the Height: Ask for the height of the box.

5. Multiply Length, Width, and Height: Combine these measurements to find out how
much space is inside the box.

6. Show the Result: Tell the user the volume of the box.

P a g e |4 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

7. End: Finish the process.

Example 4: Calculate Percentage

1. Start: Begin the process.

2. Get the Total Amount: Ask for the total number (this is the whole).

3. Get the Part Amount: Ask for the part of the total you want to find the percentage for.

4. Divide the Part by the Total: Find how much of the total the part is.

5. Multiply by 100: Convert that fraction into a percentage.

6. Show the Result: Tell the user the percentage.

7. End: Finish the process.

Example 5: Fixing a Car Battery

1. Define the Problem: The car won’t start, indicating a potential battery issue.

2. Check Battery Terminals: Inspect the terminals for corrosion and ensure they are
tightly connected.

3. Test Battery Voltage: Use a multimeter to check the battery's voltage.

o If voltage is low, proceed to jump-start the battery.

o If voltage is normal, further diagnose the starting system.

4. Jump-Start the Battery: Connect jumper cables to a working vehicle and try starting the
car.

5. Check for Corrosion: If jump-starting works, clean terminals and check for further
issues.

6. Follow Up: Monitor the battery's performance over the next few days.

Example 6: Calculate Total Price of Items in a Shopping Cart

1. Define the Problem: Calculate the total price of items in a shopping cart.

2. Input Prices: Create a list or array of item prices.

3. Initialize Total: Set a variable for total price to 0.

4. Sum Prices: Iterate through the list of prices and add each price to the total.

5. Output Total: Display the total price.

P a g e |5 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

1.3 FLOWCHART
“A graphical representation of step-by-step instructions in a sequence to describe a
computer program using shapes and objects is called flowchart.”

Flowchart consists of five basic graphical objects to describe a computer program.

1. Start/Stop (Oval)
2. Flow Path (Arrows)
3. Input/Output (Parallelogram)
4. Process (Rectangle)
5. Decision/Condition (Diamond)

Element Description Symbol


Indicates the beginning and the
Start/End Oval
end of the flowchart.
Shows the direction of the flow
Flow Path Arrow
from one step to another.
Represents the data input or
Input/Output output (e.g., entering data, Parallelogram
displaying results).
Represents a step or action in
Process the process (e.g., calculations Rectangle
or instructions).
Indicates a point where a
Decision decision must be made, leading Diamond
to different branches.

1.3.1 Use of Flowchart in Problem Solving


1. Visual Representation:

Flowcharts provide a clear and visual way to represent complex processes that helps
programmers understand the sequence of step-by-step instructions.

2. Simplification of Processes:

By breaking down a problem into smaller steps, flowcharts make it easier to identify and
analyze each part of the process that helps in understanding the overall problem more
clearly.

3. Easy to Understand:

Flowcharts use standard symbols and shapes, making them easy to read and
comprehend.

P a g e |6 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

Flowchart Algorithm
A flowchart is a visual representation of a An algorithm is a step-by-step procedure or set of
process or algorithm using symbols and arrows. rules for solving a problem.

Flowcharts use shapes (like ovals, rectangles, Algorithms are usually written in plain language or
diamonds) connected by arrows to show the pseudocode, listing steps in a sequential manner.
flow of steps.
Flowcharts help visualize the sequence of Algorithms provide a clear, logical approach to
actions and decisions, making complex problem-solving, outlining exactly what needs to
processes easier to understand. be done without visualization.
Flowcharts are often used for presentations and Algorithms are used primarily in programming and
to explain processes visually to others. software development to plan and implement
solutions.

Flowchart Example 1: Flowchart Example 2:

A computer program to find an A computer program to input marks and calculate


average of three numbers. sum and percentage. If percentage is above 70 then
print “Well done”, otherwise “Work hard”.

P a g e |7 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

1.4 DATA STRUCTURE


“A way of organizing, managing, and storing data so it can be accessed and
modified efficiently is called data structure.”

Data structures define how data is arranged in memory and how it can be manipulated for
various operations like insertion, deletion, searching, and sorting.

Data structures are mainly classified into two types: linear and non-linear.

1.4.1 Linear Data Structures


“A type of data structure where elements are arranged sequentially, one after
the other, is known as linear data structure.”

In these structures, each element is connected to its previous and next element, forming a
linear sequence.

Linear data structure includes stack, queue and array.

Stack:
“A linear data structure that works with a specific order for adding and removing
items at only one end is called stack.”

It follows a specific order for adding and removing items known as LIFO (Last In, First Out) like a
real-world stack of items, such as a stack of books or plates.

Key Characteristics of a Stack:

1. LIFO (Last In, First Out):

The last item added to the stack is the first one to be removed. Imagine stacking plates—
when you add a new plate, you place it on top. When you remove one, you take the plate
from the top.

2. Push Operation:

Adding an item to the stack is termed as push. The new item is always placed on top of
the stack.

P a g e |8 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

3. Pop Operation:

Removing an item from the stack is termed as pop. You can only remove the item from
the top of the stack.

4. Stack overflow:

If the stack is already full, it will return an overflow error which means no more items
can be added.

5. Stack underflow:

If the stack is already empty, it will return an underflow error which means no more
items can be removed.

Queue:
“A linear data structure that follows a particular order in which the items are
added from one end and removed from the another is called queue.”

It follows a FIFO (First In, First Out) order which works like a real-life queue (line) of people
waiting for something, like in a ticket line or at a grocery store.

Key Characteristics of a Queue:

1. FIFO (First In, First Out):

The first item added to the queue is the first one to be removed. Think of a line of people:
the person who enters the line first is the first to leave.

2. Enqueue Operation:

Adding an item to the queue is termed as enqueue operation. The new item is always
added to the back of the queue.

3. Dequeue Operation:

Removing an item from the queue is called dequeue operation. You can only remove
the item from the front of the queue.

P a g e |9 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

4. Front and Rear:

o The front of the queue is where items are removed (dequeued).

o The rear of the queue is where new items are added (enqueued).

Array:
“A linear data structure which holds a list of finite data elements of same data
type, and each element of array is referenced by a set of index of consecutive
numbers is called array.”

Think of an array like a row of lockers, where each locker (or slot) holds one item, and each item
can be accessed by its position (index) in the array.

Key Characteristics of an Array:

1. Fixed Size:

Once an array is created, it has a fixed number of slots (or spaces), and you cannot
change the size. For example, if you create an array of 6 elements, it will always hold 6
elements.

2. Same Data Type:

All the elements in an array must be of the same type.

P a g e | 10 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

For example, if you create an array to store numbers, all the elements must be
numbers; if it's for names, all elements must be strings (text).

3. Indexing:

Each element in an array has a position number called an index. The first element is at
position 0, the second at position 1, and so on.

4. Efficient Access:

Any element can be quickly accessed by using its index number, making it easy to find
and use specific data from the array.

1.4.2 Non-linear Data Structures


“A type of data structure where elements are arranged in a hierarchical or
interconnected manner, and each element can be connected to more than one
element is called non-linear data structure.”

There is no strict sequence to follow in non-linear data structure.

Non-linear data structure includes tree and graph.

Tree:
“A hierarchical non-linear data structure that consists of nodes connected by
edges is called tree.”

It resembles an upside-down tree, with a single root at the top and branches spreading
downwards.

Each node can have multiple child nodes but only one parent node (except for the root, which
has no parent).

Key Characteristics of a Tree:

1. Root Node:
The top node of the tree, from which all other nodes descend.

2. Parent Node:
Each node (except the root) is a parent of the nodes connected to it below.

3. Child Node:
Each node that is descendant of another node is called child of that node.

4. Edge:
Link connecting two nodes.

Binary Tree
“A tree where each node has at most two children (known as left child and right
child) is known as a binary tree.”

Each subtree has either one or two children.

P a g e | 11 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

General Tree
“A tree that contains any number of subtrees is known as a general tree.”

Graph:
“A collection of nodes (or vertices) connected by edges is called a graph.”

Unlike trees, graphs can have cycles (where it can return to the same node by following edges)
and do not have a strict hierarchical structure.

Key Characteristics of a Graph:

1. Vertices (Nodes):
The points in a graph that represent entities.

2. Edges:
The connections between the vertices that can represent relationships.

P a g e | 12 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 1: Problem Solving and Algorithm Designing

3. Directed and Undirected:

o Directed Graph: Edges have a direction.

“A type of graph that contains directed edges, that means its edges are pointing
in a particular direction is known as directed graph.”

o Undirected Graph: Edges have no direction.

“A type of graph that does not contain any direction associated with its nodes,
that means its edges are non-directional is known as undirected graph.”

Directed Graph Undirected Graph

Differences Between Queue and Stack


Queue Stack

Queue follows FIFO (First In, First Out). Stack follows LIFO (Last In, First Out).

It uses Enqueue (add to rear) and Dequeue It uses Push (add to top) and Pop (remove
(remove from front). from top).
It can access the front item directly. It can access only the top item directly.

Example: Line of customers at a bank Example: Stack of plates


(first to arrive is served first). (last plate added is the first to be taken).

Differences Between Tree and Graph

Tree Graph

Tree is a hierarchical data structure with a Graph can have any arrangement of nodes,
single root node. including cycles.
Each node has one parent and can have Nodes can be connected to any number of
multiple children. other nodes.
Tree is always directed (parent to child). Graph can be directed or undirected.

It cannot have cycles (looping back to the It can have cycles (returning to the same
same node is not allowed). node is possible).

P a g e | 13 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

2 BASICS OF PROGRAMMING IN C++

2.1 COMPUTER PROGRAM


“A sequence of instructions written in a programming language that tells a
computer how to perform specific tasks or solve particular problems is called
computer program.”

A computer program contains data and instruction which involves understanding fundamental
concepts in any programming language. The fundamental concepts are:

1. Data Types
2. Constants and Variables
3. Arrays and Strings
4. Input and Output Streams
5. Operators
6. Control Structures
7. Functions

In any programming language, there are keywords (or reserved words) for program statements
that is combined with a set of rules called syntax.

2.1.1 Syntax:
“The set of rules that define the structure of statements or instructions in a
programming language is called syntax.”

Importance of Syntax:
4. Syntax ensures the correct structure of code, which is crucial in any programming
language, allowing it to be understood by the compiler and executed by the machine.
5. Syntax provides the precise instructions for the language translation process.
6. Without proper syntax, the program cannot function correctly causing errors.

P a g e | 14 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

2.1.2 Programming Language:


“A formal language composed of a set of instructions, data and syntax used to
communicate with the computer system is called programming language.”

1. Low-Level Language
“A type of programming language that is very close to machine code or
assembly language which directly interacts with a computer’s hardware.”

 It directly translates to machine instructions.


 It directly controls over hardware resources that results in fast execution time.
 It requires deep knowledge of system architecture.
 It is difficult for humans to read and write.

Machine Code: Binary code that is executed directly by the CPU.


Example: 10110000 01100001.

Assembly Language:
Mnemonic codes to represent machine instructions.

Example: MOV, ADD, SUB used in x86 assembly.

Mnemonic Notations
2. Mid-Level Language
“A type of programming language that provides a balance between low-level and
high-level language by offering abstraction from machine code as well as direct
interaction with a computer’s hardware.”

 It provides high-level functionality like functions and control structures as well as


directly manage hardware resources.
 It is closer to hardware than high-level language that results in more efficient code
execution.
 It requires some knowledge of system architecture such as memory locations.
 It is moderately understandable for humans to read and write.

P a g e | 15 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

Example: C language used for system programming such as in embedded systems,


robots, and operating systems.

3. High-Level Language
“A type of programming language that is designed to be more human readable
and closer to natural languages, allowing to focus on problem solving rather
than managing hardware resources.”

 It handles hardware resources management automatically which allows programmers


to focus on solving problems.
 It can often run on different types of systems with little to no modification, but execution
time is greater than low-level and mid-level languages.
 The programmer does not need to manage resources directly.
 It is very easily understandable for humans to read and write.

Example: Python, Java, JavaScript, C++ C#.

Python: It is famous for its simplicity which is easily used by programmers in Artificial
Intelligence (AI), machine learning, and automation.

Java: It is cross-platform that can be used in enterprise systems, mobile applications,


and large-scale web applications.

JavaScript: It is used for front-end web development and interactivity.

C++: It is known for system software, scientific computations, real-time applications,


and performance-critical tasks.

C#: It is primarily used for Windows applications, game development (Unity), and
enterprise solutions.

P a g e | 16 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

Low-level Language High-level Language


1. It is user-friendly, written in English-
1. Machine-friendly, directly understood
like syntax, easily understood by
by the computer.
humans.

2. It requires assembly language to 2. It requires a compiler or interpreter to


convert into machine code. convert into machine code.

3. It is non-portable which means that it 3. It is portable which can be translated


cannot be executed on all machines. to run on various machine types.

4. It has abstract hardware and less


4. It provides direct access to memory
direct access making it less-memory
and hardware.
efficient.
5. It is easier to code and maintain due
5. It is difficult to code and maintain due
to simplicity and higher-level
to complexity and lack of abstraction.
abstractions.

P a g e | 17 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

Machine Language Assembly Language


1. Machine language consists of binary 1. Assembly language uses mnemonic
(0s and 1s) instructions directly codes to represent machine language
executed by the CPU. instructions.
2. It is human-readable, as it uses
2. It is not human-readable because of
symbolic representations such as
binary format.
MOV, ADD.
3. There is no abstraction from 3. It provides a slight abstraction using
hardware because it directly symbolic instructions but still closely
interacts with the processor. tied to machine code.
4. It is also machine-dependent, but
4. It is machine-dependent and cannot easier to modify compared to
be used across different systems. machine code due to symbolic
mnemonics.

2.1.3 Language Translator:


“A system software which converts source code into machine code is known as
language translator.”

Source Code: A program written in any language usually a human-readable code is


called as source code.

Machine Code: Binary code that the process in computer system can directly execute.

P a g e | 18 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

Roles of Translator
1. It converts high-level source code into machine code so that the computer’s hardware
(CPU) can understand and execute the instructions.
2. Translators detect and report syntax errors during the translation process.
3. Translators allow programmers to write in human-readable languages, which are easier
to develop and maintain.

Types of Translators
1. Compiler
“A language translator that is used to convert the source code written in high-
level language into an executable machine code file such as .exe is called
compiler.”

2. Interpreter
“A language translator that is used to read each line of code, translates it into
machine code, and immediately executes it, stopping when it encounters an
error is called interpreter.”

3. Assembler
“A language translator that reads assembly language code and converts it into
machine code that the processor can execute directly is called assembler.”

Compiler Interpreter
1. Compiler translates the entire source
1. Interpreter translates and executes
code into machine code at once
the source code line by line.
before execution.
2. It has generally faster execution as 2. It has slower execution since each
the entire code is compiled into line is translated and executed one at
machine code beforehand. a time.

3. It detects and reports errors for entire 3. It stops at the first error it encounters
code after compilation. and reports errors line by line.

4. It generates an independent 4. It does not generate a separate


executable file such as .exe file. executable file.

P a g e | 19 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

Source Code Object Code


1. Source code is a human-readable 1. Object code is a machine-readable
code written in a high-level or low- intermediate code produced by a
level language. compiler.
2. It is not human-readable since it
2. It is easily understood and modified
contains binary or hexadecimal
by humans.
instructions.
3. It requires a language translator 3. It requires further linking and
(compiler or interpreter) to be assembly to become executable
converted into object code. machine code.
4. It is portable across different
4. It is not portable and usually specific
platforms, depending on the
to a particular machine or platform.
language.

2.1.4 Errors:
“An issue or problem in the code that causes the program to fail during
compilation or execution, causes unexpected results, or lead to the program
crashing is called an error.”

There are generally three types of errors in programming:

1. Syntax Error
“The programming error that occurs when the code violates the rules or
grammar of the programming language is called syntax error.”

Syntax error is detected by the compiler. If there are any syntax errors during compilation, the
program will not compile. Examples:

1. Missing semicolon ; after statement.


2. Missing parenthesis ( ) in statements.
3. Write code to print the value of a variable without declaring it.

P a g e | 20 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

2. Run-time Error
“The programming error that occurs during program execution (run-time) after
successful compilation is called run-time error.”

Run-time error often occurs due to invalid operations, such as:

1. Division by zero
2. Accessing invalid memory.
3. Array out of bounds

3. Logical Error
“The programming error that occurs when the program compiles and runs but it
produces incorrect or unintended results is called logical error.”

Logical error is not caught by the compiler or during execution. Example:

1. Using incorrect operator such as using – instead of + for addition.


2. Incorrect loop condition
3. Misplaced parenthesis ( ) in an equation

2.2 INTEGRATED DEVELOPMENT ENVIRONMENT


“A software application that provides comprehensive tools and features to help
developers write, test, and debug code is called integrated development
environment (IDE).”

2.2.1 Benefits of IDE


1. The goal of an IDE is to streamline the development process by offering everything
developers need in one platform.
2. It integrates various tools like a text editor, compiler, debugger, and other utilities into a
single interface, simplifying the software development process.
3. Automatically checks for errors to ensure top quality code.

2.2.2 Components of IDE


Dev-C++ is a popular IDE for C++ programming language. It provides a user-friendly
environment with several components integrated into a single platform. The components are:

1. Source Code Editor:


The editor highlights syntax and often provides other features like code compilation
and line numbering to facilitate easier code writing and navigation.

2. Compiler:
The compiler translates the source code written in a high-level language into machine
language forming an executable machine code file in .exe.

P a g e | 21 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

3. Debugger:
The debugger helps in finding and fixing errors in the program, allowing programmers to
inspect their code step by step.

4. Linker:
The linker opens the compiled program file and links it with the referenced library files
as needed.

5. Loader:
The loaded loads the executable file into computer’s memory and initiates the
processing of the instructions in the CPU.

2.3 C++ PROGRAMMING LANGUAGE


“A general purpose, object-oriented programming language that extends the C
programming language.”

This high-level language was developed by Bjarne Stroustrup in 1983 as an enhancement to C


(mid-level language).

The basic building blocks (tokens) of C++ programs include:

1. Keywords (or Reserved words)


2. Identifiers (Variable, Functions or Classes)
3. Literals (Numeric values, Characters or Strings)
4. Operators

Keywords: Reserved words with special meanings in C++ syntax.

Identifiers: Names given to variables, functions, classes, etc., by the programmer.

Literals: Fixed values in the source code such as numbers, characters, and strings.

Operators: Symbols that represent operations including mathematical calculations,


comparison and logic (example: +, -, *, >, &&).

P a g e | 22 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

2.3.1 Reserved words


“The foundation of the C++ programming language that controls everything from
data type, memory management, and control flow to advanced features
including object-oriented programming.”

Understanding and using these keywords effectively is essential for writing efficient and robust
C++ programs.

Keyword Description
int Defines an integer data type.
float Defines a floating-point number.
double Defines a double-precision floating-point number.
char Defines a single character.
void Specifies that a function does not return any value.
bool Defines a Boolean value (true or false).
if Starts a conditional statement.
else Specifies an alternative branch of an if statement.
switch Allows selection between multiple options.
case Defines a case in a switch statement.
for Starts a loop that repeats a block of code a specific number of times.
while Starts a loop that repeats a block of code as long as a condition is true.
do Starts a do-while loop, where the condition is checked after the block of code is
executed.
return Exits a function and optionally returns a value.
break Exits a loop or switch statement prematurely.
continue Skips the remaining code in the current iteration of a loop and proceeds with the next
iteration.
const Declares a constant value that cannot be changed.
namespace Defines a scope for identifiers to avoid naming conflicts.
TRUE Represents the Boolean value true.
FALSE Represents the Boolean value false.

P a g e | 23 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

2.3.2 Data Types


“A token or fundamental building block of programming language that are
directly supported by the compiler and include integers, floating-point numbers,
characters, and Boolean values.”

These are the fundamental data types built into the language:

Data Description Example Size Range


Type
int Integer numbers int age = 25; 4 bytes -2,147,483,648 to
(without decimal points) 2,147,483,647
float Single-precision floating- float temp = 36.5; 4 bytes 3.4E-38 to 3.4E+38
point numbers
double Double-precision floating- double pi = 3.14159; 8 bytes 1.7E-308 to 1.7E+308
point numbers
char Single character char grade = 'A'; 1 byte -128 to 127
(enclosed in single quotes) (ASCII characters)
bool Boolean values bool flag = true; 1 byte true (1) or false (0)
(true or false)
void No value (used in function void func(); N/A N/A
declarations)

2.3.3 Identifier: Constant and Variable


“The names given to various entities such as constants, variables, functions,
arrays, etc, that are used to uniquely identify in the code and defined by the
programmer, are called identifiers.”

Constant:
“A data item whose value cannot change during the execution of the program is
called constant.”

Constant can be used in two ways:

1. Literal constant
2. Defined constant

Literal Constant: (Also called Literal)


“Any fixed numeric or non-numeric value that is explicitly stated in the program
code is called literal.”

Literal constants can be numbers, characters, strings, or any other data type that directly
encodes the data into the source code:

1. Integer Literals: Direct numerical values. (Example: 5, 100, -33).


2. Floating-point Literals: Numbers with decimal points.
(Example: 3.14, 0.1, -0.33).
3. Boolean Literals: The true and false (or 1 and 0) values.

P a g e | 24 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

4. Character Literals: Single characters surrounded by single quotes.


(Example: ‘a’, ‘1’, ‘@’)
5. String Literals: Sequences of characters surrounded by double quotes.
(Example: “Hello, world!”, “C++ programming”)

Defined Constant:
“A named identifier that allows programmer to assign a name to a literal
constant at the beginning of the source code is called defined constant.”

Defined constants are named and needed to be declared in the source code which can be done
in two ways:

1. Using #define

It allows the programmer to define constant without specifying the data type.

Example: #define PI 3.14

2. Using const

It requires declaration of the data type of the constant before assigning the literal.

Example: const float pi = 3.14;

Variable:
“A named identifier that allows programmer to assign a name to a value which
can change throughout the execution of a program is called a variable.”

Variables are used to store data that can be accessed and manipulated by the program.

Rules for Naming Variables:


1. Variable must begin with a letter or underscore.
Example: myVar, _age.
2. Variable names can contain letters, digits and underscores.
Example: count123, v_f.
3. Variable names cannot start with a digit.
Example: 123count is wrong.
4. C++ Keywords cannot be used as Variable names.
Example: int is wrong.
5. Variable names are case-sensitive.
Example: myVar and MyVar are different.
6. Special characters cannot be used as Variable names.
Example: my#Var and my-Var are wrong.

Variable Declaration
“When an identifier is created by the compiler with a specific name and data
type in the program, it is called variable declaration.”

It reserves memory for that variable but does not assign any initial value.

Syntax: data_type variable_name;

P a g e | 25 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 2: Basics of Programming in C++

Example: int marks;

For assigning or input marks to a variable, it can be declared with an integer data type and a
unique name.

Variable Initialization
“When a variable is declared with a specific name and data type in the program,
assigning an initial value to the variable is called variable initialization.”

It also can be performed at the time of declaration as well as after the declaration.

Syntax: data_type variable_name = value;

Example: int marks = 64;

Variable Assignment
“Changing the value stored in an already declared variable, is called variable
assignment.”

Syntax: variable_name = value;

Example: marks = 55;

2.3.4 String in C++


“Variables or Literals that can represent sequences of characters enclosed in
double quotes is called string in C++.”

 A variable can be declared with string data type just like any other data type.
 A string can be initialized with a string literal or by user input.
 It requires <string.h> function header.

P a g e | 26 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3 INPUT/OUTPUT HANDLING IN C++

3.1 BASIC STRUCTURE OF C++


A C++ program can be divided into several logical parts, each serving a specific purpose in
program execution. However, the basic program structure of C++ consists of three parts:

8. Pre-processor Directives
9. Main Function Header
10. Body of the program

3.1.1 Pre-processor Directives:


“Such instructions given to the compiler to pre-process the information before
actual compilation of code starts, are called pre-processor directives.”

#include <iostream>

This part contains #include or #define statements that are processed before compilation of
code begins, which allows to include libraries such as <iostream> library for input and output
operations.

using namespace std;


Particularly in C++, a namespace is attached to pre-processor directives that allows to group
related functions, variables, and classes provided by Standard Library std.

3.1.2 Main Function Header:


“The mandatory function which serves as the entry point in the C++ program and
when executed, all the statements inside it are run, is called main function
header.”

int main()

The return type of main() or main(void) is integer int which means that it returns an
integer value to indicate success or failure when the program exits on return.

The beginning of the body of the program” or main function is represented by opening curly
braces.

The ending of the body of the program or main function is represented by opening curly braces.

3.1.3 Body of the Program:


“The set of statements or code block that perform the program’s logic like
calculations, conditionals, loops and more is called body of the program

P a g e | 27 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

statement;

These are instructions that perform particular task and ended using statement terminator ;

A statement could be anything such as:

Output: cout<< Input: cin<< variable declaration: int a;

initialization: a = 2; Operation: a + b; or more.

return 0;

The return statement at the end of the body of main function indicates the program has
finished successfully. By convention, a return value of 0 means the program executed
successfully.

3.2 COMMENT STATEMENT IN C++


“Such statement that is ignored by the compiler and do not affect the execution
of the program is known as comment statement.”

C++ supports two types of comments:

1. Single-line comments
2. Multi-line comments

3.2.1 Single-line comment


“Such comment statement which is used by programmer to write comments in
a single line without affecting the execution of the program.”

 Single-line comments begin with // and extend to the end of the line.
 Everything after // on that line is considered a comment and is ignored by the compiler.

OUTPUT

3.2.2 Multi-line comment


“Such comment statement which is used by programmer to write comments in
multiple lines continuously without affecting the execution of the program.”

 Multi-line comments begin with /* and end with */. They can span multiple lines.
 Everything between /* and */ is considered a comment and is ignored by the compiler.

P a g e | 28 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

OUTPUT

3.3 INPUT AND OUTPUT HANDLING


3.3.1 Input and Output Libraries in C++

C++ offers a variety of libraries for handling input and output operations. However, <iostream>
is the most commonly used library in C++ for console input/output operations.

<iostream> provides objects like cin>> and cout<< for input/output operations.

3.3.2 Input and Output Libraries in C

In C, several libraries provide different kinds of input/output capabilities:

<stdio.h>

The primary library for handling standard input/output (I/O) operations. Functions in <stdio.h>
include:

1. scanf() for formatted input


2. printf() for formatted output
3. getchar() and putchar() for single-character input/output

<conio.h>
It provides console I/O functions but is non-standard and used in some environments (like
Turbo C++). Functions include

1. getch()
2. getche()
3. clrscr()

It is generally not available in modern compiler like DevC++ and does not provide direct output
functions similar to printf() or cout<<.

P a g e | 29 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3.3.3 Output Stream


“Such instruction or statement in program structure that are used to hold output
or result for a particular device and directs the flow of bytes from the main
memory to the device is called output stream.”

Output Description
Statements
cout<<

C++ Library: OUTPUT


<iostream>

puts()

C Library:
<cstdio>
OR OUTPUT
<stdio.h>

printf()

C Library:
<cstdio>
OR OUTPUT
<stdio.h>

There is no output stream for <conio.h>. It does not feature in modern compiler like DevC++
but it can be used with old compiler like Turbo C++ or Borland C++.

3.3.4 Input Stream


“Such instruction or statement in program structure that are used to hold input
from a data producer (keyboard, file or network) and directs the flow of bytes
from the device to the main memory is called input stream.”

Input Description
Statements
cin>>

C++ Library:
<iostream>

OUTPUT

P a g e | 30 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

Input Description
Statements
getch() The getch() reads a character without displaying it.

C Library:
<conio.h>

OUTPUT

getche() The getche() reads and displays the character.

C Library:
<conio.h>

OUTPUT

getchar() getchar() reads a single character and waits for the user to press Enter.

C Library:
<cstdio>
OR
<stdio.h>

OUTPUT

gets() gets() reads a line of input (a string) until a newline is encountered.

C Library:
<cstdio>
OR
<stdio.h>

OUTPUT

P a g e | 31 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3.4 OPERATORS:
“A symbol that performs specific function on variable and values is called
operator.”

The commonly used types of operators in C++ are as follows:

1. Arithmetic Operator
2. Relational Operator
3. Assignment Operator
4. Increment Operator
5. Decrement Operator
6. Logical Operator
7. Arithmetic Assignment Operator

3.4.1 Arithmetic Operator:


“Such operator that is used to calculate the values of two operands and returns
an integer or floating-point value is known as arithmetic operator.”

1. Addition Syntax: a + b

“An arithmetic operator which adds two operands is known as addition


operator.”

2. Subtraction Syntax: a – b

“An arithmetic operator which subtracts right operand from the left is known as
subtraction operator.”

3. Multiplication Syntax: a * b

“An arithmetic operator which multiplies two operands is known as


multiplication operator.”

4. Division Syntax: a / b

“An arithmetic operator which divides the left operand by the right operand is
known as division operator.”

5. Modulus Syntax: a % b

“An arithmetic operator which returns the remainder of the division of the left
operand by the right operand is known as modulus operator.”

Both the operands must be integer type (int) only. If they


are of the floating-point type (float), then a run-time error
occurs.

P a g e | 32 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3.4.2 Relational Operator:


“Such operator that is used to compare two operands and returns a Boolean
value (0 or 1) is known as relational operator.”

1. Equal to Syntax: a == b

“A relational operator that checks if the values of both operands are equal is
known as equal to operator.”

2. Not equal to Syntax: a != b

“A relational operator that checks if the values of both operands are not equal is
known as not equal to operator.”

3. Greater than Syntax: a > b

“A relational operator that checks if the left operand value is greater than the
right is known as greater than operator.”

4. Less than Syntax: a < b

“A relational operator that checks if the left operand value is less than the right is
known as less than operator.”

5. Greater than or equal to Syntax: a >= b

“A relational operator that checks if the left operand value is greater than or
equal to the value of the right operand is known as greater than or equal to
operator.”

P a g e | 33 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

6. Less than or equal to Syntax: a <= b

“A relational operator that checks if the left operand value is less than or equal
to the value of the right operand is known as less than or equal to operator.”

3.4.3 Assignment Operator


“Such operator that is used to assign a value to a variable is called assignment
operator.”

 The variable is created first by declaration. Example: int count;


 This allocates the variable to a memory location in the system unit of the computer such as
RAM.
 The initialization of variable is the very first assignment of a value to the variable which stores
to that memory location.
 Assignment operator is represented by equal sign, that is =.
 Example: count = 9;

P a g e | 34 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3.4.4 Increment Operator:


“Such unary operators that require only one operand and perform an operation
of increasing the value of the operand by 1 is called increment operator.”

1. Pre-increment operator Syntax: ++a

“Such increment operator that increases the value of the operand by 1 before
using its value.”

2. Post-increment operator Syntax: a++

“Such increment operator that increases the value of the operand by 1 after
using its value.”

3.4.5 Decrement Operator:


“Such unary operators that require only one operand and perform an operation
of decreasing the value of the operand by 1 is called decrement operator.”

1. Pre-decrement operator Syntax: --a

“Such decrement operator that decreases the value of the operand by 1 before
using its value.”

2. Post-decrement operator Syntax: a--

“Such decrement operator that decreases the value of the operand by 1 after
using its value.”

P a g e | 35 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

Arithmetic Operator Relational Operator


2. Arithmetic operator is used to 3. Relational operator is used to
perform mathematical calculations compare two values or expressions
on numeric values. to check a condition.
4. The symbols for arithmetic operators 4. The symbols for relational operators
are +, -, *, /, %. are ==, !=, >, <, >=, <=.
5. It returns a numeric result (int, 6. It returns a Boolean value (0 or 1)
float, etc) depending on the
operands.
7. Example: int sum = 5 + 3; 6. Example: cout<< (5 > 3);
performs addition, result is 8. returns 1, because 5 is greater than 3.

Expressions: a = 1 Condition: If a = 1, b = 2, then check a == b?

Assignment Operator ( = ) Equal to operator ( == )


3. Assignment operator is used to 5. Equal to operator is used to compare
assign a value to a variable if the operands are equal.
6. = is used in expressions. 6. == is used in conditions.
7. = returns the assigned value. 8. == returns a Boolean (0 or 1)
9. = modifies the value of the left-hand 7. == only checks for equality of both
operand. operands and does not modify.

P a g e | 36 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3.4.6 Logical Operator:


“Such operators that is used to compare two or more expressions that returns a
result of true or false is called logical operator.”

1. Logical AND operator Syntax: (relation 1) && (relation 2)

“Such logical operator which returns true if all relational expressions are true,
else it returns false, is called AND operator.”

2. Logical OR operator Syntax: (relation 1) || (relation 2)

“Such logical operator which returns true if either one of the relational
expressions is true, else it returns false, is called OR operator.”

P a g e | 37 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3. Logical NOT operator Syntax: ! (relation)

“Such logical operator which returns the inverse of a relational expression is


called NOT operator or inverter.”

3.4.7 Arithmetic Assignment Operator:


“The combination of assignment operator with arithmetic operator
is known as arithmetic assignment operator.”

1. Addition Assignment Operator

“Such operator which adds two operands and assigns the value to left operand.”

a += b OR a=a+b

Example: int x = 5; x += 2 x (new) = x (old) +2

2. Subtraction Assignment Operator

“Such operator which subtracts right operand from the left and then assigns the
value to left operand.”

a -= b OR a=a–b

P a g e | 38 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

3. Multiplication Assignment Operator

“Such operator which multiplies two operands and assigns the value to left
operand.”

a *= b OR a=a*b

4. Division Assignment Operator

“Such operator which divides the left operand by the right operand and then
assigns the value to the left operand.”

a /= b OR a=a/b

3.5 ESCAPE SEQUENCE:


“Such characters that has a special in the output stream of C++.”

\a
“An escape sequence that is used to give beep with the string of output stream
(cout<<"string") is represented by \a.”

#include<iostream>
using namespace std;
int main()
{ int a, b; OUTPUT:
cout<<"\aEnter first value:"; *Gives beep*
cin>>a; Enter first value: _
cout<<"\n\aEnter second value:"; *Gives another beep*
cin>>b;
Enter second value: _
return 0;
}

\n
“An escape sequence that is used to give new line to the string in output stream
(cout<<"string") is represented by \n.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Pakistan\nZindabad"; Pakistan
return 0; Zindabad
}

P a g e | 39 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

\t
“An escape sequence that is used to put a couple of whitespaces that makes
proceeding statements aligned in the string of output stream (cout<<"string")
is represented by \t.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Pakistan\tZindabad"; Pakistan Zindabad
return 0;
}

\r
“An escape sequence that is used to return back to the start of the string in the
output stream (cout<<"string") is represented by \r.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Pakistan\rZindabad"; Zindabad
return 0;
}

\b
“An escape sequence that is used to move the cursor one position back,
effectively deleting the previous character in the string of output stream
(cout<<"string") is represented by \”.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"Hello\b World"; Hell World
return 0;
} *The ‘o’ is removed*

\\
“An escape sequence that is used to insert a backslash character in the string of
output stream (cout<<"string") is represented by \\.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"This is a backslash: \\"; This is a backslash:\
return 0;
}

P a g e | 40 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 3: Input/Output Handling in C++

\”
“An escape sequence that is used to insert a double-quote in the string of output
stream (cout<<"string") is represented by \”.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"He said, \"Hello World!\""; He said, “Hello World!”
return 0;
}

\’
“An escape sequence that is used to insert a single-quote in the string of output
stream (cout<<"string") is represented by \”.”

#include<iostream>
using namespace std;
int main() OUTPUT:
{ cout<<"It\’s a sunny day."; It’s a sunny day.
return 0;
}

P a g e | 41 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

4 CONTROL STRUCTURE IN C++

4.1 PROGRAM STRUCTURE


“A sequence or flow of instructions or codes in a programming language is
called program structure.”

Flowchart Example: A computer program to find average of three numbers.

FLOWCHART
“A graphical representation of step-by-step instructions in a sequence to describe a
computer program using shapes and objects is called flowchart.”

Flowchart consists of five basic graphical objects to describe a computer program.

6. Start/Stop (Oval)
7. Flow Path (Arrows)
8. Input/Output (Parallelogram)
9. Process (Rectangle)
10. Decision/Condition (Diamond)

4.2 CONTROL STRUCTURE


“A program structure which controls the flow of lines of codes or instructions
which is provided by control statements is known as control structure.

Control statements include:

1. Decision Statement
2. Loop Statement
3. Jump Statement

P a g e | 42 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

4.2.1 DECISION STATEMENT


(Also known as Selection statement)

There are three decision-making or selection-making statements in C++ program structure:

1. “if” statement
2. “if-else” statement
3. “switch” statement

“if” statement

“A decision-making statement when “if” is contained in a program structure


following by conditional expression and a block of code, which is only executed
when the condition is true, is known as “if” statement.”

Syntax: if (conditional expression) //Pseudo-code

{
statement(s);
}

“if-else” statement

“A combination of decision-making statements consisting of “if” and “else” in a


program structure followed by conditional expression and block of codes, when
the condition is true, the code block of “if” is executed otherwise the code block
of “else” is executed.”

P a g e | 43 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

Syntax: if (conditional expression) //Pseudo-code

{
statement(s);
}
else
{
statement(s);
}

Nested “if” statement

“Such if statement which occurs inside the block of code of if statement so that
to run two or more conditional expressions.”

Syntax:

if (condition 1) //Pseudo-code

{
if (condition 2)
{
statement(s);
}
}

P a g e | 44 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

Nested “else-if” statement

“Such if-else statement which occurs inside the block of code of else statement
so that to run two or more conditional expressions of if program structure.”

Syntax: if (condition 1) //Pseudo-code


{ statement(s);
}
else
{ if (condition 2)
{ statement(s);
}
}

P a g e | 45 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

“switch” statement

“A decision-making statement which allows control transfer to one labelled


statement in its statement body, depending on the value of expression.”

Label is always a quantity in integer.

Syntax: switch (expression)


{
case constant1: statement 1;
break;
case constant2: statement 2;
break;
default: statement n;
}

P a g e | 46 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

Flowchart of Switch:

Example: Switch program of day number

P a g e | 47 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

Example: Ten-point Grading System

4.2.2 LOOP STATEMENT


(Also known as Iteration statement)

“Such control statement that are executed for a specific number of times until a
certain condition is achieved is called loop or iteration statement.”

ITERATION

“Iteration (Loop) is a repetitive process that is performed again and again until
the condition is met.”

There are three loop statements that are mainly used:

1. “for” loop
2. “while” loop
3. “do-while” loop

P a g e | 48 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

“for” loop

“An iteration or loop statement that allows to write a loop expression that is
executed a specific number of times where it terminates when the condition
becomes false.”

Syntax: for (variable initialization; condition; loop)


{
statement(s);
}

“while” loop

“Such iteration or loop statement which is used to repeat a specific block of


code an unknown number of times, until a condition is met.”

Syntax: while (condition)


{
statement(s);
}

Example: Two Different programs using for and while loop, with same output.

for loop while loop


1) Initialization, condition, and 1) Initialization is done separately
increment/decrement are all written before the loop, whereas the
in a single line in for loop header. condition is checked in the while
loop header.
2) The condition is checked at the 2) Only the condition is in the loop
beginning of each iteration, and all header, and the control of iteration
control elements are in one place. (increment/decrement) needs to be
handled inside the loop.
3) Best suited when the number of 3) Suitable when the number of
iterations is known beforehand. iterations is unknown and depends
on a condition.
4) Designed primarily for counting- 4) More flexible and can handle more
based iterations. complex conditions, like reading from
a file until the end is reached.

P a g e | 49 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

A while loop can handle complex conditions or situations where the number of iterations is
unknown beforehand. For example, reading data until a specific event occurs (e.g., reading a
file until End of File: EOF is reached) is more straightforward with a while loop. A for loop is
generally better for fixed, countable iterations but can be less intuitive for such cases.

Here is an example that shows how the while loop is more flexible when the number of
iterations is not known beforehand.

“do-while” loop

“Such iteration or loop statement which always execute the code block once,
before checking if the condition is true, then it repeats the loop as long as the
condition is true.”

The do-while loop is a variant of the while loop.

Syntax:

do {
// code block to be executed
}
while (condition);

P a g e | 50 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

while loop do-while loop


1) The condition in while loop is 1) The Condition in do-while loop is
checked before executing the loop checked after executing the loop
body. body.
2) If the condition is false initially, the 2) The loop body is executed at least
loop body is never executed. once, even if the condition is false.
3) It is suitable when the programmer 3) It is suitable when the loop body
wants to execute the loop only if the needs to be executed at least once.
condition is true.
4) while(condition) { 4) do {
... ...
} }
while(condition);

4.2.3 JUMP STATEMENT


“Such control statement that are used to manipulate the flow of the program if
some conditions are met is called jump statement.”

It is used to terminate or continue the loop inside a program or stop the execution of a function.
In C++, there are five jump statements:

1. break
2. continue
3. goto
4. return
5. exit()
break statement

“Such jump statement which is used to exit from a loop or switch statement is
known as break statement.”

Syntax: break;

P a g e | 51 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

continue statement

“Such jump statement which is used to skip the current iteration of a loop and
proceed with the next iteration is known as continue statement.”

Syntax: continue;

goto statement

“Such jump statement which is used to transfer control to a labelled statement


within the same function is known as goto statement.”

Label name can be written similar to variable name.

Syntax:

if (condition) {
goto label;
}
label: statement;

P a g e | 52 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

return statement

“The return statement is used to exit from a function and optionally return a
value.”

Syntax:

return value/variable/expression;

exit() statement

“The exit() function terminates the program immediately.”

It requires to include the cstdlib library.

Syntax:

#include <cstdlib>
void exit(int exit_code);

P a g e | 53 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 4: Control Structure in C++

What is the purpose of the default statement in C++?

In C++, the default statement is used in a switch statement to provide a fallback action when
none of the cases match the given value. If the switch expression doesn’t match any of the
specified cases, the default block will be executed.

In this example, if day is not ranging between 1 – 7, the default block will run, and it will print
"Invalid Day Number".

Why do we make a block of statements using braces { }?

In C++, we use curly braces { } to create a block of statements. This is important because it
groups multiple statements together so that they can be treated as a single unit.

Without braces, only the first statement after if, else, while, or other control structures
would be executed.

P a g e | 54 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

5 FUNCTIONS IN C++
“A key part of programming that is a block of reusable and organized code,
usually perform a single, related action.”

There are two types of functions:

1. Pre-defined functions
2. User-defined functions

5.1 PRE-DEFINED FUNCTIONS


“A type of function in a programming language that is already written and has its
own parameters (arguments), and name of the function is defined in the library is
known as pre-defined function.”

Pre-defined functions are also known as built-in functions.

5.1.1 Features of pre-defined functions:


1. A pre-defined function is a function that is already written and provided by the
programming language or its standard libraries.
2. It has a specific name, accepts certain types of parameters (or arguments), and
performs a specific task.
3. The programmer can call this function without needing to define its implementation, as
it is already available in the language's standard library.
4. Libraries include <cmath>, <ctime>, <cstdlib>, and many more.

P a g e | 55 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

5.1.2 Examples of pre-defined functions:


1. sqrt() : Square root of a numerical literal or value of variable
2. pow() : Power of a value or literal
3. abs() : Absolute or modulus of a literal or value of variable
4. sin() : computes the sine of an angle (in radians).
5. exp() : returns the value of e (Euler's number) raised to the power of
a given number, (e ~ 2.71828)
6. strcpy() : Copy the string from source to destination
7. toupper() : Convert lower case to upper case
8. tolower() : Convert upper case to lower case
9. time() : Returns the current time in seconds since the Unix epoch
(January 1, 1970)

P a g e | 56 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

5.2 USER-DEFINED FUNCTIONS


“A function created by the programmer that allows custom functionality by
grouping related code into reusable blocks is known as user-defined function.”

User-defined function is based on three parts:

1. Function declaration
2. Function definition
3. Function calling

5.2.1 Function declaration


“A part of function that declares the function's name, return type, and
parameters before it is used or defined.”

A function declaration, also known as a function prototype, informs the compiler about the
function name, its return type, and the parameters it expects.

This is necessary when the function definition is provided after the function call or when the
function is defined in a different file.

Syntax:

return_type function_name(parameter_list);

Example:

int add(int x, int y);


Here add is the function name of a user-defined function, int x and int y are the parameters,
whereas the int is the return type.

1. Function Name
“A unique identifier similar to variable name, given to the function so it can be
called by this name from other parts of the program.”

2. Return Type
“The data type of the value that the function will return to the caller.”

It can be any valid data type in C++, such as int, double, char, void.

Types of Return Function value:

1. No return value (void)


2. Primitive data type (int/float/char)
3. Pointer type return
4. Class/object return type

P a g e | 57 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

3. Parameters
“The variables with data types that represent the data that a function expects to
receive when it is called.”

Parameters allow you to pass values into a function so that the function can perform its task
using those values.

5.2.2 Function definition


“The actual code or body of the function that performs a specific task.”

It includes the function body, where the logic of the function is written.

Syntax:

return_type function_name(parameters) {
// Body of the function with statements
}
Example:

int add(int a, int b) {


return a + b;
}

Function Declaration Function Definition


1 Function declaration specifies the name of Function definition includes the function’s
function, return type, and parameters actual code block with statements that
without actual code. perform tasks.
2 It ends with a semicolon ; in C/C++ It does not end with a semicolon but
language. contains a full code block within braces { }.
3 It is written at the top of the program It can be written anywhere in the program.
structure.
4 It is used to tell the compiler about a It is used to implement the function’s code
function’s existence before its definition. instruction to perform a task.

5.2.3 Function calling


“The execution of the function by passing the required arguments, and control
shifts to the function’s body to perform the task.”

When a function is called, the control of the program shifts to the function’s body, executes the
code inside it, and then returns control back to where the function was called.

Syntax:

function_name(arguments);

P a g e | 58 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

Arguments
“Arguments are the actual values or expressions passed to the function when it
is called.”

Parameters are transformed into arguments in function call.

Types of Arguments:

1. No argument in function (void).


2. With argument in function (int/float/char)
3. Default argument

Function Declaration Function Definition


1 Function declaration specifies the name of Function definition includes the function’s
function, return type, and parameters actual code block with statements that
without actual code. perform tasks.
2 It ends with a semicolon ; in C/C++ It does not end with a semicolon but
language. contains a full code block within braces { }.
3 It is written at the top of the program It can be written anywhere in the program.
structure.
4 It is used to tell the compiler about a It is used to implement the function’s code
function’s existence before its definition. instruction to perform a task.

5.2.4 Examples of user-defined functions:

P a g e | 59 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

5.3 LOCAL AND GLOBAL VARIABLE


5.3.1 Local Variable
“Such variables that are declared inside a function are called local variable.”

A local variable cannot be reused in a function even when it is used in the main function.

Syntax:

return_type function_name(parameters)
{
// Local variable:
data_type variable_name = value;
// other code instructions
}

5.3.2 Global Variable


“Such variables that are declared outside a function that can be reused in any
function are called global variable.”

Global variable is also known as external variable. It holds the value of variable during the entire
execution of a program.

P a g e | 60 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

Syntax:

// Global variable:
data_type variable_name = value;

return_type function_name(parameters)
{
// other code instructions
}

External Variable Internal Variable


1 External or global variables are declared Internal or local variables are declared
outside a function so that they can be inside the code block of any function.
reused.
2 Memory is allocated when the program Memory is allocated when the function is
starts and releases it ends. called and released afterwards.
3 It is accessible throughout the entire It is accessible only within the function or
program, including inside functions. block where it is declared.
4 // Syntax of Global variable: return_type function_name(parameters)
data_type variable_name = value; {
return_type function_name(parameters) // Local variable:
{ data_type variable_name = value;
// other code instructions // other code instructions
} }

P a g e | 61 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

5.4 HEADER FILES IN C++


“A file with a .h extension that typically contains declarations of functions,
classes, and other elements, which can be shared across multiple file
management or devices.”

Applications of HeadeMemr Files:


1. Header files allow programmers to separate the function definition from declarations
and keep the code organized and reusable.
2. It allows multiple files to use the same declarations without redefining them.
3. It reduces the compilation time by only including what is necessary.

When we compile the code, the header file allows the main function to know about what is inside
the function declared in header file. The main function is the actual code in .cpp extension.

Example in Predefined Functions:


<iostream> is a header file in C++ where the standard library is accessed to provide input
(cin>>) and output (cout<<) operations.

When using header file of any predefined function, <iostream> is written with #include.

#include<iostream>

More examples: <cmath>, <cstdio>, <conio.h>

Example in User-defined Functions:


1. A user defined function for adding two floating point numbers can be created from a
header file add.h but a source file add.cpp is also needed for the function to be defined.

2. Only the function declaration is provided in header file and the function definition is
provided in the source file.

3. When the programmer compiles these files, the add.h header file allows main.cpp to
know about the add function.

4. #ifndef/#define/#endif are include guards to prevent multiple inclusions.

P a g e | 62 Shehzaib Yousuf Khan ©


Class X: Computer Chapter 5: Functions in C++

P a g e | 63 Shehzaib Yousuf Khan ©

You might also like