0% found this document useful (0 votes)
9 views117 pages

Programming Techniques and Problem Solving

Uploaded by

mehtab shah
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)
9 views117 pages

Programming Techniques and Problem Solving

Uploaded by

mehtab shah
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

PAGE#.

Chapter #. 01 PROGRAMMING TECHNIQUES


Problem:
Def#01: Anything which needs solution is called problem.
Def#02: A problem is an obstacle, difficulty or challenge or any situation that require
solution.
Explanation: A problem might be just the feeling that something is wrong and should be
corrected. There are two types of problem one is simple and the other is complex. A simple
problem may be to doing the average of any 10 numbers or to multiply any two numbers.
The complex problem is that problem which is difficult to solve as to develop software for a
forum. Each problem requires skills for the solution of that problem.
Problem Analysis:
Definition: The process of understanding the problems and proposing solutions to those
problems.
Explanation: It is divided into two sub steps: Analyzing the problem and Requirement
analysis:
Analyzing the Problem: Once a problem has been defined it must be properly analyze. By
this we mean that the analysis is done in such a way that a problem is divided in to various
parts called sub problem as the solution of sub problem make it easy to solve a complex
problem. It is very necessary that the solution of sub problems are arranged in such a way
that leads to whole problem solution.
Requirement analysis: In this step all the information about a problem solution is collected
also the entire requirements like computer, internet, etc which are necessary for the
development of a system is identified.
To Analyze (study/examine) the causes:
You need a clear idea of the problem so that it can be analyzed. Revisit the problem
description to make sure you clear about:
What is the problem about?
How frequently does it occur?
When and where does it occur?
Who is affected?
How the solution of Problem is planned. Q.#02(ii) at exercise
Ans: PLANE THE SOLUTION:
Finding the solution does not mean the problem is solved. Now, you need to design a plan of
action so that the solution gets carried out properly. The best solution can fail because it is
not implemented correctly. A problem can only be solved if the operations for its solution are

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.2

carried out in a correct order. Design a plan of action chart including all the details you need
to consider to carry it out and when each phase should happen. After analysis the solution is
planned. There can be various solutions but the proposed solution should be cost-effective,
time efficient, speedy and less complex.

Question: Define and explain the problem solving techniques. Q#.02 at exercise
The following are the some useful techniques:
Abstraction: Solving the problem in a model of the system before applying it to real system.
Explanation: Create a model before the solution of a problem. For example if we want to
construct a building first of all we will develop a model and draw a map for it. Then we will
construct that building accordingly.
Analogy: Using a solution that solved an analogies (similar) problem.
Explanation: Some time more than one problem has same nature of solution so in solving
problems we must solve our problems in such a way that solve same problems
Brainstorming (suggesting): (especially among groups of people) suggesting a large
number of solutions and ideas combining and developing then until best solution is found.
Explanation: A problem may have more than one solution so combine all the suggested
solution and then find the best solution in them.
Divide and conquer (get solution): Breaking down a large, complex problem into smaller
solvable problem.
Explanation: Commonly a complex problem is solved by “Divide and Rule” method. So a
large or complex problem is solved by breaking it in to sub problems. As the solution of sub
problems is easy. Then solution of problems must be in such a way that leads to the solution
of the whole problem.
Reduction: Transforming the problem into another problem for which solution is exist.
Explanation: In this sense the problem represents the class, since any solution to it can, in
combination with the reductions, be used to solve every problem in the class.
Research: using existing ideas or adopting existing solutions to similar problems.
Explanation: when same problem come repeatedly then adopt the exist solution for it.
Trial and error: Testing possible solutions until the right one is found.
Explanation: A problem may have a number of solutions so test each solution and find the
best one. In this technique each suggested solutions are solved practically then the best
solution is selected.
Q. What is meant by Candid solution of a problem?
Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.3

Ans: Definition: Finding the best and suitable solution of any problem is known as candid
solution.
Explanation:
Solution is the act or process of solving a problem as to obtain the desired and best result
with minimum cost. There may be several solutions for solving the problem. However
finding “the best” and “the most suited” solution is the candid solution of the problem.
Question: Describe the factors which are needed for the selecting of best solution.
Ans: there are some factors which are very important in selecting the best solution of any
problem given as below:
1. Speed: Speed is an important factor in selecting the best and suitable solution of a
problem. The best solution toward a problem is one which takes minimum time to
solve.
2. Cost: Cost is another factor for selecting the best solution of any problem. Cost of
solution includes space and other hardware, software requirements. The solution will
be considered to be the best if it gives optimal desired result with minimum cost.
3. Complexity: complexity means the resources required to the solution, most
commonly known as the time require which a problem take to solve, also the steps as
in how many steps a problem will solve and the space which is needed for the solution
of a problem as how much memory it will take.
Q#.03 at exercise
Define an algorithm explain the role of algorithm in problem solving.
Algorithm:
Def.#01: It is well defined list of steps for solving a particular problem
Def.#02: A step by step solution toward a problem.
Def#.03 It is a number of steps in which a problem is solved.
Explanation: An algorithm is number of steps in which a problem is to be solved. A
problem can only be solved if the operations for its solution are carried out in a correct order.
So the order of steps must be well defined. An algorithm is sequence of computational steps
that takes some values as input and produces some values or set of values as output. We can
say that algorithm as a tool for solving well-specified computational problems.
Role of algorithm in problem solving:
Algorithm plays an important role in developing solution to a problem, for example if we
have a complex situation which requires a lot of information to be gathered and a lot of data
to be processed. Then by dividing each activity of this information gathering and data

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.4

processing into steps then it will make the problem solving an easy task. As the “Divide and
Rule “method make the problem solving is an easy task.
Example: If we want to find the average of 20 numbers, if this process is defined in small
discrete steps then it make the solution very easy.
Step-1 Select any 20 numbers
Step-2 add all the numbers
Step-3 Divide the result of step-2 by total no of observations i.e 20
Step-4 the average will be calculated.

Criteria for measuring efficiency of an algorithm

To determine which algorithm is "best". There are generally two factors used to determine
whether one algorithm is "better" than another.

 Space requirements (i.e. how much memory is needed to complete the task).
 Time requirements (i.e. how much time will it take to complete the task).

Furthermore its efficiency is measured on the basis of following factors:


a. Input needed: The amount of time an algorithm takes depends on how large is the input
on which the algorithm operates. For example: To multiply 100 values with each other than
to multiply only ten number or values with each other. It means that for the multiplication of
100 values as 100 values are required to be enter and for the multiplication of five values
only five values are to be enter.
b. Processing to be completed: The efficiency of the algorithm depends upon the processing
time in which an operation is completed. As each activity/task take a slot of time to be
completed.
c. Decision to be taken: Decision taking is the important factor of algorithms which
improve the efficiency of an algorithm and get the desired result.
[Link] to be provided: an algorithm is said to be correct if it give the correct output for
every input instance.
The algorithm will be considered as best when it provides the desired result.
EXAMPLES OF ALGORITHM:
Problem #01: To find the sum , product and average of the five given numbers.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.5

Algorithm: Given five number n1,n2,n3,n4 and n5. This algorithm finds the sum SUM,
product PRO and average AVG of these numbers
Step#01 Read n1,n2,n3,n4,n5
Step#.02 Set Sum= n1+n2+n3+n4+n5
Step#.03 Set PRO= n1*n2*n3*n4*n5
Step#.04 Set AVG=SUM/5
Step#.05 write SUM, PRO, AVG
Step#.06 Exit
Problem#.02 To display largest one out of the three given unequal numbers.
Algorithm: Given three unequal numbers n1,n2 and n3. This algorithm finds the largest
LARG number out of three numbers.
Step#.01 Read n1,n2,n3
Step#.02 IF n1>n2 AND n1>n3 then set LARG=n1 Else if n2>n3 then set LARG=n2
ELSE set Large=n3
Step#.03 Write LARG
Step#.04 Exit
Problem#03
To find acceleration of a moving object with given mass and the force applied.
Step#.01 Read Mass,Force
Step#.02 Set Acc=Force/Mass
Step#.03 Write acc
Step#.04 Exit
Problem #05: To find the area of a triangle
Step#.01 READ B,H
Step#.02 Set Area=B*H/2
Step#.03 Write Area
Step#.04 Exit
Problem#06 To find the area of a parallelogram
Algorithm :this algorithm find the area of a parallelogram AP having base B and height H.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.6

Step#.01 Read B,H


Step#.02 Set P=B*H
Step#.03 Write AP
Step#.04 Exit
Problem#07. To find the area of a rhombus or trapezium.
Algorithm: this algorithm finds the area ATRAP of aTrapezium having A and B are the
lengths of the parallel sides, and H is the height (the perpendicular distance of the sideds).
Step#.01 READ A,B,H
Step#.02 Set ATRAP=A+B/2*H
Step#.03 Write ATRAP
Step#.04 Exit
Problem#.08 To assign grade to a subject based on the achieved marks.
Algorithm: This algorithm assigns grade GRADE to a subject based on the achieved marks
SUMARKS
Step#.01 READ SUBMARKS
Step#.02 IF SUBMARKS>=80 set Grade=A+
Else If SUBMARKS>=70 set Grade=A
Else IF SUBMARKS>=60 set Grade=B
Else IF SUBMARKS>=50 set Grade=C
Else IF SUBMARKS>=40 set Grade=D
Else IF SUBMARKS>=33 set Grade=E
Else Set Grade=Fail
(End of If statement)
Step#.03 Write GRADE
Step#.04 Exit
Problem#09: To find the interest on an amount
Algorithm: this algorithm finds the amount of interest I where Principal amount is P the rate
is R and the time is T.
Step#.01 READ P, R,T

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.7

Step#.02 Set I=P*R*T


Step#.03 Write I
Step#.04 Exit
Problem#.10 To calculate the exponent of given number .
Algorithm: this algorithm calculate exponent EXP of a given number NUM having exponent
X.
Step#.01 READ NUM,X
Step#.02 Set EXP=NUM^X
Step#.03 EXP
Step#.04 Exit
Problem#11. To find a sequence of odd numbers starting from a given number.
Algorithm: this algorithm finds a sequence SEQ of odd numbers starting from a given
number NUM upto N, where NUM must be an odd number.
Step#.01 READ NUM, N
Step#.02 Repeat Step 3 and 4 while NUM<=N
Step#.03 Write NUM
Step#.04 Set NUM=NUM+2
End of while loop
Step#.05 Exit
Problem#.12 To create MUL of a given lying between two numbers
Algorithm: this algorithm counts multiples M of a given numbers NUM lying between two
numbers N1 and N2 where N1 is greater than N2
Step#.01 READ NUM,N1,N2
Step#.02 Set M=0(initialize M)
Step#.03 For A=N1 to N2
Step#.04 Set MUL=NUM*A
Step#.05 IF MUL<=N2 then M=M+1 repeat Step 6 else goto step 7
Step#.06 Next A
Step#.07 Write M

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.8

Step#.08 Exit
Problem#.13 To produce a multiplication table TAB for a given number.
Algorithm. This algorithm produce a multiplication table TAB for a given number NUM.
Step#.01 Set C=1 (initialize counter)
Step.02 READ NUM
STEP.03 Repeat Step 4, 5 and 6 while C<=10
Step#.04 Set TAB=NUM*C
Step#.05 Write NUM’*’C’=’TAB
Step#.06 C=C+1
End of while loop
Step#.07 Exit
Problem#.14 To convert Celsius to Fahrenheit temperature
Algorithm: This algorithm converts Celsius C to Fahrenheit F temperature.
Step#.01 READ C
Step#.02 Set F=32+C*9/5
Step#.03 Write F
Step#.04 Exit
Problem#15 To convert Fahrenheit to Celsius Temperature
Algorithm: this algorithm converts Fahrenheit F to Celsius C temperature
Step#.01 READ F
Step#.02 Set C=(F-32)*5/9
Step#.03 Write C
Step#.04 Exit
Problem#.16 Find even number in integers ranging from n1 to n2 . (where n1 is less than n2
and n1 is an even number)
Step#.01 READ N1 N2
Step#.02 Set EVEN=n1
Step#.03 Repeat Step 4 and 5 while EVEN<=n2

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.9

Step#.04 Write EVEN


Step#.05 Set EVEN=EVEN+2
End of while loop
Step#.06 Exit
Problem#.17 Add members of two lists
Algorithm: This algorithm adds members of two list L1[n], L2[n] in list L3[n]
Step#.01 READ L1[n] , L2[n]
Step#.02 Set I=1[Initialize counter]
Step#.03 Repeat step 4and 5 while I<=n
Step#.04 Set L3[i]=L1[i]+L2[i]
Step#.05 Set I=I+1
End of while loop
Step#.06 Exit
Problem# 18 Calculate the GCD of given numbers
Algorithm: this algorithm calculates GCD of given two numbers m and n
Step#.01 READ m,n
Step#.02 If n=0, GOTO step 5 otherwise proceed step 3
Step#.03 Divide m by n and assign the value of the remainder to r
Step#.04 Assign the value of n to m and the value of r to n and goto step 2
Step#.05 write m
Step#.06 Exit
Problem#. 19 Determine whether a given number is prime number or not
Step#.01 READ NUM
Step#.02 Set i=2
Step#.03 Repeat step 4 and 5 while i<=Num-1
Step#.04 IF NUM%i=0 then write “not a prime number’ go to step 7
Step#.05 Set i=i+1

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.10

End of while loop


Step#.06 IF i=NUM, then write “Prime number”
Step#.07 Exit
Problem# 20 Determine prime number in integer ranging from n1 to n2 (Where n1 is greater
than n2)
Algorithm: this Algorithm determine prime numbers between n1 and n2 where n1>n2
Step#.01 READ n1,n2
Step#.02 Set n=n2+1
Step#.03 Repeat step 4 while n<n1
Step#.04 Repeat Step 5 for i=2 to n-1
Step#.05 IF n%i=0 then set n=n+1 Goto Step 3
Else
(a) Write n
(b) Set n=n+1
Step#.06 Exit

What is flowchart? Explain flowchart symbols in detail? Q#.05 at exercise


Ans: Flowchart:
Def#01: Flow chart is a pictorial form of an algorithm.
Def#.02 Flowchart is graphical/symbolic/diagrammatically representation of an algorithm.
Explanation: Flow chart has some standardized symbols which are used when a solution of
a problem is to be designed .Flow chart is a type of diagram representing a process using
different symbols containing information about each steps or a sequence of events /activity
in a problem. Each of these symbols linked with arrows which represent the flow direction of
the problem solution.
Flow chart symbols: Flowchart use special shaped to represent different types of actions or
steps in an algorithm. These are called flow chart symbols. The following are some
important flowchart symbols.
1. Oval: Represent a start and an End of a flowchart . it is also known as starting and
ending point.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.11

2. Arrow lines/flowlines: It is used to show flow of direction or flow of control from


one step to another.

3. Process Box:
A rectangle is used for representing a process. It shows the process or calculation in
the program flow chart.

4. Decision Box:

It is represented by a diamond shaped symbols in which decision is made on a certain condition. If


condition is Yes/ True then an active is to be done. If condition is N/false, then another condition is
performed.

5. Input /output box.


Input / output operations in the flow chart is represented be parallelogram.

6. Annotation symbol:
This symbol is used to represent remarks given by the programmer to a particular
part/ Component of the flow chart.

………………..

7. On page connector:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.12

This symbol is used to connect a part of the flow chart to another when flow chart is
divided the in to many parts at same page. Circle is used to represent on page
connector.

8. Off page connector:


Sometime flowchart is enough large which can’t adjust at one page. So off page
connector is used to connect flow charts which are lying at move then one page.

Q: What is the importance of flow chart?


Ans: Importance of Flowchart: flow chart is the methodology used to analyze ,improve and
manage a process or program. Flow chart use a standard symbols when the solution of a
problem is to be designed as when the solution of a problem is designed then the solution of
that problem become very easy. From the flow chart the programmer write the program.
Following are the key importance of the flow chart.
1. It helps the viewer to understand a process
2. Showing the required input and output
3. Understanding of relationship among different process steps.
4. Helping with decision making
5. Tracking the process flow
6. Highlights importance steps and eliminating the unnecessary steps.

Q: What are the Flow chart requirements when the solution of a problem is to be designed,

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.13

ANS: Flowchart requirements: When a flowchart of a problem solution is designed then


the following are the requirements which are needed.
1. Input needed: input is anything which is required for the processing. The flowchart
developer must know what exactly the input is. The input is determined from the
problem statements.
2. Processing to be completed: in Flow chart the process is , to resolves any formula or
expression or initialize any value in a variable. The flowchart developer must specify
that which formula or logic is to be used as to get the required result.
3. Decision to be taken: In flowchart the decision is either taking action when the
expression is true or false. For example, finding the result of a student, decision is
required to be taken on marks as IF marks>=40 then “pass” otherwise Result=”fail”.
4. Output design: Output is the result. The flowchart must give the result in the end.
Note: STUDY ALL THE FLOWCHART EXAMPLES FROM BOOK

EXERCISE
Q#.01Select the most appropriate choice;
i. An obstacle, difficulty or challenge or any other situation that require resolution is
called_____________.
a. Algorithm b. Problem c. Complexity d. None of the above
ii.___________ is used to describe properties of an algorithm relating to how much
various types of resources in consumes.
a. Efficiency of an algorithm b. Candid solution
c. Complexity of an algorithm d. None of the above
iii. ____________is a well defined list of steps for solving a particular problem.
a. Algorithm b. Flowchart c. Complexity of an algorithm d. All of the above
iv. An algorithm is a sequence of computational steps that transform the input into
_____________.
a. Data structure b. algorithm c. Output d. all of the above
v. Which symbol is used to represent a process?
a. b. c. d.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.14

Q#.02 Give short answer to the following questions. For ANS See page#
i. Define Problem analysis
ii. How the solution of the problem is planned.
iii. Define Candid solution of a problem.
iv. Define any three problem solving techniques
v. List various factors for selecting the best solution of any problem.
Ans: The following factors are used for selecting the best solution of any problem.
 speed
 cost
 complexity
Q#.03 Define an algorithm and explain the role of algorithm in problem solving
process.
See at page#
Q#.04 Describe the criteria for measuring efficiency of an algorithm of on the basis of:
a. Input needed
b. Processing to be completed
c. Decision to be taken
d. Outputs to be provided
For ANS See page#
Q#.05 what is flowchart? Explain flowchart symbols in detail.
For ANS See page#
Q#.06 Write an algorithm to calculate the factorial of given number and draw
flowchart for it.
Ans:
Algorithm:
Step#.01 Read NUM
Step#.02 Set Fac=1 and c=1
Step#.03 Set Fac=Fac*k

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.15

Set K=K+1
Step#.04 Repeat step#.03 if K<=N otherwise proceed to step#.05
Step#.05 Display Fac
Step#.06 Exit
Note: for flowchart see Problem#. 12 at page#30 in book.
Q#.07 Write an algorithm and draw a flowchart to resolve quadratic equation.
Algorithm:
Step#.01 Read a,b,c
Step#.02 Set X= -b+(b*b-4ac)^1/2
Step#.03 Set Y=2*a

Step#.04 Set E=X/Y


Step#.05 Display E
Step#.06 Exit

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.16

Chapter#.02 PROGRAMMING IN C

Q: what is meant by Programming?


Ans: Programming:
Def: The Process of writing program in known as Programming.
Explanation: when a user want to write a program then he will need an environment as
computer Programming language in which a program is to be write. Generally a program is
written to solve a specific problem.
Q: Define Compute Program.
Ans: Computer Program:
Def: A Set of instructions which is written and executed to perform a specific task.
Explanation: Computer program is a list of statements which tells the computer what to do.
The person who writes a program is called programmer. Programmer uses Programming
language /tools to write program.
Q: Differentiate between Program semantic and program syntax?
Ans:
Program Semantic (1) Program semantic describes meanings to statement of a
Programming language.
Program Syntax: (1) Program syntax refers to the rule of a Programming language
according to which statements of program are to be written.
Program Semantic: (2) it describes the sequence of questions to be performed by computer
when executing the statement of computer program.
Program Syntax (2): It describes the way in which computer program are to be written.
Program Semantic (3): Semantics deal with the meaning assigned to the symbols, characters
and words.
Program Syntax (3): syntax is concerned with structure of the code that a specific
programming language requires.
Q: What is Programming language? Explain different types of low level language:
ANS: Programming Language:
Definition: A set of word, symbols and codes used to write a program is called programming
language.
Explanation:
Need of Programming language: When a user want to write a program then he/she will
need a Programming language installed in his/her computer system, as a program is written
Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.17

in a specific Programming language as C, C++,JAVA , ORACLE etc. Commonly a program


is written to solve a specific problem.
Availability of Programming language: Different types of language are available in market
for writing different types of programs. Majority of High level language are general purpose
languages. By general purpose we mean that we get output according to the program or
instructions written or we can say that the general purpose language are applicable in any
field like education, health, research and engineering etc.
Types of Programing language: Programming language is divided in to two main types.
i. Low level language
ii. High level language
Types of Low level language there are two types of low level language. (i) Machine
language and (ii) Assembly language
(i)Machine language:
Def: It is a programing language in which program or instructions are written in binary as
in combination of 0s and 1s.
Explanation: Writing program in machine language required deep knowledge, as it is a
fundamental language of computer. It is only language that is directly understood by the
computer. Machine language is difficult to understand for human. It is hardware oriented
language. Machine language is also known as 1st generation language.
(ii) Assembly Language:
Def: In this language symbols are used instead of binary codes.
Explanation: Assembly language uses symbols which are called mnemonics. The
programmer uses these symbols when he/she write a program in assembly language.
Assembly language is mostly used for writing system program. It is also known symbolic
instruction code. it is 2nd generation language.
Example:

Q#.02(ii) at exercise

Q. Differentiate between Low-Level & High-Level Language


High-level Language
1. Learning
High-level languages are easy to [Link] it use commonly using English words like if,
then ,goto ,for etc
2 Understanding
High level languages are near to human languages.
3. Execution
Programs in high-level languages are slow in execution.
4. Modification
Programs in high-level languages are easy to modify.
5. Facility at hardware level
High-level languages do not provide much facility at hardware level.
6. Knowledge of hardware Deep
Knowledge of hardware is not required to write programs.
7. Uses

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.18

These languages are normally used to write application programs.

Low-level languages
[Link]
Low-level languages are difficult to learn because its instruction contain binary code or
symbols.
[Link]
Low-level languages are far from human languages.
[Link]
Programs in low-level languages are fast in execution.
[Link]
Programs in low-level languages are difficult to modify.
[Link] at hardware level
Low-level languages provides facility to write programs at hardware level.
[Link] of hardware Deep
Deep knowledge of hardware is required to write programs.
[Link]
These languages are normally used to write hardware programs.

Q. What is high level language, Explain any five types of high level language. Q#.04 at
exercise
Ans: High Level Language:
General purpose language: Mostly High level languages are the general purpose languages.
It means that these languages are applicable in every field like education, health, research,
engineering etc.
English oriented language: High level languages are English oriented languages. Its
instruction contain commonly used English words like IF, FOR, WHILE, TO etc.
Easy to learn: As its instruction contains the English words so it is suitable for the person
who wants to learn programing.
Need Translator: High level language instruction is translated into machine language by
translating software. Today compilers are used as translator for programing language.
Examples of high level language: C,C++,JAVA, Visual Basic, Oracle etc:
(I). C Programing language:
Development: C is a programming language developed at AT & T’s Bell Laboratories of
USA in 1972. It was designed and written by a man named Dennis [Link].
Procedure Language: C is a procedure programing language with many low level features
including the ability to handle memory address and bits.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.19

General purpose language: C is a general purpose language, as it is applicable in any field


of life as in engineering, science, health, education and research etc.
Easy to Learn: C is easy to learn for the person who wants to learn programing language
from the start. Its instructions contain English words like THEN, ELSE, FOR, TO etc.
Example: Unix operating system was written in C programing language.
(II) C++ programing language:
Development: In the early 1080s at Bell laboratories of USA another programming language
was developed by Bjarne Stroustrup.
Purpose of developing C++: Stroustrup states that the purpose of C++ developing is to
make writing programs easier.
OOP object oriented programming language: C++ is an object oriented programming
language as it has the features for working with objects, classes and other object oriented
concepts.
General purpose language: C is a general purpose language, as it is applicable in any field
of life as in engineering, science, health, education and research etc.
Easy to Learn: C is easy to learn for the person who wants to learn programing language
from the start. Its instructions contain English words like THEN, ELSE, FOR, TO etc.
Example: Word processor and spread sheet programs are written and developed in C++
programming language.
III. C#:
Development: It was developed in 2000 by Microsoft corporation.
Object oriented programming language: C# is an object oriented programming language. It is
based in c++ with elements of visual Basic and Java.
General Programming Language: C# is an general programming language . it can be used
in any field of life. It generates result according to the instructions given.
Program Development: All types of programs including games, utilities programs,
operating system, business application and we based application can be developed in C#.
[Link]:
Development: It was developed by sun microsystem in1991.
Object oriented programming language: Java is an object oriented programming
language. It is similar to C++.
[Link](Hypertext Preprocessor): programing language:
Development: PHP It was developed by Ramus Leadoff in1994.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.20

Scripting language: PHP is an HTML embedded scripting language. The goal of the
language is to allow web developer to write dynamically generated web pages.
General purpose programming language: It is general purpose programming language.
But is generally used to create web pages.

Difference between Compiler and Interpreter

No Compiler Interpreter

Compiler Takes Entire program as


1 Interpreter Takes Single instruction as input.
input

Intermediate Object Code


2 No Intermediate Object Code is Generated
is Generated

Conditional Control Statements are Conditional Control Statements are Executes


3
Executes faster lower

Memory
4 Requirement :More (Since Object Memory Requirement is Less
Code is Generated)

Program need not be Every time higher level program is converted


5
compiled every time into lower level program

Errors are displayed after entire Errors are displayed for every instruction
6
program is checked interpreted (if any)

7 Example : C Compiler Example : BASIC

Question#.05 at exercise
Question: Explain different parts/modules of C language IDE?
Ans: Module of C Programming language: The following are the module of C
programming language:
1. Editor: It is a program which enables users to create and edit program in C language. The
written program is known as source code and having extension “.c”. Editor is also known as
text editor. Most of the editors automatically highlight compilation error.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.21

2. Compiler: It is an translating software or program which translate source code into


machine code. When a programmer writes a program in a high level language then he/she
compiles that program in order to get result. So compiler translates that program into
machine code to process by compiler. A compiled program is known as object program and
it have the extension as “.obj”.
3. Linker: It is a program which takes one or more object code generated by a compiler and
combines then into single executable program. The extension of that executable program is
“.exe”.
4. Loader: it is a program that loads C-language programs into memory and then executes
them.
5. Debugger: Debugger is a program which helps in finding and removing of error. As
Debugging is a process in which the errors are found and removed. Debugging is a
combination of two words De which means remove and bug means error.
Question#.02(vii)
Question: What is header file?
And: Header File:
Definition: Header file are collection of standard library functions to perform different tasks.
Explanation:
Containing predefined functions: Each header file contains different types of predefined
functions. More than one header file may be including in one program. The header file must
be included in the program before calling or using its functions in the program.
Extension of header file: The extension of header file is “.h” the #include keyword are used
to include header file in programs. The header file are commonly stored in INCLUDE
subdirectory.
Example of header file:
#include”stdio.h” OR #Include<Stdio.h>
The word stdio stands for standard input/output. The header file contains the definitions of
built in input and output functions.
Question#.02(x) at exercise
Q: Write rules for variable name?
Ans. when a user declares a variable in C environment then he/she must keep in view the
following rules.
(1) The variable name must always begin with alphabet or letter, as A2, Names ,marks
(2) The length of a variable name depends upon the compiler of C.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.22

(3) Blank space is not allowed in the variable name,


(4) A variable name should not be a keyword.
(5) Variable name should not contain any special character like #,*, ^ etc.
(6) A variable name declared for one data type cannot be used for another data type.
Q#.02(viii) at exercise
Q: Differentiate between source program and object program?
ANS:
S/No Source Program Object Program
1 The program before translation is known as The Program after compilation or
source program translation is known as object program

2 Source program is written in higher level Object programs usually contain lower
languages such as Java or C level languages such as Assembly
language or machine code.

3 Source programs are easily readable by Object programs are difficult to read by
humans. humans.
Question#02(ix) at exercise
Q: what is reserved word?
Ans: Reserved word/Keyword:
Def#.01: The word that has specific meaning to the compiler is known as reserved word
DeF#.02: The words that are used by a pogromming language for special purpose are called
reserved word.
Explanation: the reserved words are that words which are used in a computer programming
language for a specific purpose as these word are reserved for that special purpose. Each
keyword has fixed meaning and that cannot be change by the user. The reserved words
cannot be used as variable names in a program.
Example: int, If, Else, While, etc are reserved words in C,C++.
Question#.06 at exercise
Q: What is the basic structure of C Program? Explain different types of preprocessor
directives?

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.23

Ans. Basic structure of C program: A C language program consist of three basic main
parts which are given as below:
 Preprocessor Directives
 The main () function
 Body of main{}
Preprocessor Directives: the instructions that are given to the compiler before the beginning
of the actual program are called preprocessor directives. These are also known as compiler
directives. The complier adds special code from these directives into the program at the time
of compilation. These preprocessor directives normally starts with the hash sign # and the
keyword like #include or # define . e.g #include<conio.h>
Main () function: when a c program is executed the control goes to Main() function as main
() function contain the statement of the c program which is known as the body of C program.
All the statements are written in the body of the C program are enclosed in braces {}. The
program cannot be compiled without main() function by the complier.
Syntax: Main()
{
Body of the program
}
Body of main: the statement of the program written inside the main () function in between
the braces {}. These statements are the body of the program. Each statements in C program
ends with semicolon;. C is case sensitive language. The statements are normally written I
lowercase letters.
Types of Preprocessor directives:
The commonly used preprocessor directives are given as below:
(i).<stdio.h>
Question#.07 at exercise
Q: What are the constant and variable, Differentiate them with examples.
Ans. Constant: constant is a quantity which cannot be changed during program execution.
Variable: A quantity which value change during program execution is known as variable.
Difference between Constant and variable
S/no Variable Constant
1 Variables are quantities with changing Constants are quantities with
magnitude, hence can assume different unchanging values, and used to

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.24

values based on the application represent numbers with significance.


2 the variables are used to represent Constants are used to represent
unknowns quantities. quantities in nature which are fixed,
3 Examples: marks , names Example: 00,Zeeshan,Pakistan
Question#. 08 at exercise
Q: Explain different data types used in c-language with examples?
Ans: Data type represents the type of data which are used in a program as either it is numeric
or character type. All C compilers accept the following fundamental data types to be
assigned to variable.
 Integer (int)
 Floating point ()
 Character char()
(i)Integer(short, int, long) type: integer are whole number with machine dependent range of
values. C has three classes of integer storage namely short, int and long. All of these data
type have signed and unsigned. Short and int have the same size.

An integer variable decoration statement has the form:

Int variable;

Example: Int marks


(ii)Floating point (float, double, long double): It represent real number with 7 digits of
precision. Floating point numbers are denoted by the keyword float. We can use the double
and long double to define the number. Float variable declaration has the form:
Float variable;

Variable Declaration No. of bytes Range


Float 4 3.4*10-38 to 3.4*1038
Double 8 1.7*10-308 to 1.7*10308
Long double 10 3.4*10-4932 to 1.1*104932

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.25

(III) character (char) type: a character variable can only store one character. An example of
declaration of character variable is
Char ch;
The C compiler sets aside one byte if memory for storing a character in a character variable.
Question #.10 at exercise
Q:What is type casting? Explain with examples.
Ans: Type Casting: Def: the process of converting one data type into another data type
during program execution is called type casting.
Types: type casting is performed in two ways,
(i)Implicit type casting
(II)Explicit type casting
(i)Implicit type casting: implicit type casting is performed automatically by the C compiler
itself.
Example: suppose x is an integer and y is a long variable and following expression is
evaluated
X+Y
In the above expression data type of x is lower than data type of Y, so the value of X will be
converted into long during the evaluation of expression.
(ii)Explicit type casting: Explicit type casting is performed by programmer himself, it cannot
be done by the complier automatically. The Cast operator is used to perform explicit type
casting, as this operator till the compiler to convert the data type of a given value.
Example: Suppose X and y are two float variables. X contain 10.3 and y contains 5.2 and the
following expression is evaluated.
X%Y
The above expression will generate an error because data type of x and y is float. The
modulus operator cannot work with float variable. It only works with integer, so the
expression can be written as below:
(int)X%(int)Y
The above statement converts the value of x and Y into integers and evaluate the expression.
The value of x will be converted to 10 and value of y will be [Link] the result of the
above expression will be 0.
What is oop: (Question#02(iv) at exercise )

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.26

Object-oriented programming (OOP) refers to a type of computer programming (software


design) in which programmers define not only the data type of a data structure, but also the
types of operations (functions) that can be applied to the data structure.
Question#02(xi) at exercise
Question: what is the purpose of const qualifier?
Ans: Const Qualifier: The const qualifier is used to define a constant, the constant is
declared by specifying its name and data type. The constant must be initializing with some
value. The initialize value can be change during program execution.
Syntax
Const data type identifier=value
Where const is a keyword and data type indicate the data of the constant . identifier represent
the constant name where value with which the constant is initialized.
Example: cons tint X=10, float Z=2.5
The above assigned value cannot be changed during program execution.
Question#.10 at exercise
Q:How variable are declared and initialize in C language? Give example.
And: Declaration of variable:
Definition: Assigning name and data type that a variable can hold is called declaration of
variable.
Explanation: A variable in a program can be declared by writing its name with data type.
All variable that are used in a program are declared using variable declaration statements.
Syntax:
Data type list of variables
Where Data type specifies data type of variable i.e int, float etc
List of variables specifies a list of variable separated by commas.
Example: int marks, roll number
Float percent,
Initialization of variable:
Def: Assigning a known value to a variable at the time of its deceleration is called
initialization of the variable.
Explanation: when a variable is declared, memory location is assigned to it. The value in
that memory location is also assigned is also assigned to the variable.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.27

Example: Int marks=950


Float Avg=85.9

Exercise
Question #.01 Select the most appropriate choice.
i. what is the set of instructions that till a computer what to do and how to do
called_____________.
a. compiler b. Program c. Comments d. Hardware
ii. Low level language are close to ________________.
a. Human language b. machine language c. computer hardware d. computer software
iii. which of the following modules is not part of c programming?
a. compiler b. Editor c. Linker d. Convertor
iv. The output of the compiler is called________________.
a. the program b. source code c. linked code d. object code
v. what is the type of language in which instructions are written in binary form
called_______________.
a. Machine language b .Assembly language c. High level language d. none
vi. Which of the following is not a high level language?
a. BASIC b. Assembly language c. Pascal d. FORTRAN
Vii. Which of the following is a compiler directive?
a. #include<stdio.h> b. Float x; [Link] main() d. All of these
viii. The process of converting source code into machine code is known as_____
a. Compilation b. Executing c. Linking d. Saving
Ix. A quantity whose value may change during execution of the program is called
a___________.
a. constant b. variable [Link] d. symbol
X. The execution of a C program starts from function.
a. Const() b. main() [Link] d. start

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.28

CHAPTER # 03 INPUT AND OUTPUT HANDELING


Definition:
Function that are used to get data and then to assign it to variables are known as input
functions, while the functions that are used to receive data from the computer memory
and then send it to the out devices are called output functions.
Definition2:
In any programming language input means to feed some data into program and output
means to display some data on screen, printer or any file.
OUTPUT FUNCTIONS:
In the C language following are the input functions:
(a) Printf( ) function
(b) puts( ) function
(c) Cout( ) function

(a) Printf( ) function:


Definition:
This is one of the most frequently used function in C language for output.
Explanation:
The printf( ) function is used to print the character, string, integer etc onto the output
screen. The general format of printf( ) function is:
Printf(“escape sequence / format specifier”, variable/expression);
Escape sequence: it is a sequence of characters that does not represent itself when
used inside a character or string, but is translated into another character or a sequence
of character that may be difficult to represent directly.
Format specifier: the format specifier is used to conversion specification code. It is
also used according to the format of output values.
Variable/expression: it is a list of quantity to be printed according to format
specifier.
some common and useful format specifiers and escape sequences are:
format specifiers
%d integers
%f floating
%c character
%s string
Escape sequence:
\n to print newline

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.29

\t to print tab
Program 3.1:
Program to print a string of characters on a screen.
#include<stdio.h>
#include<conio.h>
Void main( )
{
clrscr( );
printf(“\n welcome to programming environment”);
printf(“\n this is my first program”);
getch();
}
OUTPUT
Welcome to programming environment
This is my first program

Program 3.2:
Program to print 1 2 3 4 using printf( ) function:
#include<stdio.h>
#include<conio.h>
Void main( )
{
clrscr( );
int a=1, b=2, c=3,d=4;
printf(“%d\t %d\t %d\t %d\t”,a,b,c,d);
getch( )
}

OUTPUT
1 2 3 4

(b) Puts( ) function:


Definition:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.30

Like a printf( ) function puts ( ) function can also use to display message on screen.
General format is:
Puts(string_variable-name);
Uses of puts( ) function:
 It is use to printing message
 Ask user to enter the data
 It is also use to orienting result
Program 3.3:
Program to output a string on the screen by using puts( ) function.
#include<stdio.h>
#include<conio.h>
Void main( )
{
clrscr( );
puts(“my name is SAQIB QURESHI”);
getch( );
}
OUTPUT
My name is SAQIB QURESHI

(c) cout<< fuction:


the cout<< function is used in the C++ and object oriented C++ programming. It is
used to display output on the screen. It is used along with insertion operator <<.
The general form/syntax of cout is:
cout<<”variable or constant or expression or string of characters”;
variable: any variable whose value is to be display on the screen.
Constant: Any constant is to be printed on screen.
Expression: Any value obtained from arithmetic expression and also printed
on a screen.
String of character: String of character or a message is to be printed on the
screen.
Program 3.4:
Program to show the sum and product of two numbers.
#include<iostream.h>

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.31

#include<conio.h>
Void main( )
{
clrscr( );
int a=15, b=22, c, product;
cout<<”\n this program will add and multiply two numbers”<<endl;
c = a+b;
product= a*b;
cout<<”\n the sum of “<<a<<”and”<<b<<” is <<c<<endl;
cout<<”\n the product of “<<a<<”and”<<b<<” is <<a*b<<endl;
getche( );
}
OUTPUT
This program will add and multiply two numbers
The sum of 15 and 22 is 37
The product of 15 and 22 is 330
NOTE: endl is also work as a \n, and it is pronounced as End L.
INPUT FUNCTION:
Definition:
Input functions are those functions through which data is entered into the
computer. There are several ways to assign data to variable. The data can be assign to
the variable through input/assignment statement. The following input functions are:
a) scanf( ) function
b) getch( ) function
c) getche( ) function
d) getchar( ) function
e) gets( ) function
f) cin<< function
(a) scanf( ) function:
Definition:
Scanf( ) function is used to accept values for variables during the program
execution. The scanf( ) function inputs any type of data. The general syntax is:
scanf(“format specifier”, &var1,&variable2,…….);
where the var1 and var2 are the list of variables separated by commas, in which the
values are to be assign. The symbol & used to represent the address of memory

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.32

location. For example we input the values of two integers i-e a and b, so the scanf( )
function is written as:
scanf(“%d,%d”,&a,&b);
here %d is a format specifier for integer.
Program 3.5:
Program to input student’s roll number, total marks, obtained marks and
calculate percentage.
#include<stdio.h>
#include<conio.h>
Void main( )
{
Int rno, tm, obm
float percentage;
clrscr( );
printf(“\n Enter Roll number=:”);
scanf(“%d”,&rno);
printf(“\n Enter total marks=”);
scanf(“%d”,&tm);
printf(“\n Enter obtained marks=”);
scanf(“%d”,&obm);
percentage = obm*100/tm;
printf(“\n percentage=%d”, percentage);
getche( );
}
OUTPUT
Enter Roll number: 10
Enter total marks= 800
Enter obtained marks= 650
Percentage = 81.25
(b) getch( ) function:
Definition:
The getch( ) function is used to read a single character from the keyboard with
echoing it on the screen.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.33

The getch( ) is very important function that is used to display a single character
without showing the character on the screen.
General syntax is:

getch( );

program 3.6:
#include<stdio.h>
#include<conio.h>
Void main( )
{
clrscr( );
char ch;
printf(“enter character:”);
ch=getch( );
printf(“\n”);
putchar(ch);
getch( );
}
OUTPUT
Enter character:
S

(c) getche( ) function:

Definition:

This function is used to read and display a single character from the keyboard
with echo on the screen.

The getche( ) function is display a single character from the keyboard but its shows
the character on the screen.

General syntax is:

getche( );

program 3.7:
#include<stdio.h>
#include<conio.h>
Void main( )
{
clrscr( );

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.34

char ch;

printf(“enter character:”);

ch=getche( );

printf(“\n”);

putchar(ch);

getche( );

OUTPUT

Enter character: S

(d) getchar( ) function:

Definition:

The getchar( ) function is used to read a character from the keyboard with echo on the
screen by pressing the ENTER key.

Explanation:

The getchar( ) function work as a getche( ) function but it requires the pressing
ENTER key after entering the character.

Syntax is:

getchar( );

Program 3.8:
#include<stdio.h>
#include<conio.h>
Void main( )
{
clrscr( );

char ch;

printf(“enter character:”);

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.35

ch=getchar( );

printf(“\n”);

putchar(ch);

OUTPUT

Enter character = S ENTER

(e) gets( ) function:

Definition:

The gets( ) function reads in an entire string until user presses ENTER key.

Explanation:

Whenever gets( ) statement encounters then characters entered by user will be copied
into the variable. If user starts accepting characters and if new line character appears
then the newline character will not be copied into the string variable i-e name.

Program 3.9:
#include<stdio.h>
#include<conio.h>
Void main( )
{
char name[20];
clrscr( );

printf(“enter your name:”);

gets(name );

puts(name);

getch( );

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.36

OUTPUT

Enter your name: Abbottabad

Abbottabad

Note: the which we enter in any array should be at least 20 characters.

Program 3.10:

Write a program to get name and age (in years) of a person. Calculate the age in
month and print the name of the person and its age in month.
#include<stdio.h>
#include<conio.h>
Void main( )
{
int age, age_month;
char name[40];
clrscr( );

printf(“\n enter your name:”);

gets(name );

printf(“\n enter your age:”);

scanf(“%d”, &age);

age_month=age*12;

printf(“\n age in months = %d”,age_month);

getche( );

OUTPUT

Enter your name: Saqib Qureshi

Enter your age= 30

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.37

Age in month = 360

(f) cin function:


in c++ programming cin is an input stream(flow) and always used with
extraction function operator>>. It pauses the program until value(s) is entered
from the keyboard. It is also used for both input of numeric values as well as
character values.

Syntax of cin is:

cin>> variable1>>variable2>>……>>variable n;

like a scanf( ) function cin does not require the & operator at the start of the
variable name.

Program 3.11:

write a program to converts Fahrenheit in Celsius temperature. The Fahrenheit


temperature should be input from the keyboard at the runtime.
#include<stdio.h>
#include<conio.h>
Void main( )
{

float ftemp, ctemp;

clrscr( );

cout<< “\n please input a value for Fahrenheit temperature:”;

cin>>ftemp;

ctemp = (ftemp – 32) * 5/9;

cout<<”\n Celsius equivalent of Fahrenheit :”<<ftemp<<”is”<<ctemp;

getche( );

OUTPUT

Please input a value for Fahrenheit temperature: 98.6

Celsius equivalent of Fahrenheit 98.6 is 37

Statement terminator:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.38

Definition:

The statement terminator is used at the end of the statement. Its indicates the
compiler that the statement ends here. If the statement terminator is not used at the
end of the statement, then the C compiler give an error message during the
compilation of the program.

The symbol of the statement terminator is semi colon ( ; )

For example, in the clear screen statement we write this statement as:

clrscr( );

or in Printf( ) statement it will be written as:

printf(“My name is Saqib”);

thus the semi colon shows the end of statement.

Format specifier:

Definition:

It is the conversion of specification code. It is an operator used in input/output


function which is referred by an object or a variable.

A list of commonly used format specifiers are given in the table.

Format Purpose
specifiers

%d, % i Signed integer

% ld Long integer

%f Floating point (decimal notation)

%g Floating point (exponential notation)

%e Floating point (exponential notation)

%c Signed character

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.39

%s String

Integer format specifiers:

The %d format specifier is used to Read and print an integer and %id is used for long
integer.

Program 3.12:

#include<stdio.h>

#include<conio.h>

Void main( )

Clrscr( );

Printf(“a= %d \n”,a);

Printf(“b= %d \n”,b);

getche( );

Here %d will be replaced with the value of ‘a’ and ‘b’.

Floating point format specifiers:

The %f , %e and %g is used to Read and print floating point format specifier.
%f format specifier is used for floating point (decimal notation) , %g for exponential
notation and %e for exponential notation.

Program 3.13:

#include<stdio.h>

#include<conio.h>

Void main( )

Int a;

float b;

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.40

clrscr( );

a = 15;

b = a/2;

Printf(“a= %d \n”,a);

Printf(“b= %f \n”,b);

Printf(“b= %e \n”,b);

getche ( );

OUTPUT

a = 15

b = 7.5

b = 7.5 e+0

character format specifiers:

% c is a character format specifier used to Read and print a single character.

Program 3.14:

#include<stdio.h>

#include<conio.h>

Void main( )

Char ch=’A’;

Clrscr( );

Printf(“character = %c\n”,ch);

getche( );

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.41

OUTPUT

Character = A

Escape sequence:

As escape sequence refers to a combination of characters beginning with a


back slash ( \ ) followed by letters or digit. These can be used inside the string or
independently. It is a special non-printed characters. It is also called control sequence.

Following table shows common escape sequences.

Escape Purpose Example Output


Sequence

\n New line(moves the printing Printf(“Hello\n Hello


control to the beginning of the World”);
text. World

\t Horizontal tab (moves the Printf(“Hello \t Hello world


cursor one tab forward) World”);

\a Bell (alert) cause a beep sound Printf(“Hello \a how r Beep after hello and
in the computer internal you”); before how are you.
speaker.

\b Back space (used to move Ptintf(“Hello \b “Hello “ is printed


cursor one space back after World”); but \b deletes “o”.
printing) then “world “ is
printed. So
Hellworld is
displayed on the
screen.

\f Form feed (used to printed the Printf(“Hello\fWorld”); HelloWorlf after


output on the printer after printing “Hello” the
feeding a blank form) computer will
include a blank
paper and then print
the remaining
output. It is used
during printing.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.42

\’ Single quotation mark (used to Printf(“\ ‘ HelloWorld\’ ‘HelloWorld’


print single quotation mark ‘) “);

\” Double quotation mark(used to Printf(“\”Hello “Hello World”


print double quotation mark “) World\””);

\\ Back slash (used to print a back Printf(\\Hello World\\); \Hello World\


slash)

Operators:

Definition:

Operators are the symbols which operates on values or a variable.


Or These are special character which performs specific operations on their operands.
When operands and operators are combined then it forms an expression.
Explanation:
Operators are the symbols used to perform certain task/operation on data. C
programming has wider range of operators to perform a various Operations. For
better understanding of operators these operators can be classified as:
1. Arithmetic operators.
2. Assignment operators.
3. Compound operators.
4. Increment operators.
5. Decrement operators.
6. Relational operators.
7. Logical operators.
8. Unary and binary operators.
9. Conditional operators.
Arithmetic operators:
Definition:
An arithmetic operator is a mathematical function that takes two operands and
perform a calculation on them. These are addition subtraction division multiplications
etc.
Explanation:
These operators perform mathematical operations on their operands. They are used in
a common arithmetic and most of computer languages contains a set of such operators

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.43

that can be used within equations to perform a number of types of sequential


calculations.
The following is the list of all arithmetic operators:
Operation symbols Description
Addition + Add two values
Subtraction - Subtracts one value from another value
Multiplication * Multiplies two values
Division / Divides one value by another value
Modulus % Give the reminder of the division of two integers. It is
also called reminder operator

The arithmetic operators work with numeric values. Let suppose!


We have two variable a and b, where a = 10 and b = 5.
The arithmetic operators can be used as:
Operation Result
a+b 15
a–b 5
a*b 50
a/b 2
a%b 0

Assignment operator:
Definition:
The assignment operator is used to assign the values to the variables. It is denoted by
“=”.
Explanation:
The assignment operator is used to assign numeric or character values. However,
string data cannot be assigned to a variable with this operator. General format for the
assignment operator is:
Variable = character_constant /variable/expression;
Few examples of assignment operators are as follows:
Rno =103;
Percentage = 76.5;

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.44

Gender = ‘M’
Area = (3.14)*r*r;
It is important to note that a value assigned to a variable must be of the same type as
that of the variable type.
Compound operators:
Definition:
Compound operator is used to perform mathematical operations more easily.
The compound assignment operator combines the simple assignment operator with
other binary operator.
Explanation:
Compound assignment operators provide a shorter syntax for assigning the result of
an arithmetic operator. They perform the operation on the two operands before
assigning the result to the first operand. There are eleven compound assignment
operators.
The general syntax is:
Variable op= expression;
Or a+= 10; it is equivalent to a = a + 10;
a - = 10; it is equivalent to a = a - 10;
a*= 10; it is equivalent to a = a * 10;
program 3.15: Write a program that perform all compound assignment
operations on an integer.
#include<stdio.h>
#include<conio.h>
Void main( )
{
Int a;
a = 10;
printf(“\n the value of a = %d”,a);
a += 5;
printf(\n“value of a after a += 5 = %d”,a);

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.45

a - = 5;
printf(\n“value of a after a - = 5 = %d”,a);
a * = 2;
printf(\n“value of a after a *= 2 = %d”,a);
a / = 2;
printf(\n“value of a after a /= 2 = %d”,a);
a % = 2;
printf(\n“value of a after a %= 2 = %d”,a);
getche( );
}
OUTPUT
Value of a = 10
value of a after a += 5 = 15
value of a after a - = 5 = 10
value of a after a *= 2 = 20
value of a after a /= 2 = 10
value of a after a %= 2 = 0
Increment operator:
Definition:
Increment operators are used to increase the value or add the value to the
variable by 1. The increment operator is represented by ++. It is also a unary operator.
Explanation:
The increment operators are used either of after variable. If the increment
operator written before the variable, it is called prefix increment operator. And if the
increment operator written before the variable, it is called postfix increment operator.
For example, if we add 1 to the value of variable x, then it will be written as”
X = X +1; Or
X ++; Or ++X;
Prefix increment operator:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.46

Definition:
When an increment operator is used in prefix (before the variable) in an expression. It
adds 1 to the value of the variable before the value of the variable is used in
expression.
For example:
Sum = a + (++b);
Program 3.16:
#include<stdio.h>
#include<conio.h>
Void main( )
{
Clrscr( )
Int a, b, c, sum;
a= 1;
b=1;
c=3;
sum = a + b +(++c);
printf(“\n sum = %d”,sum);
printf(“\n c= %d”,c);
getche( );
}
OUTPUT
Sum = 6
C=4
In this program 1 value will be added to c before it is used in the expression. So the
sum is 6 and the value of c is 4.
Postfix increment operator:
Definition:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.47

When an increment operator is used in a postfix (after the variable) increment


in an expression, it adds 1 to the value of the variable after the value of the variable is
used in expression.
For example:
a + (c ++);
in this case 1 will be added to the value of c after its existing value has been used in
the expression. According to program # 3.16 the sum will be equal to 5 and c = 4.
Decrement operator:
Definition:
The decrement operator is represented by double minus sign (--). It is used to subtract
1 from the value of an integer variable.
Explanation:
The decrement operator is used either or after the variable. If the decrement operator
written before the variable, it is called prefix decrement operator. And if the
decrement operator written after the variable, it is called postfix decrement operator.
For example:
X -- or -- X
Prefix decrement operator:
Definition:
When a decrement operator is used in prefix mode (before the variable) in an
expression, it subtracts 1 to the values in the variable before the value of the variable
is used in expression.
For example:
Sum = a + b + (--c);
Program 3.17:
#include<stdio.h>
#include<conio.h>
Void main( )
{
Clrscr( )
Int a, b, c, sum;

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.48

a= 1;
b=1;
c=3;
sum = a + b +(--c);
printf(“\n sum = %d”,sum);
printf(“\n c= %d”,c);
getche( );
}
OUTPUT
Sum = 4
C=2
In this program 1 value will be subtracted from c before it is used in the expression.
So the sum is 4 and the value of c is 2.
Postfix decrement operator:
Definition:
When a decrement operator is used in prefix mode (after the variable) in an
expression, it subtracts 1 to the values in the variable after the value of the variable is
used in expression.
For example:
Sum = a + b + (c--);
Relational operators:
Definition:
The operators which compare two operands (Values) and give result as
true/false or equal, less/greater etc… is called relational operators.
Explanation:
A relational operator compares two values. It produced true or false. The relational
operator allow us to compare two values to check whether they are equal to each
other, unequal or whether one is greater than other.

C language provides the following relational operators:


Operator Function
> Greater than operator returns true if the value on the left side of

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.49

> is greater than the value on the right side, otherwise returns
false.
less than operator returns true if the value on the left side of <
< is less than the value on the right side, otherwise returns false.
== Equal to operator returns true if the values on both side of ==
are equal otherwise, returns false.
>= Greater than or equal to operator returns true if the value on the
left side of > = is greater than or equal to the value on the right
side, otherwise returns false
Less than or equal to operator returns true if the value on the
<= left side of < = is less than or equal to the value on the right
side, otherwise returns false
!= Not equal to operator returns true if the value on the left side of
! = is not equal to the value on the right side, otherwise returns
false

Use of relational operator:


If x = 10, y = 20, z = 5, then the output of the following relational expression will be:

Relational Output Returned


Expression
x>y False
Y<z False
X == z False
X<=y True
x> = y False
Y !=x True

Logical operators:
Definition:
Logical operators are used to evaluate compound condition. The logical
operator is used to perform logical operations.
Explanation:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.50

In C language there are three logical operator AND , OR,NOT are used to form
compound conditional expressions in which more than one logical condition are
tested in the same statement. A condition in C evaluate to either true or false which
instructs the computer to do a specific task. These operators are as below:
i. And operator
ii. OR operator
iii. Not operator
i) AND operator: it is used for logical multiplication. It is used to combine two or more
expressions (conditions) and thus form a compound expression. if all conditions
are true then the result will be true otherwise the result will be false.
Condition 1 Operator Condition 2 Result
False && False False
False && True False
True && False False
True && True True
For example, we have two variables i-e a= 100 and b= 50 then the compound
condition:
(a=10) && (b=10) is true because both conditions are true.
And if (a>50) && (b=>50) is false because second condition is false.

ii) OR operator: It is used for logical addition. In this operator if one of the given
condition is true then the result will be true. If both the condition is false, then the
result will be false.
Condition 1 Operator Condition 2 Result
False || False False
False || True True
True || False True
True || True True
For example, we have two variables a= 100 and b = 50,
The condition (a>50) || (b = >50) is true, as one condition is true.
iii) NOT operator: it reverts the condition from true to false and from false to true.
Operator Condition Result
! True False
! False True
For example, we have two variables a= 100 and b = 50,
The condition !(a == b) is true, as a is not equal to b.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.51

Difference between the assignment operator (=) and equal to operator (==):
The assignment operator “=” is used to assign a value to a variable whereas the
equal to operator “==” is used to compare two value of the same data type.
For example:
X = 15;
Y = a;
Z = ‘s’;
In the above statements, variable X is assign the value 15, y is assign the value stored
in a variable “a” and c is assign the character ‘s’.
The relational operator == is used to build a condition based on which computer takes
some action.
For example:
b == 10;
x == y;
in this case the value of b is equal to 10 is true otherwise false. And in second
condition the equal to operator checks whether the value of x is equal to the value of
y. if the value of x is equal to the value of y than it will be true otherwise false.
Difference between Unary and Binary operators:
Unary operator:
Definition:
An operator that works with single operands is called Unary operator.
OR a unary operator operates with only one operands i-e an operation with a single
input, or in other words, a function of a one variable.
For example:
-, ++ , --
As these operators are used with operands i-e
-a
n++
--x
Binary operator:
Definition:
An operator that works with two operands is called Binary operator.
OR A binary operator operates with two operands i-e an operation with two inputs,
or the function perform by two variables.
The binary operators are:
+, -, *, /, %
For example:
X+y
X–y
y/z
x*y
x%y
Conditional operator (?):
Definition:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.52

The conditional operator is also called ternary operator. It works with three
operands/variables. The conditional operator is also called decision making structure.
Syntax:
(condition) ? true-case statement: false-case statement;
Condition: the condition is specified as relational or logical expression.
True-case: It is executed if expression evaluates to true.
False-case: It is executed if expression evaluates to false.
For example:
Suppose we have a variable a=5 then the following statement is:
X=(a > 50) ? 1 : 0;
This will assign 1 to x if the condition a>50 is true otherwise it will assign 0 to
x if the condition is false. As a > 50 is false so x=0.
Operator and their precedence:
Operator precedence determines the group of terms in an expression and decides how
an expression is evaluated. Some operators have higher precedence than other and
some lowest precedence.
The following table show the operator and their precedence:
Precedence Operators Type
1 ! Logical NOT
2 *, /, % Multiplication, Division &
Modulus
3 +, - Addition & Subtraction
4. <, >, <=, >= Relational operators
5 ==, != Relational operator
6 && Logical AND
7 || Logical OR
8 = Assignment operator

Exercise
Q.1: Select the most appropriate choice.
1. The function that are used to get data and then to assign it to variables are known
as______________.
a. Output functions b. String functions c. Numeric functions d. Input
functions
2. which of the following functions is used to display output on the screen_____________.
a. Printf( ) b. scanf( ) c. gets( ) d. getchar( )

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.53

3. Which function is used to accept values for variables during program


execution________.

a. Printf( ) function b. cout function c. stdio.h function d. scanf( )


function
4. in C language every statement is terminated by_________________.
a. Full stop b. Double quotes c. semi colon d. Comma
5. Which of the following is the format specifier for integer data type_______________.
a. %s b. % c c. % d d. %f
6. which escape sequence is used to insert new line in output?
a. \new b. \ t c. \ n d. \line
7. Which of the following is called Modulus operator.
a. + b. % c. / d. *
8. Which operator is used to add 1 to the value of an integer variable.

a. + b. = c. -- d. ++

9. Which operator is used to add 1 to the value of the variable after the value of the variable
has been used in the expression?
a. post fix increment b. prefix increment c. Modulus operator d. Binary operator
10. which operator is used to produce true result if both conditions are true.
a. AND b. OR c. NOT d. All of the above

Q#2. Give short answers to the following questions.


i. What is the use of format specifiers? (already explained )
ii. Why escape sequences are used? Give examples. (already explained )
iii. What is the purpose of gets( ) functions? (already explained )
iv. Differentiate between getch( ) and getche( ) functions. (already explained )
v. Evaluate the following expressions.
a. 9 – 5 *(6+2)
b. 60 / 10 * 24 + 3
c. 100 % 50 – 100 % 3
Ans (a):
9 – 5 *(6+2)
9 – 5 *8
9 – 40
- 31
Ans (b):
60 / 10 * 24 + 3
6 * 24 + 3
144 + 3
147

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.54

Ans (c):
100 % 50 – 100 % 3
0 - 1
-1
Vi Differentiate between simple and compound assignment operators.
(see answer already explained )

Q.3: What are operators? Explain different types of operators with examples.
(see answer )

Q.4: What is output functions? Describe in detail different types of output functions.
(see answer )

Q.5: Discuss different format specifiers and escape sequences used in printf( ) functions.
(see answer )

Q.6: Explain different types of input functions with example.


(see answer at page # )
Q.7: Write a program that reads three numbers and prints their sum, product and average.
Ans: #include<stdio.h>
#include<conio.h>
Void main( )
{
Int a, b, c, sum, prod;
float avg;
printf(“\n enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
sum= a + b + c;
prod= a * b * c;
avg = sum/3;
printf(“sum is =%d\n”,sum);
printf(“product =%d\n”,prod);
printf(“average =%f\n”,avg);
getche();
}
Q.8: Write a program that reads the base and height of a triangle and print its
area.
Ans: #include<stdio.h>

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.55

#include<conio.h>
Void main( )
{
float b, h, area;
printf(“\n enter the value for base and height”);
scanf(“%f %f”,&b, &h);
area = (b*h) / 2;
printf(“area is =%f\n”,area);
getche( );
}

Q.9: Write a program that reads temperature in Celsius, converts it into


Fahrenheit and prints it on the screen.
Ans: #include<stdio.h>
#include<conio.h>
Void main( )
{
float C, F;
printf(“\n enter Celsius temperature”);
scanf(“%f”,&c);
F= 32 + C *5/9;
printf(“Fahrenheit temperature =%f\n”,F);
getche( );
}
Q.10: Write a program that reads name and address of a student and prints it
on the screen using gets ( ) and puts( ) functions.
Ans: #include<stdio.h>
#include<conio.h>
Void main( )
{
char name[20];
char address[30];
clrscr( );

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.56

printf(“\n Enter student name:”);


gets(name);
puts(name);
printf(“\n Enter student address”);
gets(address);
puts(address);
getche( );
}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.57

CHAPTER # 04 CONTROL STRUCTURE


CONTROL STRUCTURE
Definition:
Control structure is the block of programming that analyzes variables and
chose a direction in which to go based on given parameters.
Explanation:
The term flow control details the direction the program takes. Hence it is the
basic decision making process in computing. Flow control determines how a
computer will respond when given certain condition and parameters. We use control
structures to makes decision and after the direction flow in one or the other path/paths
available.
Control statement:
Definition:
A control statement is a statement that determines whether other statement will
be executed.
Or the control statements are used for controlling and execution of the program. There
are the four control statements in the C language. The control statements are also
called conditional/selection statement.
Conditional/selection statement:
C language provides the following statement for implementing the selection control
structure.

Types of control structures:


i. If-statement
ii. If-else statement
iii. Switch statement
iv. Nested if statement
i. If statement:
Definition:
If statement is a decision making statement. It is the simple form of selection
statement. It is used to execute or skip a statement or a set of statements by checking a
condition.
OR
The if statement is a simple control that test whether a condition is true or false. The
condition can include a variable, or be a variable.
Syntax of if statement is:
If(condition)

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.58

Statement;
The above syntax is used for single statement. If we have multiple statements then it
will written between two braces { }. It is also called block of statements.
The syntax of if statement when statements in a bock, written as:
If(condition)
{
Statement 1;
Statement 2;
.
.
.
Statement n;
}

Structure of if statement:

If True
statement

Statements (s)

False

The rest of code

Program 4.1: A program that prints the entered number when it is greater than
50.
#include<stdio.h>
#include<conio.h>
Void main()
{
Int x ;

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.59

Clrscr();
Printf(“\n enter an integer =”);
Scanf(“%d”, &x);
If(x>50)
Printf(“%d”, x);
getch();
}
OUTPUT
Enter an integer = 75
75
Program 4.2:
The following program executes a single statement if the given condition is
true.
#include<stdio.h>
#include<conio.h>
Void main( )
{
Int a, b;
Clrscr( );
a = 1000;
b = 500;
if (a>b)
printf(“\n value of a is greater than b”);
getche( );
}
OUTPUT
Value of a is greater than b

Program 4.3:
Program that inputs two numbers and print the message if both are equal.
#include<stdio.h>
#include<conio.h>
Void main( )

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.60

{
Clrscr( );
Int a, b;
Printf(“\n enter first number:”);
Scanf(“%d”, & a);
Printf(“\n enter second number:”);
Scanf(“%d”, & b);
If (a==b)
Printf(“both numbers are equal”);
getche( );
}
OUTPUT
Enter first number: 50
Enter second number: 50
Both numbers are equal

If –else statement:
Definition:
If-else statement is used to executes on statement or a group of statement until
the condition is true or false.
In the if-else statement if one condition is executed and become true than other
statement will be false.
Syntax of if-else statement:
If(condition)
Statement;
else
statement;
when two or more statements are used than it can be written in braces { }.
The syntax of compound if-else statement is written as:
If(condition)
{
Statement1;
Statement 2;
.
.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.61

Statement n;
}
else
{
Statement1;
Statement 2;
.
.
Statement n;
}

False True
If

condition

Statement (s) Statement (s)

The rest of code

Program 4.4: A program that inputs a number and find whether it is even
or odd using if-else structure.
#include<stdio.h>
#include<conio.h>
Void main( )
{
Int n;
Clrscr( )
Printf(“Enter a number:”);
Scanf(“%d”, &n);
If(n%2 ==0)
Printf(“%d is even”, n);
else
printf(“%d is odd”,n);
getch( );
}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.62

OUTPUT 1
Enter a number: 10
10 is even

OUTPUT 2
Enter a number: 17
17 is odd

Program 4.5: A program that prints the larger of two numbers:


#include<stdio.h>
#include<conio.h>
Void main( )
{
Int x, y;
Clrscr( )
Printf(“Enter Two numbers:”);
Scanf(“%d %d”, &x, &y);
If(x > y)
Printf(“\n %d is larger number than %d”, x,y);
else
printf(“\n %d is larger number than %d”, y,x);
getch( );
}

OUTPUT
Enter two numbers: 15 20
20 is larger than 15

Program 4.6: A program that finds the smallest number of three numbers:
#include<stdio.h>
#include<conio.h>
Void main( )

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.63

{
Int x, y, z, s;
Clrscr( )
Printf(“Enter Three numbers:”);
Scanf(“%d %d %d”, &x, &y, &z);
If(x < y)
S = x;
Printf(“the smaller number is: %d”, s);
else
s=y
if(s <z)
printf(“the smaller number id %d:”, s);
else
printf(“the smaller number is %d:”, z);
getch( );
}
OUTPUT
Enter three numbers: 10 6 12
The smaller number is: 6

Switch statement:
Definition:
This statement is used for multiple choice or selection. It is a substitute of if-
else statement. It is also used when multiple choices are given and one is to be
selected.
Explanation:
A switch statement allows a variable to be tested for equality against a list of
values. Each value being switched on is checked for each switch case. The switch
statement evaluates an expression and return a value. Only one of the case in the
switch statement is executed depending upon the value returned by the expression.
The syntax is used for switch statement as:
Switch (expression)
{
Case 1:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.64

Statements;
break;
case 2:
statements;
break;
.
.
.
Case n:
Statements
break;
default:
statements;
}
In the syntax, expression appears within the switch statement. First the expression is
evaluated and then the value returned by the expression is compared with each case
number. If it matches with case number than the statement of those case will be
executed.
The break is used to exit from switch body. It is used at the end of each case.
The keyword default used in the body of the switch statement. The default used when
no match in each case, under this condition the default is executed.

Is switch True Statements for


expression= case first case
1?

False

Is switch Statements for


expression= case second case
2? True

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.65

False
Default
statements
No match

Next statement/s

Program 4.10: A program to show that input character is vowel or not:


#include<stdio.h>
#include<conio.h>
Void main( )
{
char ch;
clrscr( );
printf(“Enter a character””);
scanf(“%c”, & ch);
switch (ch)
{
Case ‘a’:
Printf(“Vowel a”);
break;
Case ‘e’:
Printf(“Vowel e”);
break;
Case ‘i’:
Printf(“Vowel i”);
break;
Case ‘o’:
Printf(“Vowel o”);

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.66

break;
Case ‘u’:
Printf(“Vowel u”);
break;
default:
Printf(“Not aVowel”);
}
getche( );
}
OUTPUT
Enter a character: a
Vowel a

Using nested section structure:


Definition:
In the C language programming, nesting is related to the enclosing of control
structure one into another. For example, if statement can be nest inside another if
statement.
Generally, or in other words, statement within a statement is called nested statement.
The syntax of such nesting techniques is:
If (condition)
{
If (condition)
{
Statement (s);
}
else
{
Statement (s);
}}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.67

Program 4.11: A program to find that a number that is input from the keyboard is
Positive, negative, even, or odd?
#include<stdio.h>
#include<conio.h>
Void main ( )
{
Int num;
Printf(“Enter a number:”);
Scanf(“%d”, & num);
If(num>0)
{
Printf(“\n you enter positive number”);
If(num%2==0)
Printf(“\n You enter even number”);
else
printf(“\n you enter odd number”);
}
Else
Printf(“you enter negative number”);
getche( );
}
OUTPUT
Enter a number: 7
You enter positive number
You enter odd number

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.68

Exercise
Q#1: Select the most appropriate choice.
1. Which programming statement makes a decision?

a. If b. break c. Assignment d. Printf ( )

2. The conditional portion of if statement is enclosed within ___________.

a. { } b. ( ) c. [ ] d. < >

3. Which of the following is NOT a part of if statement?

a. A condition that evaluate as a character b. A condition the evaluates as true or


false
c. A true block d. A false block
4. the case block ends with _______________.
a. } b. { c. break; d. default
5. what is output of the following code.
If ( ( 1==1) || ( 2==3) )
Printf(“Good”);
else
printf(“Bad”);
a. Good b. Bad c. GoodBad d. No output

Q#2: Write a program in C to input three integers. Find out the largest among
these integers using if-else structure and print it on the screen.

Ans: #include<stdio.h>
#include<conio.h>
Void main( )
{
Int x, y, z, largest;
Clrscr( )

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.69

Printf(“Enter Three numbers:”);


Scanf(“%d %d %d”, &x, &y, &z);
If(x > y)
largest = x;
Printf(“the largest number is: %d”, largest);
else
largest = y
if(largest > z)
printf(“the largest number id %d:”, largest);
else
printf(“the largest number is %d:”, z);
getch( );
}

Q# 3: Write a program in C to input a single character and print a message “it is


vowel” or “it is consonant”. Using if-else structure.
#include <stdio.h>
#include<conio.h>
void main( )
{
char c;
clrscr( );
printf("Enter an alphabet: ");
scanf("%c",&c);
if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U')
printf("%c is a vowel.",c);
else
printf("%c is a consonant.",c);
getche( );
}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.70

Q#4: Write a program in Q#3 using switch-case structure.


#include <stdio.h>
#include<conio.h>
void main( )
{
char ch;
clrscr( );
printf("Input a character\n");
scanf("%c", &ch);
switch (ch)
{
Case ‘a’:
Printf(“Vowel a”);
break;
Case ‘e’:
Printf(“Vowel e”);
break;
Case ‘i’:
Printf(“Vowel i”);
break;
Case ‘o’:
Printf(“Vowel o”);
break;
Case ‘u’:
Printf(“Vowel u”);
break;
default:
Printf(“Not aVowel”);
}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.71

getche( );
}
OUTPUT
Enter a character: a
Vowel a

Q#5: write the output of the following program.


Ans: #include<stdio.h>
Void main( )
{
int a, b, c;
a=b=10;
c=13;
if ( ( a==b)&&(a>c) )
printf(“condition is true \n”);
else
{
Printf(“a is equal to b \n”);
Printf(“a is not greater than b \n”);
}
}
OUTPUT
a is equal to b
A is not greater than b

Q#6: find the error if any in the following program.


#include<stdio.h>
Void main( )
{
int a;
print(“Enter any number=”);
scanf(“%f”,&a);

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.72

if (a>10)
printf(“value is greater than 10”);
else if
printf(“value is less than 10”)
}
Ans:
In line number 5 the output statement not defined. It’s a syntax error. Print to
printf ().
In line number 6 the format specifier %f is not required because we declare
integer format specifier. So %d is correct format specifier to use in scanf( )
function.
In line number 10, the statement terminator is missing. (;)

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.73

CHAPTER# 05 LOOP STRUCTURE

Loop structure:
Loops cause program to execute the certain block of code repeatedly until test
condition is false. Loops are used in performing repetitive task in programming.
Consider these scenarios:
You want to execute some code/s 100 times.
You want to execute some code/s certain number of times depending upon input from
user.
These types of task can be solved in programming using loops.
There are 3 types of loops in C programming:
for loop
while loop
do...while loop
1. The for loop:
Definition:
The for loop executes one or more statement for a specified number of times. It is a
more frequent loop used by the programmers.
Explanation:
Syntax:
for(initialization; condition; increment/decrement)
{
Body of the loop;
}
Initialization:
It is an expression which specifies the starting value of the counter variable.
Condition:
It is a relational expression. The statement within a loop is executed only if the given
condition is true. If condition is false, the statement will not be executed.
Increment/Decrement:
This part of a loop specifies the change in counter variable after each execution of the
loop.
Body of the loop:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.74

It is a statement or a group of statements in braces { } to be repeated.


For example:
for(I = 1; i<=10;i++)
i=1: is initialization
i<=10 is condition
i++ is increment
program 5.1: A program to display numbers from 1 to 10 using for loop.
#include<stdio.h>
#include<conio.h>
void main( )
{
Int x;
clrscr( );
for(x=1;x<=10;x++)
printf(“%d\t”,x);
getche( );
}
OUTPUT
1 2 3 4 5 6 7 8 9 10

Program 5.2: A program to display numbers in reverse order from 10 to 1.


#include<stdio.h>
#include<conio.h>
void main( )
{
Int num;
clrscr( );
for(num=10;x>=1; --num)
printf(“%d\t”,num);
getche( );
}
OUTPUT
10 9 8 7 6 5 4 3 2 1

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.75

Program 5.3:
A program that inputs a number and displays the table of the number up
to 10 using for loop.
#include<stdio.h> OUTPUT
#include<conio.h> 5x1= 5
void main( ) 5 x 2 = 10
{
5 x 3 = 15
Int tab,n,x;
5 x 4 = 20
clrscr( );
5 x 5 = 25
printf(“\n enter number for the table”);
5 x 6 = 30
scanf(“%d”,&n);
for(x=1;x<=10;x++) 5 x 7 = 35

printf(“\n%d x %d=%d”,n,x,n*x); 5 x 8 = 40
getche( ); 5 x 9 = 45
} 5 x 10 = 50

Program 5.4: A program to calculate the sum of odd numbers from 1 to 20 and
thn print the sum on the screen.
#include<stdio.h>
#include<conio.h>
Void main( )
{
Int n, sum;
Clrscr( );
Sum = 0;
For(n=1; n<=20; n+=2)
{
Sum = sum + n;
}
Printf(“\n sum =%d”, sum);
getche( );
}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.76

OUTPUT
Sum = 10

The while loop:


Definition:
The while loop executes one or more statement until the given condition remains
true.
Explanation:
The while loops checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed, that is, code/s inside the braces { } are
executed. Then again the test expression is checked whether test expression is true or
not. This process continues until the test expression becomes false.
The syntax of the while loop is as follows:
Syntax
While (condition)
{
Body of the loop;
}
Where,
Condition: The condition is given as a relational expression. The body of the loop
is executed only if the given condition is true. If the condition is false, the body of the
loop is never executed.
Body of the loop: It is a statement or group of the statements in braces{ } to be
repeated.
Program5.5: A program that displays “Pakistan” for five times using while loop.
#include<stdio.h>
#include<conio.h>
void main( )
{
Int n;

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.77

clrscr ( );
n = 1;
while (n<=5)
{
Printf(“\n Pakistan”);
n++;
}
getche ( );
}
OUTPUT
Pakistan
Pakistan
Pakistan
Pakistan
Pakistan

Program 5.6: A program to print natural numbers 1 to 10 in descending


order.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n = 10;
clrscr ( );
while (n != 0)
{
Printf(“\t %d”, n);
n--;

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.78

}
getche ( );
}
OUTPUT
10 9 8 7 6 5 4 3 2 1

Program 5.7: A program that resolve the following series and displays the
result using while loop.
2+4+6+………….+20

#include<stdio.h>
#include<conio>
void main ( )
{
Int c, sum=0;
clrscr ( );
c = 2;
while(c<=20)
{
Sum = sum+c;
C = c+2;
}
Printf(“sum = %d”, sum);
getch ( );
}

OUTPUT
Sum = 110

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.79

The do-while loop:


Definition:
The do-while loop executes the statements until the given condition is true.

Explanation:
The do-while loop is similar to the while loop, except that the test condition occurs at
the end of the loop. Having the test condition at the end, guarantees that the body of
the loop always executes at least one time.
The do-while loop is an exit-condition loop. This means that the body of the loop is
always executed first. Then, the test condition is evaluated. If the test condition
is TRUE, the program executes the body of the loop again. If the test condition
is FALSE, the loop terminates and program execution continues with the statement
following the while.
Syntax of do-while loop is:
do
{
body f the loop;
}
while(condition);

where
do: it is the keyword that indicates the beginning of the loop.
Condition: The condition is given as a relational expression. The statement of the
body is executed if the given condition is true. If the condition is false, the statement
of the body are executed only once because the condition comes at the end.
Body of the loop: It is a statement or group of the statements in braces{ } to be
repeated.

Program 5.9: A program to print first ten integers using do-while loop.
#include<stdio.h>

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.80

#include<conio.h>
Void main ( )
{
Int n;
clrscr( );
n =1;
do
{
Printf(“\t %d”, n);
n ++;
}
While( n<=10);
getche( );
}

OUTPUT

1 2 3 4 5 6 7 8 9 10

The break statement:


Definition:
The break statement terminates the execution of the loop when it is used inside the
body of the loop.
Explanation:
When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.81

Program 5.10:A program that inputs a number from the user using for loop. If
the number is greater than 0, it is displayed and the next number is input. The
program exist the loop if the number is 0 or negative using break statement.

#include<stdio.h>
#include<conio.h>
void main ( )
{
Int x, num;
clrscr( );
for(x =1; x<=5; x ++)
{
Printf(“\n Enter a number”);
Scanf(“%d”, &num);
If(num<=0)
break;
printf(“\n you entered %d\n”,num);
}
Printf(“\n OK”);
getche( );
}
The above program uses break statement in for loop. The counter variable x indicates
that the loop should execute for five times. But It is executed only twice.

The continue statement:


Definition:
The continue statement shifts the control back to the beginning of the loop.

Explanation:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.82

The continue statement is used inside the body of the loop.


The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.
For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops,
continue statement causes the program control to pass to the conditional tests.
Syntax of continue statement is:
Continue;

Program 5.11: write a program and use the concept of continue statement
using while loop.

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int c;
c =1;
while(c<=5)
{
Printf(‘\n Pakistan”);
c ++;
continue;
printf(“Islamabad”);
printf(“Peshawar”);
}
getche( );
}
Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.83

OUTPUT
Pakistan
Pakistan
Pakistan
Pakistan
Pakistan
Nested Loop:
Definition:
A loop within another loop is called nested loop. In nested loop an inner loop is
completely enclosed inside an outer loop.
Explanation:
The depth of nested loop depends on the complexity of a problem. We can have any
number of nested loops as required. Consider a nested loop where the outer
loop runs n times and consists of another loop inside it. The inner loop runs m times.
Then, the total number of times the inner loop runs during the program execution is
n*m.
Program 5.12: A program to print the output as shown below. Using nested
for loops.
#include<stdio.h>
Include<conio.h>
void main ( )
{
Int i , j;
clrscr ( );
for(i=1; i<=5; i ++)
{
for(j=1; j<=I; j++)
printf(“\t %d”, j);
}

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.84

printf(“\n”);
}
getche( );
}

OUTPUT

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

EXERCISE
Q.1: Select the most appropriate choice.
i. How many types of loop structures are available in C?
a. 4 b. 3 c. 2 d. 6
ii. Which loop structure always executes at least once
a. do-while b. for c. while d. nested
iii. in which loop the condition comes before the body of the loop?
a. While loop b. do-while loop c. for loop d. a and c both
iv. In which loop the condition comes after the body of the loop?
a. for loop b. While loop c. do-while loop d. a and c both
v. Which of the following statement is used in a body of the loop to exit from the loop?
a. break b. terminate c. exit d. both a and b
vi. a loop within another loop is called___________.
a. Counter loop b. complex loop c. outer loop d. nested loop

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.85

vii. Which statement is used o move the control to the start of loop body?
a. Continue b. break c. while d. for
viii. Which of the following loop is a good choice when the number of iterations are
known in advance.
a. Do-while b. for c. while d. nested

Q.2: Explain different types of looping structures with examples?


Q.3: Differentiate between do-while and while loops. Explain with program
examples?
Q.4: Write a program in C to calculate and print the product of the even number
from 1 to 100 by using while loop?
Ans #include<stdio.h>
#include<conio.h>
void main()
{
int counter;
double a=100,i,prod;
clrscr();
{
printf("Even numbers between 1 to 100\n");
for(counter = 1; counter <= 100; counter++)
{
if(counter%2 == 0)
{
printf("\t%d ", counter);
}
}
}
i=4;
prod=2;
while(i<=a)
{
prod=prod*i; prod=2*4=8
i=i+2; i=2+2 =4
}
printf("\n the prod of even number from 1 to 50 is %2f",prod);
getche();
}
OUTPUT
The even numbers from 1 to 100 is

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.86

2 4 6 8 10 12 14 16 18 20 22 24 26
28 30 32 34 36 38 40 42 44 46 48 50 52
54 56 58 60 62 64 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
Prod= 6.84 X 1079

Q.5: Write a program to display alphabets from A to Z using for loop?


Ans:
#include<stdio.h>
#include<conio.h>
Void main( )
{
char ch;
clrscr( );
for(ch=’A’; ch<=’Z’; ++ch)
printf(“%c”, ch);
getch( );
}

OUTPUT
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Q.6: Write a program to display the following output using nested for loop.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.87

a
a a
a a a
a a a a
a a a a a
Ans: #include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
getch( );
}
Q.7: Write a program in C to print the sum of odd numbers from 1 to 50 using for
loop.
Ans:
#include<stdio.h>
#include <conio.h>
void main( )
{
int i, n, sum=0;

printf("The odd numbers from 1 to 50 as follow: ");

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.88

for(i=1; i<=n; i+=2)


{
sum += i;
}
printf("\n Sum of odd number between 1 to 50 = %d", n, sum);
getche( );
}
OUTPUT
The odd numbers from 1 to 50 as follow:
1 3 5 7 9 11 13 15 17 19 21
Sum = 625

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.89

CHAPTER # 06.
Data:
Raw facts and figures which are processed by digital computer is called data.
OR Data is a collection of facts, such as numbers, words, measurements, observations or
even just descriptions of things.
OR the quantities, characters, or symbols on which operations are performed by a
computer, which may be stored and transmitted in the form of electrical signals and
recorded on magnetic, optical, or mechanical recording media.

Data representation:
Data is represented in a computer by means of simple on/off switches, and
digitally these become 1 and 0. Millions of switches in combination create all the
data in a computer system.
All the data entered into computer is first converted into binary number system i-e 0
and 1. One digit in binary number is called a Bit and the combination of eight bit is
called Byte.
A byte is a basic unit of computer memory that is used to represent data.
For example, when a letter A is input to the computer it is first converted to its binary
code i-e 01000001.
Logic gates:
Logic gates are the basic building blocks of digital computer. Logic gates operates on
two voltage levels and process digital signals which represent binary digit 0 and 1.
Digital Logic and Logic gates:
Digital logic is used to create a digital circuit which consist of large number of logic
gates:
A logic gate is an elementary building block of a digital circuit. Most logic gates have
two inputs and one output. At any given moment, every terminal is in one of the two
binary conditions low (0) or high (1), represented by different voltage levels.

Basic logic gates:


AND, OR and NOT are the three basic logic gates because these three gates can be
used to implement other complex types of gates.
AND Gate:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.90

Definition:
AND gate perform the logical multiplication, commonly known as AND function.
Explanation:
The AND gate has two or more inputs and a single output. The output of AND gate is
high (1) when all its inputs are high, and if any one input is low (0) then output will be
low.
Here we have two inputs A and B, then output F can be represented mathematically
as:
F= A . B
Here (.) dot is denoted the AND operation.
Symbolically it is represented as:
A
F=A.B
B
OR Gate:
Definition:
The or gate performs logical addition, commonly known as OR function.
Explanation:
The OR gate has two or more inputs and single output. The output of OR gate is high
when any one of its input is high.
Here we have two inputs A and B, then output F can be represented mathematically
as:
F=A+B
Here (+) sign denotes OR operation.
Symbolically it is represented as:
A
F=A+B
B

OR Gate:
Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.91

Definition:
NOT Gate is used to reverse the input value. It is a gate whose input is the inverse or
compliment of the input.
Explanation:
NOT gate takes single input and produces a single output. If the input to NOT gate is
“0” then the output will be “1”. If the input is “1” then the output will be “0”. It is also
performing the logical negation. NOT gate inverts the inputs to produce the output
therefore, it is also called inverter.
Symbolically is represented as:

X F=X

Truth table:
Definition:
It is a table which contains all the possible combinations of input values and their
corresponding output values.
Explanation:
In a truth table, there is “n” input values then there will be 2n possible combinations. It
is also used to represent all possible combinations of a Boolean function or expression
or logic gate.
Boolean function/expression is the combination of Boolean variables and/or
constants linked by Boolean operators.
Properties of truth table:
 Truth table consists of rows and columns.
 It shows relationship between input to output from digital logic circuit.
 It shows output for all possible combinations of input using 0 for low and 1 for
high.
 All the combinations of inputs are listed in columns on the left and outputs is
shown in the rightmost column.
 The input columns are constructed in the order of binary counting with a
number of bits equal to the number of inputs.

Truth table for AND, OR, NOT gates:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.92

Truth table for two inputs AND gate:


Let X and Y are the two inputs and F is the output from an AND gate, then the truth
table for AND gate will be as:

X Y F=X.Y

0 0 0

0 1 0

1 0 0

1 1 1

Truth table for three inputs AND gate:


Let X and Y and Z are the two inputs and F is the output from an AND gate, then the
truth table for AND gate will be as:

X Y Z F x.y.z

0 0 0 0

0 0 1 0

0 1 0 0

0 1 1 0

1 0 0 0

1 0 1 0

1 1 0 0

1 1 1 1

Truth table for two inputs OR gate:


Let X and Y are the two inputs and F is the output from an OR gate, then the truth
table for OR gate will be as:

X Y F=X+Y

0 0 0

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.93

0 1 1

1 0 1

1 1 1

Truth table for three inputs OR gate:


Let X and Y and Z are the two inputs and F is the output from an OR gate, then the
truth table for OR gate will be as:

X Y Z F x.y.z

0 0 0 0

0 0 1 1

0 1 0 1

0 1 1 1

1 0 0 1

1 0 1 1

1 1 0 1

1 1 1 1

Truth table for NOT gate:

X F = X/

0 1

1 0

More logic gates with their truth tables:


NOR gate:
Definition:
The gate whose input is “1” when all the inputs are “0” is called NOR gate.
Explanation:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.94

NOR gate is actually the compliment or inverse of the OR gate. Therefore, it is also
called NOT(OR) gate.
If X and Y are two inputs, then F can be represented mathematically as:

Symbolically it is represented as:

Y
Truth table for NOR gate:

X Y

0 0 1

0 1 0

1 0 0

1 1 0

NAND Gate:
Definition:
The gate whose output is “0” when all the inputs are “1” is called NAND gate.
Explanation:
NAND gate is actually the compliment of the AND gate. Therefore, it is also called
NOT(AND) gate.
If X and Y are the two inputs to a NAND gate and F is its output, then symbolically it
represented as:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.95

Truth table for NAND gate:

X Y

0 0 1

0 1 1

1 0 1

1 1 0

Exclusive – OR gate (XOR):


Definition:
The gate whose output is “0” when all the inputs are either 0s or 1s is called XOR
gate.
Explanation:
XOR gate produces “0” output for the same input values, and produces “1” for
different input values.
If X and Y are the two inputs to XOR gate and F is the output, then symbolically it is
represented as:
X
Y F = (X Y) = X/Y + XY/

Truth table for XOR gate:

INPUTS OUTPUT

X Y F = (X Y) = X/Y + XY/

0 0 0

0 1 1

1 0 1

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.96

1 1 0

Exclusive NOR gate (XNOR):


Definition:
The gate whose output is “1” when all the inputs are either 0s and 1s is called XNOR
gate.
Explanation:
XNOR gat produces the output “1” for same input values, and produces “0” output for
different input values.
If X and Y are the two inputs to XNOR gate and F is the output, then symbolically it
is represented as:

X F = (X Y) = X/Y + XY/
Y

Truth table for XNOR gate:

INPUTS OUTPUT

X Y F = (X Y) = XY + X/ Y/

0 0 1

0 1 0

1 0 0

1 1 1

Creating NAND, NOR, XOR and XNOR gates using basic gates:
The NAND, NOR, XOR and XNOR gates can be easily created using AND, OR and
NOT gates.
Creating NAND and NOR gates using basic gates:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.97

The NAND gates can be easily created using an AND gate and a NOT gate as shown
below.

The NOR gate can also be created in a similar way by using an OR gate and a NOT
gate as shown below.

Creating XOR and XNOR gates using basic gates:


The XOR gate representing the function:
F = x/ y + XY/
This function consists of two terms x/ y and XY/. Two AND gates are required for
those terms and the output of these gates can be input into a single OR gate create the
XOR gate as shown below.

The XOR gate represents the function:


F = XY + x/Y/
This function consists of two terms XY and x/Y/ . the logic circuit of this gates can be
created by using two AND gates for the terms XY and x/Y/, two NOT gates to change
X to x/ Y and Y/ and a single OR gate as shown below.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.98

Conversion Boolean expression to Logic Circuit:


A Boolean variable can take value 0 or 1. For the given values of the variable, the
Boolean function can be either 0 or 1.
Consider the following Boolean function.
F=X+Y
The function F is equal to 0, if X = 0 and Y = 0. For all other combinations of X and
Y , the function will be equal to 1.
Example 1:
Conversion of Boolean function F1 = x y z/ to logic circuit.
A single AND gate required for the term x y z/. A NOT gate is also required to
convert the z into z/, before it is input to the AND gate as shown below.

Example 2:
Conversion of Boolean function F2 = X + Y/ Z to logic circuit.
To creat a logic circuit of this function, one AND gate is required for the term Y/ Z,
one Not gate to covert Y to Y/ and an OR gate to perform OR operation on the term X
and Y/ Z.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.99

Example 3:
Conversion of Boolean function F3 = XY/ + X/Z to logic circuit.

Simplification of Boolean function using Karnaugh Map:


Boolean function simplification:
Definition:
It is a process of reducing the number of terms and/or variables in a Boolean function
without effecting the final output.
Explanation:
In this process different methods are used for this purpose. Karnaugh Map (K-Map)
method was introduced by Maurice Karnaugh in 1953. It provides a simple method
for simplifying Boolean functions.
Karnaugh Map:
K-Map is a pictorial form of Boolean expression. It consists of square boxes called
cells. All the possible combinations of variables involved in a Boolean function are
written inside the cells in their respective position. A two variable K-Map contains 22
= 4 cells and three variable K-Map contain 23 = 8 cells on it.
Karnaugh map – Rules of simplification:
The K-map used the following rules for the simplification of expression by grouping
together adjacent cells containing ONEs.
 Groups may not include any cell containing a zero.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.100

 Groups may be horizontal or vertical, but not diagonal.


 Groups must contain 1 , 2 , 4, 8 or in general 2n cells.
 Each group should be as large as possible.
 Each cell containing a one must be in at least one group.
 Groups may wrap around the table. The leftmost cell in a row may be
grouped with the rightmost cell and the top cell in a column may be grouped
with the bottom cell.
Simplification of two variables Boolean function by K-map:
Example 1:
Consider the following map. The function plotted is : Z = f(A,B) = AB/ + AB.
Truth table for above Boolean function:
A B Z = f(A,B) = AB/ + AB
0 0 0
0 1 0
1 0 1
1 1 1

Now implement these values of the truth table in the following K-Map.

A A/ A
B

0 1
B
B 0 1

A
Z = f(A,B) = A

Example 2:

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.101

Consider the expression Z = f(A,B) = A/B/ + AB/ + A/B


A B Z = f(A,B) = A/B/ + AB/ +
A/ B
0 0 1
0 1 1
1 0 1
1 1 0

Now implement these values of the truth table in the following K-Map.

A A/ A
B

1 1
B
B 1 0

A/ B/
Z = f(A,B) = A/ + B/
Simplification of three variables Boolean function by K-Map:
Example 1:
Z = f(A,B,C) = A.B.C + A/. B.C + A.B.C/ + A/.B.C/
Now drawing K-Map for the expression.

A A/B/ A/ B AB AB/

0 1 1 0

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.102
B
0 1 1 0
C
C/

Z = f(A,B,C) = B
Example 2:
SEE FROM BOOK

EXERCISE
Q.1: Select the most appropriate choice.
1. when the data enters into the computer, it is converted into _______?
a. binary number system b. Decimal number system
c. Hexadecimal number system d. Octal number system
2. An electronic circuit that takes one or more input signals and produces a single
output is called______________.
a. Diagram b. Table c. Digital logic circuit d. none of these
3. the output of which gate is 1 only when all its inputs are 1?
a. AND gate b. OR gate c. NOT gate d. NAND gate
4. which gate perform the logic negation of complementation?
a. AND gate b. OR gate c. NOT gate d. XOR gate
5. the gate whose output is “1” when all the inputs are 0’s is called____?
a. NAND gate b. NOR gate c. NOT gate d. XOR gate
6. K-Map method is not used for_______________________?
a. minimizing the Boolean expression
b. representing Boolean expression diagrammatically
c. making the comparison between two variables
d. designing the digital circuit

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.103

Q.2: How data is represented in a computer, explain briefly?


See answer on page
Q.3: What are the three basic gates? Draw their circuit diagrams and truth table.
Q.4: convert the following Boolean expression to logic circuit.
f(A,B,C) = ABC + A/B/ + C/ + A/B/

ABC ABC + A/B/

A/ A/ B /
B/
C/ + A/B/
C/

Q.5: simplifying the following Boolean function using K-map method. Also draw the logic
diagram of the simplified function.
Ans: (i) F = X/Z + X/Z/

Now implement these values of the truth table in the following K-Map.

X X/ X
Z

1 0
Z/
Z 1 0

X/
Z = f(X,Z) = X/

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.104

X X/ X/ Z
Z
X/ Z + X / Z
X/ X / Z/

(ii) F = A/ B + B C/ + B/ C/
F = A/ B (C + C/) + BC/ (A + A/) + B/C/(A + A/)
F = A/ BC + A/BC/ + ABC/ + A/BC/ + A B/C/ + A/ B/C/
Now drawing K-Map for the expression.

A AB AB/ A/ B A/B/
B

0 1
C
C/ 1 1 1 1

=A/B+C/

A
B
C

(iii) F = X/Z/ + Y/Z/ + YZ/ + XYZ

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.105

X/Z/(Y + Y/) + Y/Z/(X + X/) + YZ/(X + X/) + XYZ

X /YZ/ + X /Y/ Z/+ X Y/ Z/ + X /Y/ Z/ + X Y Z/ + X /Y Z/ + XYZ

XY X/ Y XY/ X / Y/

1 0 0 O
Z
Z/
1 1 1 1

=XY+Z/

Logic Diagram :
X XY
Y
Z

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.106

CHAPTER #.07 WORLD WIDE WEB & HTML


Question : Define and explain word wide web ?
Ans : Word Wide Web & HTML :
Definition :“it is an information system on the internet server that support formatted,
documents (web page) interlink by hyperlinks and access by any one through internet ”
Invention : www was invented by an English scientist Time Berner Lee in 1989.
Explanation :World wide web is also known as web. The web is made up of web server
which are computer that store documents (web page) which can be access through internet
by anyone documents on the internet are created markup language like HTML (Hyper text
markup language).
Question : Define web page?
Ans :Web page :
Definition :“ A web page is document on the internet that can be access through a web
browser ”
Explanation :Every web page have a unique web address. Web address is also known as
uniform resource locator (URL). A web page may contain text, image , audio , video clips
etc.
Web page are displayed through web browser. As the user went to display a specific web
page then he/she will write web address of that specific web page at the address bar.
Question : Define website?
Ans :Website:
Definition :“ A location connected to the internet that maintain one or more web pages ”
Explanation :A web site is a collection of related web pages. A website is specified by a
specific web address (URL) and accessible through that web address. Website is loaded by
web browser .
Question : Define web browser ?
Answer : WEB BROWSER
Definition#.01 :“ It is a software which is used to open/load website ”
Definition#.02: “ A software that enable a user to retrieve information on the web ”
Explanation :
Information on the internet/web can be access by URLs as each website. Web page having a
specific address (URL) .

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.107

All the web browser have graphical user interface which enable user to open multiple
websites at the same [Link] that web browser is very easy to learn and use.
Example:
 Internet Explorer
 Google Chrome
 Opera mini
 UC browser
Question : Define web server ?
Ans :Web Server :
Definition :“ A web server are computer that facilitate and deliver web pages from the
various websites that have ”
OR
“ Web server is computer that runs websites ”
Explanation :A web server is any internet server that respond to any http request and deliver
web page files etc. The web server includes hardware , software, protocol and contents.
Every web server has an IP address.
Question : Define URL ?
Ans :Uniform Resource Locator (URL) :URL is also called web address. It is an address of
a web page on the web/ internet. As each webpage has a unique address called web address
or URL. when want to create display/load a website. We must write the URL of that website
in the address bar of web browser.
Format :
URL have the following format
Protocol : / / Domain name / other information
Example :The URL of Mardan education board is http : / / [Link] / information
Where http (hyper text transfer protocol) is the protocol which specify how communication
will take place bisem is the domain name further web page is specified after domain name
As http : // [Link] /main / result will display the result page.
Question : Define and explain search engine ?
Ans :Search Engine :
Definition :“A search engine is a web site that allow user to find information on the World
Wide Web

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.108

Explanation : Search engine have been designed to help users in finding information on the
web. Users simply write a text word or sentence in a search engine then the search engine
looks for matching websites for all over the world on the web. The users open a website
according to his/her well or need by just clicking on displayed website. Finding or getting a
specific kind of information within millions of web pages on the web is difficult or
impossible task. But search engine have been solved this problem.
Example : Google is a best example of search engine which is commonly in use today.

Question : Define Home page?


Ans :Home Page : Home page is a main or very first page of a website that opens in a
browser when users access it.
Example :Home page of university of Peshawer website, [Link]
Question : Define web Hosting ?
Ans :Web Hosting :
Definition :“ The activity or business of providing storage space and access for website ”
OR
“ Web hosting is a service , providing by web hosting companies to upload website on web
server and make them available for computer (Internet) users ”
Explanation :Computer users first design web page on their computer and then test that web
page in order to check either it working properly or not. After testing the web page these
web pages are uploaded on a web server to make them available for other users. Uploading
of web hosting companies these companies make the websites running on computer which
are connected to the internet all the time web hosting companies provide 24 hours support
and online control for managing the website.
Types of Websites: There are many different types of websites and each provide particular
type of service. some are as following.
Web Portals: Those type of websites that offer different types Of services.
Explanation: Web portals provide many facilities to the user which include news, email,
online shopping malls etc. .it function as a point of access to information on the web.
Example: A school web portal delivers information about the school background, facilities,
admissions etc.
News Websites: News websites provide information about current
Events and opinions.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.109

Explanation:These web sites publish new stories and let their visitors voice be heard. these
web sites provide their visitors a way to get their thoughts and views publish. very often at
the end of news stories, visitors are asked to share their experience or knowledge about the
topic.
Example:News websites like [Link]/ ,[Link]
,[Link] etc. .
Information websites: The web sites which provide information on any topic
In the form of text, videos and graphics etc.
Example: [Link] informational websites gives information on large
scale which include animals ,business, health ,education etc. .
Educational websites: those websites which are design for educational purposes
Explanation:These sites contain animation, slide presentation and tutorials to educate
people on various topic. information is presented in a well-organized way. its purpose is to
impart knowledge to people who r looking for better education.
Example: [Link] ,[Link] etc…
Personal websites:Those websites created for personal use which contain. There
information, hobbies, friends etc. Personal websites contain the information about that
person. its purpose is to share the personal information with family members and friends.
personal websites are also open for public and anybody can visit and leave comments.
Business Websites:These sites provide facilities to maintain business relationship and
selling information, services and commodities via internet .it give facilities to exchange the
business documents, such an orders or invoices b/w suppliers and customers. services
provide by business sites include banking, ticket, stock market transactions and even remote
education.
Entertainment Websites: It provides different types of entertainments to computer [Link]
include sport, radio, computer, games, fashion etc.
Write note on HTML?
INTRODUCTION TO HTML: HTML stand for hypertext markup language. it is a kind
of language which contain a series of special codes. they define the style that should be used,
when displaying the text and also allow the links to other documents .it is use to create
webpages. It is the language of WWW. Its codes are written using HTML tags. The tags are
special control character which are enclosed with in angle brackets (“< >”). Tags are
instruction tells your browser what to show on the web page .HTML files are plain text files
so they can be created by using single editor i – e: notepad, world pad etc.
Q:How an HTML document can be created and displayed
CREATING AND DISPLING HTML DOCUMENT; Note pad ++ is used for creating
HTML documents. it can be download from internet.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.110

Creating the first HTML document: Following are some steps to create a document in
HTML 1) Open the NOTEPAD ++ program and type the text.
2)now save your HTML document, open file menu and select save As …… and give file
name with the extension of .html.
Displaying the HTML document (web page):To open your document in browser window,
go to location where u save it. double click to open it. the browser window will be displayed.
Q:Describe basic tags used in HTML code.
Tags used to MARK – UP HTML, Element:

HTML Head and Body Tags: Following are the tags used for mark-up HTML element in
the document.
<html></html> Tags: The first one <html> use for the start of HTML document. and the
</html> indicates the end of document.
<head>, </head>Tags: It is use to give title to the webpage.
<body></body> tags: Any type of data inside the body will be display on browser
If any change is required, it can change easily by opening it.
Q:How text can be formatted while displaying on web using html?
TEXT FORMATTING: It is related to the appearance of the text in a web i-e size, color,
style
Basic of Text Formatting: Following are the basics of text formatting
Specifying a Page Title: The “<title></title>” tags are used to specify page title. The text
b/w them is use to set the title to the page which is displayed on the title bar on the web
browser.
Example:<title> THE SCHOOL<title>. It will be display the text THE SCHOOL.
Creating a Paragraph; The <p></p> is use to define the paragraph. HTML automatically
adds an extra blank line before and after a paragraph.
Inserting Line Breaks:The <b> is line break tag. it is use to end a line wherever it is placed
and it does not have a closing tag.
Inserting Space: Space is needed in HTML documents. if a user insert more than one space
anywhere in the document, the browser will show only one space, rest of the space will be
truncated, if user wants to have many space in a HTML document then the &nbsp character
entity must be used.
Adding headings /Sub-Heading: There are 6 tags, <h1></h1> to <h6></h6>. the<h1> is
used to specify the largest heading and <h6 > tags specify the smallest.
Q: Describe text formatting tags and their use?

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.111

TEXT FORMATTING TAGS AND THEIR USE:TAXT FORMATTING tags are used to
format the text. some commonly used text formatting tags are described below.
Bold <b></b>: These tags use to make the text bold in a web browser.
Example: <b> NEWS</b>.
Result:It will show as NEWS.
Underline <u></u>: These are used to underline the text with in a tags.
Example: <u>important </u>
Result: important

Italic <I></i>: These tags are used to make the text italic
Example: <i> Pakistan Zindabad </i>
Result: Pakistan Zindabad.
Superscript <sup></sup>: It is use to give the power to the integer.
Example: X<sup>y</sup>
Result: XY
Subscript <sub></sub>: Use to convert the text to subscript that with in the tags.
Example: x<sub>7</sub>
Result: X5
Font size <font size=? ></font>: These tags are used to change the size of the text. Replace
the symbol of? with the range of to 7. Is small and 7 is largest font size.
Example: <font size =4>THE EXAM</font>
Result: THE EXAM.
FONT color<font color =?></font>: These are used to change the color of the font.
Replace the symbol of? By blue, black, yellow, pink etc.
Example: <font color =black > CLASS ROOM </font>.
Result: CLASS ROOM.
Font face <font face=?></font>: These tags are used to change the font face of text that is
within the tags. replace? Symbol by aril, courier, caliber etc.
Example: <font face =French script >the best teacher </font>

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.112

Result: the best teacher


How a listed data/text can be displayed at webpage using html?
CREATING LIST IN HTML:
Lists are very important in web pages .HTML provides various methods for specifying lists.
Types of LIST: There are four types od list which is use in HTML pages. They are given
below
Unordered list: In this list each item starts with a bullet. unordered means that the list item
don’t have numbering.” <ul></ul>” tags are used for listing and each item is
surrounded by<li></li> tags.
Ordered list: In ordered list all items of the list are started with numbers which are in
ascending order.” <ol></ol>” tags are used to create ordered list and it is also
surrounded by” <li></li>” tags.
Definition list: It is use to define the terms .it is not a list of item .it is a list of terms with
their explanation.
<dl></dl>: it is use to define a definition list.
<dt></dt: use to define each item of definition list
<dd></dd>: use to explain each term of definition list.
Nested list:
Its means alit within a list. we can create a nested list with in another u ordered
list. any combination of ordered or unordered list it can be used or can be created
Creating list:

NOTE:
for creating list see pg211
to217.

IMAGS AND BACKGROUNDS: As reading of text a lot of time so images is impotent to


learn and understand easily. images have great value in a webpage.
Q:How image is added to webpage ?

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.113

Adding image in web page: The image tags, <img> with src attribute is use to displaying
image in a web pages. IMAGE is not a part of HTML it is saved in computer
memory.
<img> tags: HTML can insert image in a web page. it has an attributes but not closing tags.
Src attribute: It stands for source. it tells the browser where the image is located. it has
many attributes but src is most important one.
Adding border in an image: Border is the box of line around the image boundary .it can be
set around an image by using its border attribute in the <img> tag its attribute is as following
<img src =” image jpg” border=4>
The no 4 specifies the width of the border in pixels. The browser will display the image with
border.
Specifying image size in a webpage: User can resize the image in a web page by using
height, width, alt attributes in the<img>tag.
Height attribute:
It is use to inserted in the <img> tag to specify the height of the image in pixels. this can be
different then the real. the browser will resize the pic as it is specified.
Width attribute: It is use to inserted the width of the image in <img> Tag. it can be
different from the real [Link] browser will resize the image as specified.
Alt attribute: If for some reasons the browser Can be displayed the image. the user can
insert the alt attribute in the <img> tag to tell reader what image is missing in the
page. the value of the alt attribute provides alternative text in place of image in web
page.
Q:How background and foreground color can be added to webpage:
Applying background and foreground color: To apply a background in a page, insert
bgcolor attribute and for foreground insert text in the<body> tag.
Applying background image: An image can be set as a background of the page by using
background attribute in the <body> tag
<body background=” [Link]”>
If the image is smaller than the web page than it will be repeated till it doesn’t cover the
page.
What is meant by hyperlink which tags are used for hyperlink in html?
HYPERLINKS: The entire WWW is connected by hyperlinks. a web page contains many
hyperlinks and each sends the user to a related webpage or picture/file.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.114

Hyperlink: A hyperlink is a text or image in a web page that links it to other webpage or
another section.
Explanation: It creates a link between text or image. it usually in blue color and underline.
When the reader moves the pointer over any hyperlink the pointer changes to a small hand.
clicking on it allows the reader to jump from page to page.
Anchor tag:
The <a></a> tag is known as anchor. It is used to create a hyperlink which
may be text or image, with the href attribute.
Creating a hyperlink to a webpage:
Anchor with a name attribute is used to create a hyperlink within a web page.
Steps:
It involves two steps to creating the anchor itself and then creating a hyperlink to the anchor
Creating the anchor: create the label in the anchor tag at all location in the web page where
you want hyperlink.
Syntax: <a href =#” label”> text to be displayed</a>
Note:
The# symbol must be put before the label,
Creating a graphical hyperlink:
To create a graphical in web page the syntax should be followed
<a href =”url” ><img src=”name of image file></a>
Example:
<a href =” http:[Link]><img src=” image .jpg”></a>

It will display the [Link] file browser window. When the readers move
the mouse pointer over the image, it will change to small hand and clicking on the image will
open the Federal Board website.
Q:Describe the method by which a table can be created at webpage using HTML.
CREATING TABLES:
Tables are also used in web page to present info in an organized member which
is easy to read and understand by the reader or user.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.115

A table consist of row and columns. some tags are used to create a table in browser which
are as following.
<table></table>:
These tags are use to create a table.
<tr></tr>: these tags define a row.
<td></td>: it defines column. column of every row is called Data cell and it can contain
image text, paragraph. Etc…
<th></th>: it is use for table heading.
Cells spacing: it is use to make space between the cells.
cell padding : it is use to make space between data and border.
Attributes use in creating table:
Following are the attributes use to create table.

Colspan attribute: use to combine the cells.


Rowspon attribute: use to combine the rows of the [Link] will also specify the number of
rows a cell should span.
Align attribute: it is use to centers the title in the column of the table. Title can be at left or
right.
Valign attribute: use to change the position of cells i-e: top, bottom, left, right .
Nowrap attribute: it is a Boolean tag. when it is present then the text inside the cell it will
be not wrap.
Note: .
for more info and example plzzz check the page #234
to238 .

How a frames can be created on webpage using html


CREATING FRAMES:
frames are commonly used in web pages to present HTML
document.
in multiple views. Frames allow to display info in an organized manner within a web page.

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.116

Frames: it is a small rectangular window or pane within a browser window. It also allows
user to display more than one HTML document in a one or same browser window. Each
farm is independent of the other. The <frame> tag is use to place HTML document in a
frame.
Frameset: it defines how to divide the browser window into frames.
the<frameset></frameset> tag are used to achieve this. The user can divide the browser
window into vertical or horizontal frame
Creating a frameset:
The <frameset></frameset> and <farm> tags are use together to create farms in
browser window.
<frameset></frameset>: this tag defines either the series of row or columns.
Two attributes: it has two attributes.
1-cols attribute: it defines series of columns.
2-Rows attribute: it defines the series of rows.
Syntax: both have same syntax
<frameset row=?>
<frameset cols=?>
Where the symbol? Is replace by 30%, 40%, etc.
Example:
For columns: <frameset cols = 50%,70%>
The tag will divide the browser into 2 columns the first one will be of 50% of width of
browser window and the second one will be of 70%. It will create 2 vertical frames.
For rows: similarly <frameset rows=50%,70%>
The tag will be divide the browser window into two equal – size rows that is the browser
window will divide into equal- size horizontal frames.
Exercise
Q1 select the most appropriate answer.
1 internet address which identifies a website is called
URL
2 A collection of webpages hosted on a web server is called?
Website

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad
PAGE#.117

3 which language is used for creating web pages?


HTML
4 Text or image in a web page that links it to another web page is called?
Hyperlink
5 which of the following refers to the uploading of webpages to sebserver so that others can
access it?
Web hosting
Q3 html tags for the the following

1 <p></p>
2 <h1><h2><h3>….<h6>
3 <b></b>
4 <u></u>
5 <i></i>
6 <center></center>
7 <sup></sup>
8 <sub></sub>
9 <font size=?></font>, <font color=?></font>,<font face=?></font>,

Thanks….
Reviewed by Sir Haris (MS/MPHILL Computer Science)
work as a lecturer at The Peace College Abbottabad

Reviewed by Hafiz Haris MS/MPhil CS, LECTURER at THE PEACE GROUP OF SCHOOLS AND
COLLEGES Abbottabad

You might also like