0% found this document useful (0 votes)
2K views312 pages

A Textbook On Computer Science-Grade 12: Asia's

Uploaded by

Binayak chhetri
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)
2K views312 pages

A Textbook On Computer Science-Grade 12: Asia's

Uploaded by

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

Approved by Government of Nepal, Ministry of Education, Science and Technology, Curriculum Development

Centre, Sanothimi, Bhaktapur as an Additional Learning Material.

Asia’s

A Textbook on Computer Science-Grade 12


Author
Anil Pradhan

Published By
ASIA PUBLICATIONS PVT. LTD.
Publisher ASIA PUBLICATIONS PVT. LTD.
Basundhara-3, Kathmandu, Nepal
Plus code: p8rm+7j Kathmandu
Tel:- +977-01-5903919, 5903915, 5903916
Email:- [email protected]

Author ANIL PRADHAN

Edition FIRST : 2078 BS


© Publication
No part of this book may be
reproduced or transmitted ISBN 978-9937-576-92-5
by any means (electronic,
photocopying, recording,
or otherwise) without prior © Asia Publications Pvt. Ltd.
written permission from the
author. Any breach of this Price : Rs 395/-
condition will entail legal Layout and Design
action and prosecution.

Printed in Nepal
Laiepate Marg, Dumbarai, Kathmandu, Nepal
Tel: 01-4433840
Computer technology is undergoing rapid change, and new and improved technological
advances appear almost daily. Computer technology has touched every part of our lives. It has
made a significant impact in teaching and learning in our schools. Because of the significance of
computers in today’s world, it is important to be computer literate.
Start Up Computing-A Textbook on Computer Science-Book 12 is one of a series on computer
science designed for all the categories of students of Nepal. The book 12 of this series is
recommended for use in class 12.
The purpose of this book is to acquaint the students with the fundamental concepts, application
and programming aspects of computing. The material is presented in a conceptual and
application-oriented manner. It has been prepared to sharp focus creativity and encourage
young children to explore and experiment with learning opportunities. The special features
of this edition which highlights the important points covered in each chapter are given below:
The special features of this edition which highlights the important points covered in each
chapter are given below:
a. The material is presented in a conceptual and application-oriented manner.
b. Get More Info includes knowledge that take the students beyond their classroom.
c. Connect provides additional information to enhance knowledge of the students.
d. Tech Terms provides a glossary of important terms at the end of each chapter.
e. Concepts Review has been given at the end of each chapter for a quick recapitulation of
all the topics in that chapter.
f. Each chapter has a set of exercises which will test their understanding of the topic.
g. Evaluate consists of extensive exercises including HOTS (Higher Order Thinking Skills)
questions and practical questions to assess the knowledge of the concepts learnt
h. In the Lab provides hands-on exercises based on the concept taught
While a lot of care has been taken in ensuring the preparation of a conceptually accurate and
error free book, the room for improvement is forever present. The author would be thankful
for any suggestions for improvement.
Author
Contents
1. Database Management System 9
Data and Information
Electronic Database
Tables : The building blocks of database
Files - The Traditional Approach
Database Management System
Types of Database Structures or Data Models
Entity-Relationship Database Model
Relationship between Tables
Schema and Instances
DBMS Keys
Data Normalization
Normal Forms
Denormoralization of Data
Centralized Vs. Distributed Database
Data Security
Database Administrator
Structured Query Language
Installing MySQL on Microsoft Windows
General Format of SQL statement
SQL CREATE TABLE Statement
SQL DROP TABLE Statement
SQL ALTER TABLE Statement
SQL SELECT Statement
SQL INSERT Statement
SQL UPDATE Query
MySQL DELETE Statement

2. Communications and Networking 42


Communications and Networking
Communication and Basic Elements of a Communication System
Data Communication
Computer Network
Data Transmission
Modulation
Transmission Modes
Computer Network Models
Computer Network Categories
Physical Topologies for LAN
Communication Media
Transmission Impairments Terminology
Networking Terminology
Networking Tools
Network Connectivity Devices
OSI (Open System Interconnection) Model
Internet Protocol Addressing

3. Web Technology 72
The Internet
Uses of the Interne
History of Internet
How the Internet works?
Client Side Scripting and Server Side Scripting
Introduction to JavaScript
JavaScript Data Types
JavaScript Variable
JavaScript Operators
Control Structure
Switch case
Creating Sample Program
Object Definition
Object Properties
Object Methods
Do Not Declare Strings, Numbers, and Booleans as Objects!
JavaScript Events
What can JavaScript Do?
JavaScript Form Validation
JavaScript Can Validate Numeric Input
Automatic HTML Form Validation
Data Validation
HTML Constraint Validation
Constraint Validation HTML Input Attributes
Constraint Validation CSS Pseudo Selectors
What is jQuery?
Why jQuery?
jQuery Syntax
What is PHP
Why use PHP
PHP Features
Web Development
How to run PHP code in XAMPP
PHP Case Sensitivity
PHP Data Types
PHP Variables
PHP Operators
MySQL Connection Using PHP Script
Creating Tables from Command Prompt
Creating Tables Using PHP Script
Select Data With MySQLi

4. Programming in C-Language 135


Definition and Features of C-Program
Structure of C-Program
Compile and Execute C Program
C Preprocessor
Header Files and their Purpose
Fundamentals of C-Program
Data Types
Escape Sequence in C
Types of Specifier
Statement
Operators
Rules of logical operators
Conditional operator
Comma operator
The Sizeof operator
Precedence and Associativity
Expressions
Type Casting and Conversion
Introduction to Library Functions
Functions in C-Language
Advantages of Functions
Need for user-defined function
Using Functions
Arguments Passed by Value
Arguments Passed by Reference
Return Statement
Types of User-Defined Functions
Recursive Function
Arrays and Functions
C Programming Storage Class
Structure and Union in C-Language
Structure in C
Important Points for Structure
How to initialize data to structure elements
Memory Consumption of Structure
Nested Structure in C
Structure and Array
Passing Structure to Function
Union in C
Differences between Structure and Union
Pointers in C-Language
How to get the value of an address?
Declaration of Pointer variable
Initialization of pointer
Uses of Pointer
Manipulation of Pointers Value
Pointers with Array
Pointer with Character Array

5. Object Oriented Programming 235
Programming Paradigms
Concept
Features of OOP
Advantages of OOP
Disadvantages of OOP
Basic Elements of OOP
Applications of using OOP
Difference between structured programming and object oriented programming

6. Software Process Model 244


System Analyst
Role of a Good System Analyst
System Engineers
System Development Life Cycle
Importance and Necessity of System Development Life Cycle
System Development Model
Spiral Model
Prototyping Model
System Development Phases
Implementation
Concept of Requirements Gathering
Concept of System Design Tools
Entity-Relationship Diagram
Algorithm
Flowchart
Pseudocode
Decision Table
Decision Tree
CASE Tools
Documentation
Software and Quality

7. Recent Trends in Technology 274


Artificial Intelligence
Components of Artificial Intelligence
Uses of Artificial Intelligence
Ethical Aspect of AI
Robotics
Cloud Computing
Characteristics of Cloud Computing
Big Data
e-Business
e-Commerce
Types of e-Commerce system
Differences between e-Business and e-Commerce
e-Government
Goals of e-Government
Types of e-Government services
e-Medicine
Virutal Reality
Mobile Computing
Internet of Things (IoT)

Project Work 293


Telecom Billing Management System in C with source code 294
Past Question Papers 301
Chapter Database
1 Management
System

Concept
Every organization maintains data pertaining to its business, activities, employees and
other related information. For example, the database of a particular school (institution)
contains data about its students, their academic and co-curricular achievements, details of
teachers and other administrative staff, etc. Similarly, the database of a library will contain
data about all its books employees, members and about its various other activities. This
data needs to be maintained in such a manner that it can be readily available and can be
presented easily in desired formats. The data also needs to be updated regularly. Earlier
this was done manually by maintaining records in various files. However, in this one
problem arose, i.e., if an information was to be updated, it had to be done separately in
all the related files. Therefore, the need arose for having such a data collection system
where control of information was centralized. This led to the designing of databases.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 9


Data and Information
Data is the plural form of the word “datum” which refers to a collection of raw facts. Data are
the raw materials of information processing. Once manipulated and processed according to
certain requirements, they form a desired output which serves some purpose. These resultant
facts are known as information. Information is the most critical resource of the organization.
Data becomes information when you understand what it means.
Data (for computers) with structure Information (for people)
Processing is a series of actions or operations that converts some input into useful output.
Hence, data processing is defined as the processing of data to make it more usable and
meaningful, thus transforming it into information. It consists of three sub-activities - capturing
the input data, manipulating the data, and producing the output results.

Data Processing Information

Electronic Database
Electronic database refers to an organized collection of data stored on a computer in such a
way that its contents (data) can easily be accessed, updated and queried upon with the help of
a software program. It maintains any information that may be necessary to the decision-making
processes involved in the management of that organization. The advantage of electronic
database is the limitless capacity to store data, and speed, accuracy and efficiency with which
you can retrieve information.

Tables : the building blocks of database


The table is the basic element of the database. Table is a set of information about a particular
subject (for example, a table could have information on all the departments of a company). Table
has records in it, each related to the subject of the table (for example, a record could have
information about an employee of the company). Each record is made up of fields, which
contain specific information about the thing the record represents (for example, each record in
the table that contains information about employee of the company would have fields for things
like Employee Number, First name, Last name, Address, etc.).

Fields
Employee Master Table
Emp No Dept No. Address
Records E01 D01 New Road
E02 D02 Prithivi Chowk
E03 D03 Surket Road

10 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Files - The Traditional Approach
Traditionally, data files were developed and maintained separately for individual applications.
Thus, the file processing system relied on the piecemeal approach of data across the
organization where every functional unit like marketing, finance, production, etc., used to
maintain their own set of application programs and data files. No doubt such an organization
was simple to operate and had better local control but the data of the organization got
dispersed throughout the functional sub-systems. This approach was rendered inadequate,
especially when organizations started developing organization-wide integrated applications.
The major drawbacks of file processing system may be outlined due to the following reasons.
a. Data Duplication
Since each application has its own data file, the same data may have to be recorded and
stored in several files.

b. Data Inconsistency
Data duplication leads to data inconsistency especially when data is to be updated. Data
inconsistency occurs because the same data items which appear in more than one file do
not get updated simultaneously in all the data files.

c. Lack of Data Integration


Because of independent data files, users face difficulty in getting information on any ad hoc
query that requires accessing data stored in more than one file. Thus, either complicated
programs have to be developed to retrieve data from each independent data file or
users have to manually collect the required information from various outputs of separate
applications.

d. Data Dependence
The applications in file processing systems are data dependent, i.e. the file organisation,
its physical location and retrieval from the storage media are dictated by the needs of the
particular application.

e. Program Dependence
The reports produced by the file processing system are program dependent, which
implies that if any change in the format or structure of data and records in the file is to be
made, a corresponding change in the programs have to be made. Similarly, if any new
report is to be produced, a new program will have to be developed.

a. What is electronic database?


b. What are the limitations of file processing system?

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 11


Database Management System
Database Management System helps maintain a centralized control over the data. It involves
creating, modifying, deleting, and adding data in files. The software that allows to perform
these functions is known as Database Management System (DBMS) software. Some popular
DBMS software are Microsoft Access, Microsoft SQL Server and Oracle.
Database Management System can thus be defined as a collection of programs that enables
you to store, modify, and extract information from a database.

How Database Management System Works?


DBMS provides a centralized control over data - A database system maintains a centralized
database, i.e. all the data is kept at one place and any application that requires the data can
access it from this central location. Any application can share data from the central location.
Though sometimes it may be necessary to duplicate the data i.e. maintain multiple copies of
the data, the redundancy can be controlled as the DBMS is aware of the multiple copies and
updates them regularly.

USER

Data File
USER
Data File

Application Data File


Prog-1

DBMS
Application
Prog-1

Advantages of DBMS
A computerized Database Management System offers several advantages over the conventional
filing systems. Some of these advantages are as follows:

Provides an organized way of storing data


The Database Management System allows you to store, retrieve and process a collection of
data in a central database file. It eliminates the need of using different files for the storage of
data.

12 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Facilitates quick and efficient retrieval of information
The main task of the Database Management System is to provide the correct information in
the required format as and when required. One can use a query to extract the required data
from the database.

Reduces data redundancy


In a conventional filing system, two or more files may store the same piece of data. This leads
to data duplication or data redundancy, resulting in an inefficient use of memory space.
In a DBMS, all the data is kept at one central location. The centralization of data ensures that
no unnecessary duplication of data takes place. This leads to reduction in the total amount of
data, and a better and more efficient use of memory space.

Improves the consistency of data


Data consistency refers to the lack of contradiction in the data. Since all the data in a database
is kept at one central location, any changes made to a particular data item are immediately
reflected across the whole database. This reduces the chances of data being changed in one
file and remaining unchanged in some other file. Thus, improving the overall consistency of
data.

Allows sharing of data


The sharing of data means that the same data can be shared by many users or application
programs. Each user may have access to the same data, which may be used for different
purpose by different users.

Disadvantages of a Database
In contrast to the many advantages of the database approach, there are a few disadvantages as
well. The disadvantages of a database of a database approach are given below.

Centralised database
The data structure may become quite complex because of the centralized database supporting
many applications in an organization. This may lead to difficulties in its management and may
require a professional/an experienced database designer and sometimes extensive training for
users.

More disk space


Database approach generally requires more processing than file management system and,
thus, needs more disk space for program storage.

System operation
Since the database is used by many users in the organization, any failure in it, whether due to
a system fault, database corruption, etc. will affect the system operation as it would render all
users unable to access the database.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 13


Security risk
Being a centralized database, it is more prone to security disasters. Besides the above-
mentioned disadvantages, sometimes the database approach may not be cost-effective for
smaller organizations. This is because of the reason that as with other complex software
systems, the cost in terms of software, hardware and operating/administrative personnel also
increases.

Cost of data conversion


When a computer file-based system is replaced with a database system, the data stored into
data file must be converted to database file. It is very difficult and costly method to convert
data of data files into database. You have to hire database and system designers along with
application programmers. Alternatively, you have to take the services of some software house.
So a lot of money has to be paid for developing software.

Cost of hardware and software


A processor with high speed of data processing and memory of large size is required to run the
DBMS software. It means that you have to upgrade the hardware used for file-based system.
Similarly, DBMS software is also very costly.

Disadvantages of DBMS
Some of the disadvantages of DBMS are as follows:
a. The design of the database system is complex, difficult and is very time consuming task to
perform.
b. Huge amount of investment is needed to setup the required hardware and the software
needed to run those applications.
c. Database systems require sophisticated hardware and software and highly skilled
personnel.
d. The cost of DBMS varies significantly, depending on the environment and functionality
provided. There is also the recurrent annual maintenance cost.
e. The disk storage requirements for the DBMS and the database may necessitate the
purchase of additional storage space. The procurement of additional hardware results in
further expenditure.

Objectives of DBMS
The objectives that the management should keep in mind when they design and organize their
data base management systems are to:
a. Provide for mass storage of relevant data
b. Make access to the data easy for the user
c. Provide prompt response to user requests for data

14 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Understanding Database Terminology

Field
A database field is a set of data values, of the same data type, in a table. It is also referred to as
a column or an attribute. Fields are organized into records, which contain all the information
within the table relevant to a specific entity.
A simple example is a table that saves employee’s job record. The fields in this table could be
the following: Employee ID, Last Name, First Name, Position, and Department.
Employee ID Last Name First Name Position Department
101 Rai Punam Director Human Resources

102 Khan Raju Manager Human Resources

103 Acharya Ramu Assistant Human Resources

104 Shrestha Susmita Accountant Financial Resources

105 Chettri Retika Supervisor Financial Resources


Record
A database record refers to a collection of fields about the same person/item/object. A database
record can be thought of as a row of information within a database table. In the phone book
example, each last name begins a record/row which contains data in the name, address and
phone number fields. A record is often used in a database search because each record has a
unique, identifying quality (or value). A database record is, basically, a row that contains unique
data in each of the fields. A database will usually contain a large number of records but only a
small number of fields.
Raju Khan’s database record is highlighted. There are three records in this database table.

Employee ID Last Name First Name Position Department


101 Rai Punam Director Human Resources

102 Khan Raju Manager Human Resources


103 Acharya Ramu Assistant Human Resources

104 Shrestha Susmita Accountant Financial Resources

105 Chettri Retika Supervisor Financial Resources

Object
A database object is any defined object in a database that is used to store or reference data.
The most common object that people interact with is the table. Other objects are indexes,
stored procedures, sequences, views and many more.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 15


Types of Database Structures or Data Models
Generally, database systems are classified on the basis of one of the three data models they use
in building the conceptual structure or schema of the database. The three models are:
(i) Hierarchical model
(ii) Network model
(iii) Relational model
Let us briefly discuss these database structures.

Hierarchical Model
In the hierarchical structure, the relationships between records are stored in the form of a
hierarchy or a tree which has a root. In this model, all records are dependent and arranged
in a multi-level structure, thus the root may have a number of branches and each branch may
have a number of sub-branches and so on. The lowermost record is known as the ‘child’ of
the next higher level record, whereas the higher level record is called the ‘parent’ of its child
records. Thus in this approach, all the relationships among records are one-to many.

NCC

Science Humanities Management

Chemistry Physics Biology


Advantages of Hierarchical Model
1. Easy to understand.
2. These database system can enforce varying degree of security feature.
3. Because of its inherent parent-child structure, database integrity is highly promoted in
these systems.
4. It supports one-to-one and one-to-many relationship.

a. What is Database Management System? What are the advantages and disadvantages of
DBMS?
b. What are the objectives of Database Management System.

16 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Disadvantages of Hierarchical Model
1. Difficult to access values at lower level.
2. This model may not be flexible to accommodate the dynamic needs of an organization.
3. Deletion of parent node result in deletion of child node forcefully.
4. It increases redundancy because same data has to be repeated in different places.

Network Database Model


A network database model is a database model that allows multiple records to be linked to
the same owner file. The model can be seen as an upside down tree where the branches are
the member information linked to the owner, which is the bottom of the tree. The multiple
linkages which this information allows the network database model to be very flexible. In
addition, the relationship that the information has in the network database model is defined as
many-to-many relationship because one owner file can be linked to many member files and
vice versa.

NCC

Science Examination Library

Faculties Books Students

Advantages of Network Database Model


1. It has many to many relationship, network database model can easily be accessed in any
table record in the database
2. For more complex data, it is easier to use because of the multiple relationship founded
among its data
3. Easier to navigate and search for information because of its flexibility

Disadvantages of Network Database Model


1. Difficult for first time users
2. Difficulties with alterations of the database because when information entered can alter
the entire database

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 17


Differences between Hierarchical Model and Network Database Model
Hierarchical Model Network Database Model
One-to-Many relationship Many-to-Many relationship
Difficult to navigate because of its strict owner Easily accessed because of the linkage
to member connection between the information
Less flexibility with the collection of Great flexibility among the information files
information because of the hierarchical because the multiple relationships among the files
position of the files
Relational Database Model
The relational database model was promoted by E.F. Codd and has been acknowledged as a
very important concept in database management system. The relational model relieves the
user from details of storage structures and access methods. It is also conceptually simple and
based on sound theoretical principles that provide formal tools to tackle problems arising in
database design and maintenance.
Relational database model manages data in more than one file at a time and these files are
treated as tables with rows and columns rather than lists of records. The column of each table
represents a data base field and each row a data base record, which is also called tuple. A
relational database management system can relate the data of one table to the data of another
table through the use of a common field.

Advantages of Relational Database Model


1. Since one table is linked to the other tables with some common fields, rules implemented
on one table can easily be implemented to another table.
2. Referential integrity can be easily implemented.
3. The database has very less data redundancy.
4. Normalization of the database possible.
5. Rapid database processing and searching is possible.

Disadvantages of Relational Database Model


1. It is more complex than other models due to relationship (link) with other tables.
2. Too many rules make the database not very user-friendly.

a. Explain the different types of data models.


b. Differentiate between Hierarchical Model and Network Database Model.
c. What is a Relational Database Model? List any three advantages of Relational Database
Model.

18 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Entity-Relationship database model
An Entity-Relationship model (ER model) describes the structure of a database with the help
of a diagram, which is known as Entity Relationship Diagram (ER Diagram). An ER diagram
efficiently shows the relationships between various entities stored in a database. An ER model
is a design or blueprint of a database that can later be implemented as a database.
An E-R diagram has following features:
a. E-R diagrams are used to represent E-R model in a database, which makes them easy to
be converted into relations (tables).
b. E-R diagrams provide the purpose of real-world modeling of objects which makes them
intently useful.
c. E-R diagrams require no technical knowledge and no hardware support.
d. These diagrams are very easy to understand and easy to create even by a naive user.
e. It gives a standard solution of visualizing the data logically.
The main components of E-R model are:
Entity
Entity is any real-world object can be represented as an entity about
which data can be stored in a database. All the real world objects like
a book, an organization, a product, a car or a person are the examples
of an entity. Any living or non-living objects can be represented by an
entity. An entity is symbolically represented by a rectangle enclosing its
name.

Attribute
Each entity has a set of properties. These properties of each entity are
termed as attributes. For example, a car entity would be described by
attributes such as price, registration number, model number, color etc.
Attributes are indicated by ovals in an E-R diagram.

Link
The flow of information is indicated by the links in E-R diagram. It is
simply a line. It is a connector of entities, attributes and relationship.

Relationship
The logical association among entities is called relationship. A
relationship is represented by diamond shape in ER diagram, it shows
the relationship among entities. Relationships are mapped with entities
in various ways. Mapping cardinalities define the number of association
between two entities. For example,
a. An employee assigned a project.
b. Teacher teaches a student.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 19
Relationship between Tables
A relationship plays a very important role in the database design. It is formed by linking matching
fields of two tables. The relationships effectively join tables to form one large table. This avoids
having to repeatedly enter the same data, therefore, saving time and reducing data entry
errors. There are three possible relationships between related entities or table. They are:
one-to-one, one-to-many and many-to-many.

One-to-One (1:1)
In a one-to-one relationship, each record in Table A can have only one matching record in
Table B, and each record in Table B can have only one matching record in Table A. This type
of relationship is not common, because most information related in this way would be in
one table. For example, One person has only one passport and one passport is given to one
person.

1 1
Person has Passport

One-to-Many (1:m)
One-to-many relationship is the most common type of relationship. In a one-to-many
relationship, a record in Table A can have many matching records in Table B, but a record in
Table B has only one matching record in Table A. For example-one customer can place many
orders but one order cannot be placed by many customers.

1 M
Customer Placed Order

Many-to-Many (m:m)
In a many-to many relationship, a record in Table A can have many matching records in Table
B, and a record in Table B can have many matching records in Table A. This type of relationship
is only possible by defining a third table (called a junction table) whose primary key consists of
two fields-the foreign keys from both Tables A and B. For example, a student can be assigned
to many projects and a project can be assigned to many students.

M M
Student Assigned Project

20 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Schema and Instances
A schema is the complete design of database which is also known as intension. It is the collection
of named objects. The names of tables, columns of each table, datatype, triggers, functions
views packages and other objects are included in the schema.
Let’s take an example of the student database. The schema diagram for the student database
could contain a table regarding to student’s information such as name, course detail, academic
performance and other information. In the given below schema diagram, there are two
records named as student and course with their attributes.
STUDENT

Name Student_number Semester

COURSE

Course_number Course_Name Credit_hours Department

An instance is the information collected in a database at some specific moment. It contains a


snapshot of the database. Database instances tend to change with time. A DBMS ensures that
its every instance (state) is in a valid state, by diligently following all the validations, constraints,
and conditions that the database designers have imposed.
Let’s take the similar example in the instance. Here the student construct will contain their
individual entities in the attributes.

STUDENT

Name Student_number Semester

Antony 1021 1

Bob 1022 1

Deeksha 1023 1

Rohan 1024 1

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 21


DBMS Keys
A DBMS key is an attribute or set of an attribute which helps you to identify a row(tuple) in a
relation(table). They allow you to find the relation between two tables. Keys help you uniquely
identify a row in a table by a combination of one or more columns in that table.
Here, are reasons for using keys in the DBMS system.
a. Keys help you to identify any row of data in a table.
b. Allows you to establish a relationship between and identify the relation between tables
c. Help you to enforce identity and integrity in the relationship.

DBMS has following types of keys each have their different functionality:
Primary Key
A column or group of columns in a table which helps us to uniquely identifies every row in
that table is called a primary key. This DBMS can’t be a duplicate. The same value can’t appear
more than once in the table.

Alternate Key
All the keys which are not primary key are called an alternate key. It is a candidate key which
is currently not the primary key. However, a table may have single or multiple choices for the
primary key.

Candidate Key
A candidate key is a column, or set of columns, in a table that can uniquely identify any database
record without referring to any other data. The primary key should be selected from the
candidate keys. Every table must have at least a single candidate key.

Candidate Key

StudID Roll No First Name LastName Email


1 11 Tom Prince [email protected]
2 12 Nick Wright [email protected]
3 13 Dana Natan [email protected]

Primary Key Alternate Key

a. What are the main components of Entity-Relationship model (ER model)?


b. Define the following terms: Primary key and Candidate key.

22 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Data Normalization
Data normalization is a process to present a database in normal form to avoid undesirable
things such as repetition of information, inability to represent information, loss of information,
etc. While designing a database, normalization theory helps to design the database in more
than one table. Normalization improves performance by reducing redundancy.
Advantages of data normalization are as follows:
1. It reduces redundancy.
2. It improves faster sorting and index creation.
3. It creates few indexes and nulls.
4. It ignores repetition of information.
5. It simplifies the structure of tables.
6. It improves the performance of a system.
7. It avoids loss of information.

Normal Forms
The normal forms are used to ensure that various types of anomalies and inconsistencies are
removed from the database. Normal forms are table structure with minimum redundancy.
Several normal forms have been defined. The most important and widely used are:
a. First Normal Form (1 NF)
b. Second Normal Form (2 NF)
c. Third Normal Form (3 NF)

First Normal Form (1 NF)


A table is said to be in the 1 NF when each cell of the table contains atomic value. Consider
the following table Employee.

Table Employee
EmpCode Dept Workcode Hours Amount per hour
Emp100 Accounts A1 100 50
A2 110 60
A3 120 70
Emp101 Administration A1 110 50
A2 100 75
Emp102 Sales A4 55 45
A5 60 55

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 23


Note: 1 NF expresses that each cell of the table should not have repeating groups. So, the data
in the above table is not normalized because cell work code, hours and amount per hour have
more than one value.
Applying the 1 NF, Employee table can be designed in the following form:
Table Employee
EmpCode Dept Workcode Hours Amount per hour
Emp100 Accounts A1 100 50
Emp100 Accounts A2 110 60
Emp100 Accounts A3 120 70
Emp101 Administration A1 110 50
Emp101 Administration A2 100 75
Emp102 Sales A4 55 45
Emp102 Sales A5 60 55
Second Normal Form (2 NF)
The table is said to be in 2 NF when it is in 1 NF and every attribute in the row is functionally
dependent upon the whole key, and not just part of the key.
Table Employee
EmpCode Dept Workcode Hours Amount per hour
Emp100 Accounts A1 100 50
Emp100 Accounts A2 110 60
Emp100 Accounts A3 120 70
Emp101 Administration A1 110 50
Emp101 Administration A2 100 75
Emp102 Sales A4 55 45
Emp102 Sales A5 60 55
In the above table, for each value of Empcode, there is more than one value of Amount Per
Hour. For example, for Empcode Emp 100, there are three values of Hours and Amount
Per Hour. So, Hours and Amount Per Hour are not functionally dependent upon Empcode.
However, for a combination of Empcode and Workcode there is exactly one value of Hours
and Amount Per Hour. So, Hours and Amount Per Hour is functionally depend on the whole
key Empcode and Workcode. Now, you must check whether Dept is functionally dependent
on the whole key that is Empcode + Workcode. For each value of Empcode there is only
one value of Dept. So, Dept is functionally dependent on the Empcode. However, for the
each value of Workcode, there is more than one value of Dept. So, Dept is not functionally
dependent on the Workcode. Therefore, Dept is functionally dependent on part of the key that
is Empcode and not functionally dependent on the whole key that is Empcode + Workcode.
Therefore, the above table is not in 2 NF.

24 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


To convert the above table (Employee) into 2 NF, you must remove the attributes that are not
functionally dependent on the whole key and place them in a different table with the attribute
that is functionally dependent on. In the above table, Dept is not fully dependent on the whole
key that is Empcode + Workhour, you can place Dept along with Empcode in a separate table
called Department and, store Ecode,Workcode, Hours and Amount Per Hour in a separate
table Work.
Applying the 2 NF tables can be designed in the following form:

Table Department
Empcode Dept
Emp100 Account
Emp101 Administration
Emp102 Sales

Table Work
EmpCode Workcode Hours Amount per hour
Emp100 A1 100 50
Emp100 A2 110 60
Emp100 A3 120 70
Emp101 A1 110 50
Emp101 A2 100 75
Emp102 A4 55 45
Emp102 A5 60 55

Third Normal Form (3 NF)


A relation is said to be in 3 NF when it is in 2 NF and every non-key attribute is functionally
dependent only on the primary key (Non-key is an attribute, if it is does not participate in the
primary key).
Consider the following table:
Table Employee
Empcode Dept Hours
Emp100 Account 100
Emp101 Administration 120
Emp102 Sales 100
Emp103 Sales 120
Emp104 Account 110

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 25


The primary key in the above table is Empcode. There is exactly one value of Dept for each
value of Empcode. Hence, Dept is functionally dependent on the primary key Empcode.
Similarly, for each value of Empcode there is only one value of Hours. Hence, Hours is also
functionally dependent on the primary key Empcode. So, the table is in 2 NF. Attribute Hours
is also dependent on the Dept. According to the rules of 3 NF, all non-key attributes have to
be functionally dependent only on the primary key. So, the above table is not in 3 NF.
To obtain the 3 NF from the above table employee, we will decompose the table with the following
form:
Table Employee
Empcode Dept
Emp100 Account
Emp101 Administration
Emp102 Sales
Emp103 Sales
Emp104 Account

Table Hours
Dept Hours
Account Account
Administration 120
Sales 100
Sales 120
Account 110
Denormoralization of Data
Data normalization theory is an aid to design the database in more than one table, which
improves efficiency of database by reducing redundancy. However, sometimes to get a simple
output, you have to join multiple tables. In such situations, it is wiser to introduce a degree
of redundancy by creating extra column, which affects the performance of a query. So, the
intentional introduction of redundancy in a table in order to improve the efficiency is called
denormalization.
For example, consider the following tables:
Table Employee

Empcode Dept Rate per hour


Emp100 Account 35
Emp101 Administration 55

26 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Emp102 Sales 60
Emp103 Sales 60
Emp104 Account 70

Table Hours
Dept 100
Account Account
Administration 120
Sales 100
Sales 120
Account 110

If you want to calculate the total wage for thousand employees, multiplying rate per hour by
working hours, the computer will take more time to process because it involves query and
calculation. So, to speed up the process of the query and calculation, sometimes it is necessary
to introduce redundancy and to add up extra columns. The following table shows an example
of data denormalization.

Table Employee
EmpCode Dept Rate per hour Hours Total Wage
Emp100 Accounts 35 100 3500
Emp101 Administration 55 120 6600
Emp102 Sales 60 100 6000
Emp103 Sales 60 120 7200
Emp104 Account 70 110 7700

Data Normalization Data normalization is a process to present a database in


normal form to avoid undesirable things.
Denormalization The intentional introduction of redundancy in a table in order
to improve the efficiency.

a. What is data normalization? What are the most important and widely used forms of data
normalization?
b. Explain the normalization process with examples.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 27
Centralized Vs. Distributed Database
Centralized Database
A centralised database is a database that is located, stored, and maintained in a single location.
This location is most often a central computer or database system, for example a desktop or
server CPU, or a mainframe computer. It is used by an organization (e.g. a business company)
or an institution (e.g. a university.) Users access a centralised database through a computer
network which is able to give them access to the central CPU, which in turn maintains to the
database itself.

Finance

Purchasing Centralized Sales


Database

HR

Advantages:
1. The data integrity is maximized as the whole database is stored at a single physical location.
2. The data redundancy is minimal in the centralised database. All the data is stored together
and not scattered across different locations. So, it is easier to make sure there is no
redundant data available.
3. Since all the data is in one place, there can be stronger security measures around it. So,
the centralised database is much more secure.
4. Data is easily portable because it is stored at the same place.
5. The centralized database is cheaper than the other types of databases as it requires less
power and maintenance.

Disadvantages:
1. Since all the data is at one location, it takes more time to search and access it. If the
network is slow, this process takes even more time.
2. There is a lot of data access traffic for the centralized database. This may create a bottleneck
situation.
3. Since all the data is at the same location, if multiple users try to access it simultaneously, it
creates a problem. This may reduce the efficiency of the system.
4. If there are no database recovery measures in place and a system failure occurs, then all
the data in the database will be destroyed.

28 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Distributed Database
Distributed database, as the name indicates, is stored in more than one physical location.
The database is stored partly in one location while it is partly stored and maintained in other
locations. In other words, a distributed database coordinates data access from various locations.
In this approach, databases are designed as an entity and are linked through communication

{ {
networks.

System System
in in
Nepal Australia

workstation workstation

Database Database
NETWORK

workstation
Database
{ System
in
Canada

Advantages:
1. If there were a natural catastrophe such as a fire or an earthquake, all the data would not
be destroyed as it is stored at different locations.
2. It is cheaper to create a network of systems containing a part of the database. This database
can also be easily increased or decreased.
3. Even if some of the data nodes go offline, the rest of the database can continue its normal
functions.

Disadvantages:
1. The distributed database is quite complex and it is difficult to make sure that a user gets a
uniform view of the database because it is spread across multiple locations.
2. It is difficult to provide security in a distributed database as the database needs to be
secured at all the locations it is stored.
3. It is difficult to maintain data integrity in the distributed database because of its nature.
There can also be data redundancy in the database as it is stored at multiple locations.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 29
Data Security
Data security refers to protective digital privacy measures that are applied to prevent
unauthorized access to computers, databases and websites. Data security also protects data
from corruption. Data security is the main priority for organizations of every size and genre.
Data security is also known as information security (IS) or computer security. Examples of data
security technologies include software/hardware disk encryption, backups, data masking and
data erasure.
Some of the data security methods are:
1. Implementing strong passwords is the easiest thing you can do to strengthen your security.
2. Typical hardware security controls include: regular maintenance, air conditioning
system, dust-free environment, security lighting, power protection devices and fire
alarms.
3. Backups are an important countermeasure against data corruption or loss. Backups allow
you to restore data that is damaged or destroyed. Scheduling regular backups to an
external hard drive, or in the cloud, is a painless way to ensure that all your data is stored
safely.
4. Protection from virus attacks is one of the most important security aspects of an
organization. Antivirus and anti-malware software are essentials in your arsenal of online
security weapons, as well.

Database Administrator
A database administrator (DBA) is a specialized computer systems administrator who maintains
a successful database environment by directing or performing all related activities to keep the
data secure. The top responsibility of a DBA professional is to maintain data integrity. This
means the DBA will ensure that data is secure from unauthorized access but is available to
users.

Qualities of a good DBA


a. The DBA should have depth knowledge of operating system in which database server is
running.
b. The DBA should have a sound knowledge of SQL.
c. The DBA should have a sound knowledge of good database design.
d. The DBA should have sound understanding of network architecture.
e. The DBA should have a good knowledge of database server.

Responsibility of DBA
a. Database installation, upgrade and patching
b. Install and configure relevant network components
c. Ensure database access, consistency and integrity
d. Resolving issues related to performance bottlenecks

30 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Structured Query Language
SQL (pronounced “ess-que-el”) is the acronym for Structured Query Language. SQL is the
standard language for communicating with relational database management systems. SQL is
used to query, insert, update and modify data. Some common relational database management
systems that use SQL are: Oracle, Sybase, MS SQL Server,MS Access, MySQL, etc.

SQL Command
SQL defines following ways to manipulate data stored in an RDBMS.
DDL: Data Definition Language
Data Definition Language includes changes to the structure of the table like creation of table,
altering table, deleting a table etc. All DDL commands are auto-committed. That means it
saves all the changes permanently in the database.
Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table

DML: Data Manipulation Language


DML commands are used for manipulating the data stored in the table and not the table itself.
DML commands are not auto-committed. It means changes are not permanent to database,
they can be rolled back.
Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables

DCL: Data Control Language


Data control language are the commands to grant and take back authority from any database
user.
Command Description
grant grant permission of right
revoke take back permission.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 31


Installing MySQL on Microsoft Windows
The simplest and recommended method is to download MySQL Installer (for Windows) and
let it install and configure a specific version of MySQL Server as follows:
a. Download MySQL Installer from https://dev.mysql.com/downloads/installer/ and execute
it.
Note:
Unlike the standard MySQL Installer, the smaller web-community version does not bundle
any MySQL applications, but downloads only the MySQL products you choose to install.

b. Determine the setup type to use for the initial installation of MySQL products. For
example:
Developer Default: Provides a setup type that includes the selected version of MySQL
Server and other MySQL tools related to MySQL development, such as MySQL
Workbench.
Server Only: Provides a setup for the selected version of MySQL Server without other
products.
Custom: Enables you to select any version of MySQL Server and other MySQL products.

c. Install the server instance (and products) and then begin the server configuration by first
selecting one of the following levels of availability for the server instance:
Standalone MySQL Server / Classic MySQL Replication (default)
Configures a server instance to run without high availability.

InnoDB cluster
Provides two configuration options based on MySQL Group Replication to:
Configure multiple server instances in a sandbox InnoDB Cluster on the local host (for
testing only).
Create a new InnoDB Cluster and configure one seed instance or add a new server
instance to an existing InnoDB Cluster.

d. Complete the configuration process by following the onscreen instructions.


MySQL is now installed. If you configured MySQL as a service, then Windows automatically
starts the MySQL server every time you restart the system. Also, this process installs the
MySQL Installer application on the local host, which you can use later to upgrade or
reconfigure MySQL server.

32 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


General Format of SQL statement
The general format of SQL statement is:
Verb
[Clause 1] <para1 : 1 para2 : 2 para1 : n>
[Clause 2] <para2 : 1 para2 : 2 para2 : n>
...
[Clause n];
The rules for writing SQL statements are:
a. An SQL statement starts with a verb. This verb may have some additional words.
b. Each verb is followed by a clause.
c. Each clause has one or more parameters.
d. A space separates clauses within an SQL statement.
e. A comma separates parameters within a clause.
f. A semicolon is used to terminate SQL statements.

SQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a new table in a database.
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
a. The column parameters specify the names of the columns of the table.
b. The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).

Example:
CREATE TABLE Customers
( CustID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 33


SQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table in a database.
Syntax:
DROP TABLE table_name;

Note:
Be careful before dropping a table. Deleting a table will result in loss of complete information stored
in the table.

Example:
DROP TABLE Shippers;

SQL ALTER TABLE Statement


MySQL ALTER statement is used when you want to change the name of your table or any
table field. It is also used to add or delete an existing column in a table.
The ALTER statement is always used with “ADD”, “DROP” and “MODIFY” commands
according to the situation.

ADD a column in the table


Syntax:
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ];

Parameter Name Description


table_name It specifies the name of the table that you want to modify.
new_column_name It specifies the name of the new column that you want to add to
the table.
column_definition It specifies the data type and definition of the column (NULL or
NOT NULL, etc).
FIRST | AFTER column_ It is optional. It tells MySQL where in the table to create the
name column. If this parameter is not specified, the new column will
be added to the end of the table.

Example:
In this example, we add a new column “cus_age” in the existing table “cus_tbl”.
ALTER TABLE cus_tbl
ADD cus_age varchar(40) NOT NULL;

34 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Add multiple columns in the table
Syntax:
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
...
;

Example:
In this example, we add two new columns “cus_address”, and cus_salary in the existing table
“cus_tbl”. cus_address is added after cus_surname column and cus_salary is added after cus_
age column.
ALTER TABLE cus_tbl
ADD cus_address varchar(100) NOT NULL
AFTER cus_surname,
ADD cus_salary int(100) NOT NULL
AFTER cus_age ;

MODIFY column in the table


The MODIFY command is used to change the column definition of the table.
Syntax:
ALTER TABLE table_name
MODIFY column_name column_definition
[ FIRST | AFTER column_name ];

Example:
In this example, we modify the column cus_surname to be a data type of varchar(50) and
force the column to allow NULL values.
ALTER TABLE cus_tbl
MODIFY cus_surname varchar(50) NULL;

DROP column in table


Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 35


Example:
Let’s take an example to drop the column name “cus_address” from the table “cus_tbl”.
ALTER TABLE cus_tbl
DROP COLUMN cus_address;

RENAME column in table


Syntax:
ALTER TABLE table_name
CHANGE COLUMN old_name new_name
column_definition
[ FIRST | AFTER column_name ]

Example:
In this example, we will change the column name “cus_surname” to “cus_title”.
ALTER TABLE cus_tbl
CHANGE COLUMN cus_surname cus_title
varchar(20) NOT NULL;

RENAME table
Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;

Example:
ALTER TABLE cus_tbl
RENAME TO cus_table;

SQL SELECT Statement


The SELECT statement in MySQL is used to fetch data from one or more tables. We can
retrieve records of all fields or specified fields that match specified criteria using this statement.
It can also work with various scripting languages such as PHP, Ruby, and many more.
Syntax:
SELECT field_name1, field_name 2,... field_nameN
FROM table_name1, table_name2...
[WHERE condition]
[GROUP BY field_name(s)]

36 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


[HAVING condition]
[ORDER BY field_name(s)]
[OFFSET M ][LIMIT N];
Syntax for all fields:
SELECT * FROM tables [WHERE conditions]
[GROUP BY fieldName(s)]
[HAVING condition]
[ORDER BY fieldName(s)]
[OFFSET M ][LIMIT N];

Parameter Name Description


field_name(s) or * It is used to specify one or more columns to return in the result
set. The asterisk (*) returns all fields of a table.
table_name(s) It is the name of tables from which we want to fetch data.
WHERE It is an optional clause. It specifies the condition that returned the
matched records in the result set.
GROUP BY It is optional. It collects data from multiple records and grouped
them by one or more columns.
HAVING It is optional. It works with the GROUP BY clause and returns
only those rows whose condition is TRUE.
ORDER BY It is optional. It is used for sorting the records in the result set.
OFFSET It is optional. It specifies to which row returns first. By default, It
starts with zero.
LIMIT It is optional. It is used to limit the number of returned records
in the result set.
Example:
a. SELECT CustomerName, City FROM Customers;
-Selects the “CustomerName” and “City” columns from the “Customers” table.

b. SELECT * FROM Customers;


- Selects all the columns from the “Customers” table.

SQL INSERT Statement


MySQL INSERT statement is used to store or add data in MySQL table within the database.
We can perform insertion of records in two ways using a single query in MySQL:
a. Insert record in a single row
b. Insert record in multiple rows

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 37


Syntax:
To insert a single record in MySQL table
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );
In the above syntax, we first have to specify the table name and list of comma-separated
columns. Second, we provide the list of values corresponding to columns name after the
VALUES clause.

Note:
Field name is optional. If we want to specify partial values, the field name is mandatory. It also
ensures that the column name and values should be the same. Also, the position of columns and
corresponding values must be the same.

To insert multiple records within a single command


INSERT INTO table_name VALUES
( value1, value2,...valueN )
( value1, value2,...valueN )
...........
( value1, value2,...valueN );
In the above syntax, all rows should be separated by commas in the value fields.

Example:
First, create a table “People” in the database using the following command:
CREATE TABLE People(
id int NOT NULL AUTO_INCREMENT,
name varchar(45) NOT NULL,
occupation varchar(35) NOT NULL,
age int,
PRIMARY KEY (id)
);
If we want to store multiple records, use the following statements where we can either specify
all field names or don’t specify any field.
INSERT INTO People VALUES
(102, ‘Joseph’, ‘Developer’, 30),
(103, ‘Mike’, ‘Leader’, 28),
(104, ‘Stephen’, ‘Scientist’, 45);

38 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


SQL UPDATE Query
MySQL UPDATE query is a DML statement used to modify the data of the MySQL table
within the database. In a real-life scenario, records are changed over a period of time. So,
we need to make changes in the values of the tables also. To do so, it is required to use the
UPDATE query.
The UPDATE statement is used with the SET and WHERE clauses. The SET clause is used to
change the values of the specified column. We can update single or multiple columns at a time.

Syntax:
UPDATE table_name
SET column_name1 = new-value1,
column_name2=new-value2, ...
[WHERE Clause]

Parameter Name Description


table_name It is the name of a table in which we want to perform updation.
column_name It is the name of a column in which we want to perform updation
with the new value using the SET clause. If there is a need to
update multiple columns, separate the columns with a comma
operator by specifying the value in each column.
WHERE Clause It is optional. It is used to specify the row name in which we
are going to perform updation. If we omit this clause, MySQL
updates all rows.
MySQL DELETE Statement
MySQL DELETE statement is used to remove records from the MySQL table that is no longer
required in the database. This query in MySQL deletes a full row from the table and produces
the count of deleted rows. It also allows us to delete more than one record from the table
within a single query, which is beneficial while removing large numbers of records from a table.
By using the delete statement, we can also remove data based on conditions.
Once we delete the records using this query, we cannot recover it. Therefore before deleting
any records from the table, it is recommended to create a backup of your database. The
database backups allow us to restore the data whenever we need it in the future.

Syntax:
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) should be deleted. If you omit the
WHERE clause, all records in the table will be deleted!
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 39
Concepts Review
Topic Key Concepts
Electronic database Data is the plural form of the word “datum” which refers to
a collection of raw facts.
Processing is a series of actions or operations that converts
some input into useful output.
Data processing is defined as the processing of data to make
it more usable and meaningful, thus transforming it into
information.
Electronic database refers to an organized collection of data
stored on a computer in such a way that its contents (data)
can easily be accessed, updated and queried upon with the
help of a software program.
Table is a set of information about a particular subject
(for example, a table could have information on all the
departments of a company).
Database Management An entity-relationship model (ERM) is a theoretical and
System conceptual way of showing data relationships in software
development.
The relationships effectively join tables to form one large
table.
Data normalization is a process to present a database in
normal form to avoid undesirable things such as repetition
of information, inability to represent information, loss of
information, etc.
A table is said to be in the 1 NF when each cell of the table
contains atomic value.
The table is said to be in 2 NF when it is in 1 NF and every
attribute in the row is functionally dependent upon the
whole key, and not just part of the key.
A relation is said to be in 3 NF when it is in 2 NF and
every non-key attribute is functionally dependent only on
the primary key (Non-key is an attribute, if it is does not
participate in the primary key).
A centralised database (sometimes abbreviated CDB) is a
database that is located, stored, and maintained in a single
location.

40 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Section 1.1 (Very Short Questions)
a. What is electronic database?
b. State any three objectives of DBMS.
c. Define the following terms: Field, Record and Object
d. What is primary key?
e. What are domains and tuples?
f. What is data security?

Section 1.2 (Short Questions)


a. What are the advantages and disadvantages of database management system?
b. What is the purpose of E-R diagram? List out the different symbols used in E-R diagram
with their meaning and examples.
c. What is data normalization? What are the most widely used forms of data normalization?
d. What is data security? What are the different data security method?
e. Who is DBA? What are the qualities of DBA?

Section 1.3 (Long Questions)


a. What is a Database Management System? How does database management system
work?
b. Explain the different types of database structures.
c. What is relational database model? List its advantages and disadvantages.
d. Explain the difference between centralized database and distributed database.
e. What is Structured Query Language? What are the four main categories of SQL code?

Make a case study to computerize the library system of your college. Ask
the librarian the type of records they are maintaining. Then identify all the
necessary entities, make an ERD and design a database with tables, queries,
forms and reports.

Teaching Manual
While teaching this chapter, the key concepts that need to be emphasized upon include:
a. Concept of database system and file based system, definition of DBMS, types of data
models.
b. Concept of normalization and denormalization, differentiate between centralised database
and distributed database and database designing using MS-ACCESS.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 41


Communications
Chapter
and
2 Networking

Concept
Originally all computers and other information processing devices stood alone and
their information was available only to those who had direct connections to them.
Since the value of data increases dramatically when it’s easier to collect and distribute,
computers and other information processing devices are now connected to one
another in networks. Computer networks can include all the computers and devices in
a department, a building, or multiple buildings spread over a wide geographic area. They
form the backbone in the entire computer industry. The demand for larger, faster, higher-
capacity network has increased as businesses have realized the value of networking their
computer systems.

42 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Communications and Networking
Originally all computers and other information processing devices stood alone and their
information was available only to those who had direct connections to them. Since the value
of data increases dramatically when it’s easier to collect and distribute, computers and other
information processing devices are now connected to one another in networks. Computer
networks can include all the computers and devices in a department, a building, or multiple
buildings spread over a wide geographic area. They form the backbone in the entire computer
industry. The demand for larger, faster, higher-capacity network has increased as businesses
have realized the value of networking their computer systems.

Communication and Basic Elements of a Communication System


Communication is the process of transferring messages from one point to another. The three
basic elements of any communication system are:
a. A sender, which creates the message to be transmitted.
b. A medium, which carries the message.
c. A receiver, which receives the message.
For example; when you speak to your friend on the telephone, you are the sender, the
telephone line, through which your voice is transmitted, is the medium, and your friend is the
receiver.

Data Communication
Data communication refers to the exchange of data between a source and a receiver. The
device that transmits the data is known as a source and the device that receives the transmitted
data is known as a receiver. A data communication system has the following components:
Message It is the information or data to be communicated. It can consist of text,
numbers, pictures, sound or video or any combination of these.
Sender It is the device that generates and sends that message.
Receiver It is the device that receives the message.
Medium It is the channel or physical path through which the message is carried from
the sender to the receiver. The medium can be wired like twisted pair
wire, coaxial cable, fiber-optic cable or wireless like laser, radio waves, and
microwaves.
Protocol It is a set of rules that govern the communication between the devices.
Both the sender and the receiver follow same protocols to communicate
with each other.
Protocol Protocol
Medium
Sender Receiver
Transmission
Media
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 43
Computer Network
Computer networking technology has become the most explosive area of growth in the entire
computer industry. Today, more and more computers are being connected into computer
networks. The value of the computer connected to a network increases exponentially with
the number of machines connected to it. Computer network is a communication system
connecting two or more computers that work together to exchange information and share
resources. It includes network media, such as a cable to carry network data; network adapter
card to translate the data between the computer and the network media; a network operating
system to enable a machine to participate in the network; and a network protocol to control
the network communications.

Need and Importance of Computer Networks


The unprecedented growth of information, the need for sharing it quickly, efficiently and
reliably with others while keeping the costs down has given a tremendous boost to computer
networking. Networking computers together offers many advantages. Some of them are
discussed below:

Quick and Efficient Transfer of Data Files


Computer network allows faster, easier and reliable transfer of data files from one computer
to the other.

Sharing of Resources
Computer network facilitates the users to share the limited and otherwise expensive resources
among a number of computing devices.

Increased Cost-Efficiency
Computer networks are a feasible cost-efficient solution as they allow software to be stored
or installed as one computer which can then be shared among other computers connected
on the same network.

Saving of Money
Since a network allows sharing of hardware and software, it saves a considerable amount of
money which would otherwise be spent on buying separate hardware and software for each
computer.

Access to Information on Remote Computer


The Internet (the biggest network of computers) allows access to information stored on
remote computers. This enables us to perform a number of tasks such as the reservations and
buying of Airline tickets, Hotel bookings, payments of electricity bills, etc. sitting right there in
the comfort of our homes without needing to step outside.

44 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Faster, Cheaper and Reliable Communication
Computer networking helps in sending and receiving of electronic-mail (e-mail) messages
from anywhere in the world. This allows the users to communicate online in a faster and cost
effective manner. Video conferencing is another form of communication. People in distant
locations can hold a meeting, and they can hear and see each other simultaneously.

Back-Up and Support


Networked computers provide the critical function of back-up. In the event that one computer
fails, its counterpart can resume its functions and workload. Back-up capability is useful in
systems like air traffic control, banking, military and many other applications.

Disadvantages of Computer Networks


1. The network systems are more sophisticated and complex to run. This can add to costs
and you may need specialist staff to run the network.
2. Computer network faults can cause loss of data and resources.
3. The network services becomes unusable and productivity fails if the networks are badly
managed.
4. Proper maintenance of a network computer requires considerable time and expertise.
5. File security is more important if connected to WANs, e.g., protection from computer
viruses and hackers.

Data Transmission
Data may be transferred from one device to another by means of some communication
media. The electromagnetic or light waves that transfer data from one device to another
device in encoded form are called signals. Data transmissions across the network can occur
in two forms i.e.:
a. Analog signal
b. Digital signal

Analog Signal
The transfer of data in the form of electrical signals or continuous waves is called analog signal
or analog data transmission. An analog signal is measured in volts and its frequency is in hertz
(Hz).

Advantages of Analog Signaling


1. Allows multiple transmissions across the cable
2.. Suffers less from attenuation

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 45


Disadvantages of Analog Signaling
1. Suffers from EMI. Electromagnetic interference (or EMI, also called radio-frequency
interference or RFI (radio frequency) is disturbance that affects an electrical circuit due to
either electromagnetic induction or electromagnetic radiation emitted from an external
source
2. Can only be transmitted in one direction without sophisticated equipment

Digital Signal
The transfer of data in the form of digit is called digital signal or digital data transmission. Digital
signals consist of binary digits 0 & 1. Electrical pulses are used to represent binary digits. Data
transmission between computers is in the form of digital signals.

Advantages of Digital Signaling


1. Equipment is cheaper and simpler than analog equipment
2. Signals can be transmitted on a cable bidirectional
3. Digital signals suffer less from EMI

Disadvantages Digital Signaling


1. Only one signal can be sent at a time
2. Digital signals suffer from attenuation

V Transmitted Signal

1 0 0 1 0 1 1 Code Represented
T
Modulation
The process of changing some characteristics (amplitude, frequency or phase) of a carrier
wave in accordance with the intensity of the signal is known as modulation. Modulation means
to change. In modulation, some characteristics of the carrier wave is changed in accordance
with the intensity (amplitude) of the signal. The resultant wave is called the modulated wave or
radio wave and contains the audio signal. Therefore, modulation permits the transmission to
occur at high frequencies while it simultaneously allows the carrying of the audio signal. There
are three types of modulation:
a. Amplitude Modulation (AM)
b. Frequency Modulation (FM)
c. Phase Modulation (PM)

46 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Amplitude Modulation (AM)
Amplitude Modulation (AM) is the method of broadcasting electrical signals that cannot travel
very far on their own. In this method, the signal is imposed or ‘imprinted’ on a carrier wave
whose amplitude increases or diminishes with the amplitude of the signal. AM transmission
operates in the 535 to 1705 kilohertz frequency band used for shortwave broadcasting and
some citizen band (CB) aviation services. The following points are worth noting in the case of
amplitude modulation:
a. The amplitude of the carrier wave changes according to the intensity of the signal.
b. The amplitude variations of the carrier wave is at the signal frequency.
c. The amplitude of the amplitude modulated wave remains the same-carrier frequency.

Frequency Modulation (FM)


Frequency Modulation (FM) is the method of broadcasting electrical signals that cannot travel
very far on their own. In this method, the signal is imposed or ‘imprinted’ on a carrier wave
whose frequency increases or diminishes with the frequency of the signal. FM transmission
operates in 88 to 108 megahertz frequency band, and is less susceptible to electromagnetic
interference than amplitude modulation (AM).

The frequency modulation has the following advantages:


1. It gives noiseless reception. Noise is a form of amplitude vibrations and FM receivers
reject such signals.
2. Operating range is quite large.
3. It gives high-fidelity reception.
4. The efficiency of transmission is very high.

Phase Modulation (FM)


Phase Modulation (PM) is a method of impressing data onto an alternating-current (AC)
waveform by varying the instantaneous phase of the wave. This scheme can be used with
analog or digital data. Unlike frequency modulation (FM), phase modulation is not widely used
for transmitting radio waves. This is because PM requires more complex receiving hardware,
and there can be ambiguity problems in determining whether, for example, the signal has
changed phase by +180° or -180°.
PM is used for signal and waveform generation in digital synthesizers, such as the Casio CZ
synthesizers, and to implement FM synthesis in such digital synthesizers as the Yamaha DX7.

a. What is a data communication? List the components of data communication.


b. What is a computer network? List the advantages and disadvantages of computer network.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 47


Transmission Modes
The way in which data is transmitted from one place to another is called data transmission
mode. It is also called the data communication mode. It indicates the direction of flow of
information. The transmission is characterized by:
a. The direction of the exchanges
b. The transmission mode: the number of bits sent simultaneously

Direction of Data Transmission


There are three different transmission modes characterized according to the direction of the
exchanges:

Simplex Mode Communication


Simplex mode communication is a mode of transmission in which communication takes place
between two stations in only one direction at a time. There is no return path. Simplex mode
can use the full bandwidth of the medium for transmission because the transmission operates
in only one direction. Radio and television broadcasts operate in simplex mode.
Simplex (One-way only)
Transmitter Receiver

Half Duplex Mode Communication


Half duplex communication is a mode of transmission in which data flows in the both directions,
but only from one direction at a time. Half duplex mode use the full bandwidth of the medium
because the transmission occurs in only one direction at a time. Walkie-talkies operate in half
duplex mode.

Transmitter Receiver
Half Duplex (Both ways, but
only one way at a time)
Receiver Transmitter

Full Duplex Mode Communication


Full duplex communication is a mode of transmission in which data is transmitted in both the
directions simultaneously on the same channel. Full duplex mode cannot use the full bandwidth
of the medium because the transmissions are allowed in both directions simultaneously. The
most common example of a full-duplex network is the telephone system. Both parties can
speak simultaneously during a telephone call and each party can also hear the other at the
same time.
Full Duplex (Both ways,
Transmitter Receiver
simultaneously)

Receiver Transmitter

48 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Computer Network Models
Computer network model is a design specifications for how the nodes on a network interact
and communicate. The three primary network models are centralized computing network,
client/server network and peer-to-peer network.
Centralized Computing Network
Terminal
Centralized Computing Network is a network
model in which a host computer connected
to other computers or terminals provide data
or computing services via a network. The host
computer is the core of the centralized computing
model. A network host may offer information Workstation running
resources, services and applications to users Terminal Emulator
or other nodes on the network. Centralized program
computing network provides high performance
and centralized management, but it is also Everything is local
expensive to implement. Centralized computing to Host
network is also called host-based networks.

Client/Server Network
Client/Server Network is the workhorse of the network world and consists of at least one
server (with shared resources) and the other computers on the network, called clients, makes
a service request from the server. Servers provide access to shared files, printers, hardware
and applications. In client/server networks, processing power, management services and
administrative functions can be concentrated where needed while clients can still perform
many basic end-user tasks on their own.
Client/Server has the following characteristics:
1. The client server computing works with a system of request and response. The client
sends a request to the server and the server responds with the desired information.
2. A server can only accommodate a limited number of client requests at a time. So it uses
a system based to priority to respond to the requests.
Client Client Domain Controller Server Client Client

Client logs into domain

Client can access all domain resources

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 49


Peer-to-Peer Network
Peer-to-Peer network is a network model in which resource sharing, processing, and
communications control are completely decentralized. All clients on the network are equal
in terms of providing and using resources, and users are authenticated by each individual
workstations. Peer-to-Peer networks are easy and inexpensive to implement. However,
they are only practical in very small organizations, due to lack of central data storage and
administration.
Peer

Files

Files

Peer

Peer to Peer Network has the following characteristics:


1. Each device in a P2P network gives resources to the network and consumes resources
that the network provides.
2. In a P2P network, files are shared between the different computers.
3. It has better stability and scalability.
4. The setup of a peer-to-peer network requires specialized software.
5. Since nodes in peer to peer networks act as both clients and servers, it is difficult to
provide adequate security for the nodes. This can lead to denial of service attacks.

Difference between Client/Server network and Peer to Peer network


Client/Server Network Peer to Peer Network
Client-server networks are computer Peer-to-Peer network is a network model
networks that use a dedicated computer in which resource sharing, processing, and
(server) to store data, manage/provide communications control are completely
resources and control user access. decentralized.
Client-Server network focuses on information Peer-to-Peer network focuses on connectivity.
sharing.
Centralized server is used to store the data. Each peer has its own data.
Client-Server network is used for both small Peer-to-Peer network is generally suited
and large networks. for small networks with fewer than 10
computers.

50 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Computer Network Categories
A network can mean a small group of linked computers to a chain of a few hundred computers
of different types spread around the world. Thus, networks vary in size, complexity and
geographical spread. Mostly, computers are classified on the basis of geographical spread and
on this basis, there can be three types of networks: Local Area Network (LAN), Metropolitan
Area Network (MAN) and Wide Area Network (WAN)

Local Area Network (LAN)


Local Area Network is a self-contained network that spans a small area, such as a single building,
floor, or a room. It consists of just two or more personal computers connected together by
a cable, a small radio transmitter. It consists of a communication channel, network computers
and devices, a network interface card and a network operating system. The major benefit of
a local area network is that it can help to reduce cost by allowing people and computers to
share expensive resources.
LAN has the following characteristics:
1. Data transfer rates are high, usually 1 Mbps-100 Mbps (Million of bits per second).
2. Owned by a single organization.
3. Diameter of not more than three kilometers.
4. The transmission media is shared by all the connected devices in the network.
5. Each device connected in the network can either operate standalone or in the network.

gET
mORE Wireless LANs (WLAN)
Wireless Local Area Network (WLAN) links devices over a short distance
iNFO via a wireless technology that uses radio waves to establish connections.
Each computer connected into a WLAN has a small antenna in its Network
Interface Card. Data signal transmitted by these antennae, are picked up and
routed by a wireless network switch known as the Access Point. A wireless
technology known as Wi-Fi is used for setting up high-speed WLANs over a
distance of upto 30 meters.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 51


Metropolitan Area Network (MAN)
Metropolitan Area Network is a large computer network that spans a metropolitan area
or campus. Its geographic scope falls between WAN and LAN. They typically use wireless
infrastructure or optical fiber connections to link their sites. Cable TV network is a good
example of such network.
MAN has the following characteristics:
1. The network size falls intermediate between LANs and WANs. A MAN typically covers
an area of between 5 and 50 km diameter.
2. The communications links and equipment of MAN are generally owned by either a
consortium of users or by a single network provider who sells the service to the users.
3. A MAN often acts as a high speed network to allow sharing of regional resources. It is also
frequently used to provide a shared connection to other networks using a link to a WAN.

Wide Area Network (WAN)


Wide Area Network is a telecommunications
network, usually used for connecting computers,
that spans a wide geographical area. WANs can be
used to connect cities, states, or even countries.
Typically, it will employ communication circuits
such as long-distance telephone wires, fiber optic
cable, microwaves and satellites. WANs are often
used by larger corporations or organizations to
facilitate the exchange of data. The world’s most
popular WAN is the Internet.
Wireless MAN
gET Wireless MAN or a Wireless Metropolitan Area Network is a type
of wireless network that connects several wireless LANs over a city or
mORE metropolitan area. A wireless technology known as the WiMAX or Wireless
iNFO Interoperability for Microwave Access is used for setting up wireless MANs
within a radius of 50 km.

52 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


WAN has the following characteristics:
1. Multiple computers are connected together.
2. It connects devices that are separated by a broader geographical area.
3. A WAN usually interconnects multiple LANs
4. Communication links between computers are provided by telephone networks, public
data networks, satellites, etc.

Physical Topologies for LAN


The physical topology of a network is the actual geometric layout of nodes. The commonly
used physical network topologies are bus, star and ring. The choice of network topology for
installing a computer network depends upon a combination of factors, such as:
a. The desired performance of the system.
b. The desired reliability of the entire system.
c. Size (number of nodes and their geographical distribution) of the system.
d. Expendability of the system.
e. Cost of the components and services required
f. Availability of communication lines.
g. Delays involved in routing information from one to another.

Physical Bus Topology


A physical bus topology is a network topology in which all the computers and peripheral
devices are connected to a common single cable called bus. On a bus, only one computer
can transfer information at a time. When a computer sends information, the information moves
through the entire length of the cable. The destination computer retrieves the information
from the cable. The bus has terminators at either end which absorb the signals transmitted on
a network cable. Terminators prevent signals from being bounced back along the cable and
causing interference.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 53


Advantages:
1. Easy to implement and extend.
2. Easy to install.
3. Easy identification of cable faults.

Disadvantages:
1. Limited cable length and number of stations.
2. If there is a problem with the cable, the entire network breaks down.
3. Maintenance costs may be higher in the long run.

Physical Ring Topology


A physical ring topology is a network topology
or circuit arrangement in which each network
node is attached along the same signal path to
two other devices, forming a path in the shape
of a ring. Each node in turn reads the network
signal from its upstream neighbour and then
retransmits it to its downstream neighbour, so
signal quality is high. Thus data travels in one
direction only, from node to node around
the ring. After passing through each node, it
returns to the sending node, which removes
it.
Advantages:
1. Performs better than a bus topology under heavy network load.
2. Does not require network server to manage the connectivity between the computers.
3. Easy to use optical fibers as a medium of transmission.
4.. Token passing makes ring topology perform better than bus topology under heavy traffic.
5. Reduced chances of data collision as each node release a data packet after receiving the
token.

Disadvantages:
1. Node failure causes network failure.
2. Difficult to diagnose faults.
3. Network re-configuration is difficult.
4. Network is highly dependent on the wire which connects different components.

54 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Physical Star Topology
A physical star topology is a network topology
where each of the devices and computers
on a network connect to one central switch,
hub or computer. Thus, the hub and leaf
nodes, and the transmission lines between
them, form a graph with the topology of a
star. Data on a star network passes through
the hub, switch, or concentrator before
continuing to its destination. The hub, switch,
or concentrator manages and controls all
functions of the network. It also acts as a
repeater for the data flow.
Advantages:
1. Easy to install and wire.
2. Easy to detect faults and to remove parts.
3. No disruptions to the network when connecting or removing devices.

Disadvantages:
1. High dependence of the system on the functioning of the central hub.
2. Failure of the central hub renders the network inoperable.
3. The performance and scalability of the network depends on the capabilities of the hub.

Physical Tree Topology


A physical tree topology is a type of network topology that includes at least three specific
levels in a topology hierarchy. A tree topology includes multiple star topologies, which involve
a variety of single nodes connected to a central node. Multiple stars involve either a series or
tertiary nodes attached to two or more secondary nodes, which are attached to the tree’s
primary trunk node. Experts may define a tree topology as a combination of star and bus
topologies, where multiple elements are connected through a single lateral connection.

Advantages:
1. Expansion of network is possible and easy.
2 Here, we divide the whole network into segments (star networks), which can be easily
managed and maintained.
3. Error detection and correction is easy.
4. Each segment is provided with dedicated point-to-point wiring to the central hub.
5. If one segment is damaged, other segments are not affected.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 55
Disadvantages:
1. Because of its basic structure, tree topology, relies heavily on the main bus cable, if it
breaks whole network is crippled.
2. As more and more nodes and segments are added, the maintenance becomes difficult.
3. Scalability of the network depends on the type of cable used.

Physical Mesh Topology


In a mesh network topology, each of the network node, computer and other devices, are
interconnected with one another. Every node not only sends its own signals but also relays
data from other nodes. In fact a true mesh topology is the one where every node is connected
to every other node in the network. This type of topology is very expensive as there are many
redundant connections, thus it is not mostly used in computer networks. It is commonly used
in wireless networks. Flooding or routing technique is used in mesh topology.

Advantages:
1. Data can be transmitted from different devices simultaneously. This topology can withstand
high traffic.
2. Even if one of the components fails, there is always an alternative present. So data transfer
doesn’t get affected.
3. Expansion and modification in topology can be done without disrupting other nodes.

Disadvantages:
1. There are high chances of redundancy in many of the network connections.
2. Overall cost of this network is way too high as compared to other network topologies.
3. Set-up and maintenance of this topology is very difficult. Even administration of the
network is tough.

Local Area Network A self-contained network that spans a small area, such as a
single building, floor, or a room.
Wide Area Network A telecommunications network, usually used for connecting
computers, that spans a wide geographical area.

a. What is the difference between LAN and WAN?


b. What is LAN topology? What are the advantages and disadvantages of ring topology?

56 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Communication Media
Communication media refers to the mode of physical connection needed for data transmission.
It forms the path over which data travels as it passes from a sending device to a receiving device
in a telecommunications system. There are two types of communication media: bounded
media and unbounded media.

Guided (Bounded) Media


Guided (Bounded) media is any network media that travels in a contained conductor. This
conductor can be a metal wire through which electricity flows or a glass strand through which
pulses of light flows. Some of the examples of bounded media are twisted pair wire, coaxial
cable and fiber optic cable.

Twisted Pair Cable


Twisted pair cable is the oldest and common medium of
transmission. It consists of a pair of insulated wires twisted
together. The wires are twisted so as to reduce the electrical
interference. It is lightweight, cheap, can be installed easily,
and they support many different types of network. Twisted-
pair cable is used by older telephone networks The two
types of twisted pair cable are UTP (Unshielded Twisted
Pair) and STP (Shielded Twisted Pair).

Cable Type Description


UTP Unshielded Twisted Pair is the most popular type of twisted pair cabling
because it is inexpensive, reliable and supports data transfer rates up to
1 Gbps. It consists of two unshielded wires twisted around each other
within the cable to carry a differential signal. The combination of differential
signal and the twists (twists per foot) give UTP good noise rejection
and a maximum distance of 100 meters. It supports the physical star
configuration. It comes in different grades, called categories (Category 1
to Category 7 or Cat 1 to Cat 7), where the cable’s bandwidth capability
increases with the category number. Cat 5 is the most popular category
that uses RJ-45 connectors.
STP Shielded Twisted Pair (STP) consists of wires wrapped in a metal sheath
to provide extra protection from external interfering signals. STP is more
difficult to install and is more expensive than UTP. STP has a shorter
distance than UTP (only 90 meters) but has better noise rejection. STP
cable grades are called types and range from type 1 to type 9 with types
1, 1A, 2A and 6A used in networks.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 57


Coaxial Cable
Coaxial cable, or coax, is an electrical cable with an inner
conductor surrounded by a flexible, tubular insulating
layer, surrounded by a tubular conducting shield. The
term coaxial comes from the inner conductor and the
outer shield sharing the same geometric axis. Coaxial
cable is used as a transmission line for radio frequency
signals, in applications such as connecting radio
transmitters and receivers with their antennas, computer
network (Internet) connections and distributing cable
television signals.
Cable Type Description
ThinNet ThinNet is about an eighth inch in diameter and easy to install. It uses
BNC connectors and requires a 50 ohm terminator. It has an end-to-
end distance of 185 meters.
ThickNet ThickNet is about half inch in diameter and is difficult to install. There are
two types of connectors for use with ThickNet - the N-connector and a
vampire tap. It has an end-to-end distance of 500 meters.

Fiber Optic
Fiber optic cable is a thin glass strand designed for light
transmission. It is constructed of a transparent core
made up of pure silicon dioxide, through which the light
travels. The glass core is between 5 and 125 microns.
The core is surrounded by a cladding layer that reflects
light, guiding the light along the core. A plastic coating
covers the cladding to protect the glass surface. It can
easily carry data at more than a billion bits per second.
It is immune to electromagnetic interference and offers
greater bandwidth. It is a very secure transmission
medium. It is used as a medium for telecommunication
and networking because it is flexible and can be bundled
as cables. The main disadvantage of fiber optics is that the
cables are expensive to install. In addition, they are more
fragile than wire and are difficult to split. The connectors
used in fiber optic are ST and SC.

ST (Straight Tip) - a connector developed by AT&T. SC (Standard Connector)


- developed by the laboratories at Nippon Telegraph and Telephone (NTT)

58 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Unbounded Media
Unbounded media uses a transmission carrier to send data signals through the air instead of
cables. It includes wireless transmission methods such as radio networking, infrared transmission
and microwave transmission to interconnect the other components of a network. Unbounded
media technologies have two distinct advantages for businesses over bounded media; first,
they are generally easier to install and reconfigure; and second; they afford client machines a
lot of mobility.

Microwave Transmission
Microwave transmission involves the
sending and receiving of microwave signals
over a microwave link. This microwave link
is made up of a string of microwave radio
antennas located at the top of towers at
various microwave sites. Microwaves must
be transmitted in a straight line with no
obstructions between microwave antennas. To avoid possible obstructions, such as buildings
or mountains, microwave stations often are positioned on the tops of buildings, towers or
mountains. Microwave transmission is commonly used by communication systems on the
surface of the Earth, in satellite communications, and in deep space radio communications.

Advantages:
1. It provides cheaper than digging trenches for laying cables and maintaining repeaters and
cables if cables get broken by a variety of causes.
2. It offers freedom from land acquisition rights that are required for laying, repairing the
cables.
3. It offers ease of communication over difficult terrain.
4. It has the ability to communicate over oceans.

Disadvantages:
1. Microwave communication is an insecure communication.
2. Signals from a single antenna may split up and propagate by slightly different paths to the
receiving antenna. When these out-of-phase signals recombine, they interfere, reducing
the signal strength.
3. Microwave propagation is susceptible to weather effects like rains, thunder storms, etc.
4. Bandwidth allocation is extremely limited in case of microwaves.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 59


Radio Wave Transmission
The transmission making use of radio frequencies is
termed as radio-wave transmission. It is a form of Radio frequency (RF) waves
communications in which signals are sent via radio
frequency (RF) waves in the 10 KHz and 1 GHz.
It is subject to electrical interference from power
lines, a building’s metal structural components and Indoor Outdoor
atmospheric conditions. All radios today, however,
use continuous sine waves to transmit information
(audio, video, data). Each different radio signals uses
a different sine wave frequency, and that is how
they are all separated.
Any radio setup has two parts.
a. The transmitter
b. The receiver
The transmitter takes some sort of message (it could be the sound of someone’s voice, pictures
for a TV set, data for a radio modem or whatever), encodes it onto a sine wave and transmits
it with radio waves. The receiver receives the radio waves and decodes the message from the
sine wave it receives. Both the transmitter and receiver use antennas to radiate and capture
the radio signal.

Advantages:
1. Radio-wave transmission offers mobility.
2. It proves cheaper than digging trenches for laying cables and maintaining repeaters and
cables if cables get broken by a variety of causes.
4. It offers freedom from land acquisition rights that are required for laying, repairing the
cables.
5. It offers ease of communication over difficult terrain.

Disadvantages:
1. Radio-wave communication is an insecure communication.
2. Radio-wave propagation is susceptible to weather effects like rains, thunder storms, etc.
3. Like most other forms of electronic communication, radio requires the presence of
electricity, both at the point of the transmission and the point of reception. While battery-
powered radios are common, these power needs are more cumbersome than those of
land line telephones, which can operate using electricity already in the lines to make calls
even during periods of emergency or power outages. A powerful radio transmitter, such
as a regional broadcast station, requires large amounts of electricity at all times to send out
its signal.

60 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Infrared Transmission
Infrared transmission refers to energy in the region
of the electromagnetic radiation spectrum at
wavelength is longer than those of visible light, but Indoor Outdoor
shorter than those of radio. It is used for networking
computers together and connecting devices.
Infrared connectivity requires two devices having
visual contact with each other. Infrared signals
cannot pass through walls, so they are generally
contained inside a single room.

Satellite Communication
Satellite communication is the use of artificial
satellites to provide communication links between
various points on Earth. Satellite communications
play a vital role in the global telecommunications
system. Approximately 2,000 artificial satellites
orbiting Earth relay analog and digital signals carrying
voice, video, and data to and from one or many
locations worldwide. Satellite communication has
two main components: the ground segment, which
consists of fixed or mobile transmission, reception,
and ancillary equipment, and the space segment,
which primarily is the satellite itself.
Advantages:
1. The area coverage through satellite transmission is quite large.
2. Mobile communication cab be easily achieved by satellite communication because of its
flexibility in interconnecting mobile vehicles.
3. The satellite communication has the advantage of the quality of transmitted signals and the
location of Earth Stations. The sending and receiving information independent of distance.
4. Satellites can cover large areas of the Earth. This is particularly useful for sparsely populated
areas.

Disadvantages:
1. With the satellite in position the communication path between the terrestrial transmitter
and receiver is approximately 75000 km long.
2. There is a delay of ¼ sec between the transmission and reception of a signal because the
velocity of electromagnetic wave is 3* 10^5 km/second.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 61


3. The time delay reduces the efficiency of satellite in data transmission and long file transfer,
which carried out over the satellites.
4. Over-crowding of available bandwidth due to low antenna gains is occurred.
5. High atmosphere losses above 30 GHz limit the carrier frequency.

Transmission Impairments Terminology


In communication system, analog signals travel through transmission media, which tends to
deteriorate the quality of analog signal, which means that the signal at the beginning of the
medium is not the same as the signal at the end of the medium. The imperfection causes signal
impairment.
Terminology used in Transmission Impairments
Cable Type Description
Jitter Jitter is the variation in the time between data packets arriving, caused
by network congestion, or route changes. The longer data packets
take to transmit, the more jitter affects audio quality. The standard jitter
measurement is in milliseconds (ms). If receiving jitter is higher than 15-
20ms, it can increase latency and result in packet loss, causing audio
quality degradation.
Echo All media have a preferred termination condition for perfect transfer of
signal power. The signal arriving at the end of a transmission line should
be fully absorbed otherwise it will be reflected back down the line to
the sender and appear as an Echo. Echo Suppressors are often fitted to
transmission lines to reduce this effect.
Crosstalk Crosstalk is a disturbance caused by the electric or magnetic fields of
one telecommunication signal affecting a signal in an adjacent circuit. The
phenomenon that causes crosstalk is called electromagnetic interference
(EMI).
Distortion Distortion is change in shape of the signal. This type of distortion is
observed for the composite signals made by different frequencies. If the
medium is not perfect, then all the frequency components present at the
input will not only be equally attenuated and will not be proportionally
delayed.
Noise The random or unwanted signal that mixes up with the original signal is
called noise.
Bandwidth Bandwidth is the difference between the highest and lowest frequencies
that an analog communication system can pass as measured in Hertz
(Hz) or cycles per second.
Singing When the returning signal is repeatedly coupled back into the forward
path to produce oscillations, singing occurs.

62 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Networking Terminology
The business of networking is like any other technical discipline; it has a language of its own.
Part of the task of mastering the technology is to master the language used to describe that
technology. There are a number of specialized terms that describe computer networks. Some
terms often used with networks are explained below:

IP Address
IP address stands for internet protocol address; it is an identifying number that is associated with
a specific computer or computer network. When connected to the internet, the IP address
allows the computers to send and receive information.

Subnet Mask
A subnet mask is a 32 bits address used to distinguish between a network address and a host
address in IP address. A subnet mask identifies which part of an IP address is the network
address and the host address. Two types of subnet masks are:
The default Subnet Mask is the number of bits which is reserved by the address class. Using
this default mask will accommodate a single network subnet in the relative class.
A Custom Subnet Mask can be defined by an administrator to accommodate many network.

Gateway
Gateway is a network device that connects dissimilar networks with different protocols.
Gateways can translate data between different operating systems, between different email
formats, or between totally different networks. Gateways are most commonly used to transfer
data between private networks and the Internet.

MAC address
MAC address is a unique identifier that is assigned to a NIC (Network Interface Controller/
Card). It consists of a 48 bit or 64-bit address, which is associated with the network adapter.
MAC address can be in hexadecimal format. The full form of MAC address is Media Access
Control address.

Internet
The Internet is one of the most exciting and fastest growing applications of information
technology. Internet can be defined as a global network of over a million of smaller
heterogeneous computer networks. It is a network of networks that consists of millions of
private, public, academic, business, and government networks, of local to global scope, that
are linked by a broad array of electronic and optical networking technologies. The Internet
carries a vast range of information resources and services, such as the inter-linked hypertext
documents of the World Wide Web (WWW) and the infrastructure to support electronic mail.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 63


Intranet
Intranet is a private network within an organization that resembles the Internet. Like the public
Internet, intranets use browsers, web sites, and Web pages. Intranets typically provide e-mail,
mailing lists, newsgroups, and FTP services accessible only to those within the organization.
Organizations use intranets to provide information to their employees. Typical applications
include electronic telephone directories, e-mail addresses, employee benefit information,
internal job openings and much more.

Extranet
Extranet is a private network that uses Internet technology and the public telecommunication
system to connect more than one organization. Many organizations use Internet technologies
to allow suppliers and others limited access to their networks. The purpose is to increase
efficiency and reduce costs.

Networking Tools
A computer networking tool is any type of software that assists in the creation, maintenance,
or distribution of a network. Some of the networking tools are:

Packet Tracer
Packet Tracer is a cross-platform visual simulation tool designed by Cisco Systems that allows
users to create network topologies and imitate modern computer networks. The software
allows users to simulate the configuration of Cisco routers and switches using a simulated
command line interface. Packet Tracer makes use of a drag and drop user interface, allowing
users to add and remove simulated network devices as they see fit. The software is mainly
focused towards Certified Cisco Network Associate Academy students as an educational tool
for helping them learn fundamental CCNA concepts. Previously students enrolled in a CCNA
Academy program could freely download and use the tool free of charge for educational use.

Remote Login
Remote Login is a process in which user can login into remote site i.e. computer and use
services that are available on the remote computer. With the help of remote login a user is
able to understand result of transferring result of processing from the remote computer to the
local computer.

Network Connectivity Devices


Network devices are components used to connect clients to the network and assist in moving
data around a network in the most efficient manner. In some cases, network devices can boost
the data signal to increase the distance your data transmission can travel before they are so
degraded that they are unusuable at their destination. Some of the devices commonly used in
network connectivity are ethernet hub, network switch, repeaters, bridges, routers, gateway
and MODEM.
64 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
Network Interface Card ( NIC )
Network Interface Card (NIC) is a computer circuit board or
card that is installed in a computer so that it can be connected
to a network. Personal computers and workstations on
a Local Area Network (LAN) typically contain a network
interface card specifically designed for the LAN transmission
technology such as Ethernet or Token Ring. Network
Interface Card provides a dedicated, full-time connection to
a network. It boosts or amplifies the signal’s strength so it can
flow through the cables.

Network Switch
Network switch is a networking device that is used to segment networks into different
subnetworks called subnets or LAN segments. Segmenting the network into smaller subnets,
prevents traffic overloading in a network.The network switch functions as the traffic management
system within the network, directing data packets to the correct destination. These devices are
used to connect peripheral devices to the network and ensure maximum cost effectiveness
and the ability to share resources.

Router
Router is a network device that connects multiple networks that use the same protocol.
It forwards data packets from one network to another. Each data packet contains address
information that a router can use to determine if the source and destination are on the same
network, or if the data packet must be transferred from one network to another. It sends data
between networks by examining the network addresses contained in the packets they process.
It extracts the destination of a packet it receives, selects the best path to that destination, and
forwards data packets to the next device along this path.

MODEM
The word ‘MODEM’ stands for modulator-demodulator. Modulation
is the name of the process of converting from digital to analog.
Demodulation is the process of converting from analog to digital.
It is a device attached to the computer that converts or modulates
digital signals from a computer or other digital device to analog signals
and convert them into digital signals for the computer or any other
digital device. The sending modem modulates the data into a signal
that is compatible with the phone line, and the receiving modem
demodulates the signal back into digital data. Modems are generally
classified by the amount of data they can send in a given time, normally
measured in bits per second (bps).

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 65


OSI (Open System Interconnection) Model
OSI (Open Systems Interconnection) is reference model for how applications can communicate
over a network. A reference model is a conceptual framework for understanding relationships.
The purpose of the OSI reference model is to guide vendors and developers so the digital
communication products and software programs they create will inter-operate, and to facilitate
clear comparisons among communications tools.
Software/Upper Layers

Application To allow access to network resources

Presentation To translate, encrypt and compress data

Session To establish, manage, and terminate session

Heart of OSI Transport To provide reliable process to process message delivery and error delivery
Hardware/Lower Layers

Network To move packets from source to destination and to provide internet working

Data Link To organize bits into frame and to provide hop to hop delivery

Physical To transmit bits over a medium and to provide mechanical and electrical specifications

Physical Layer
The physical layer is the first layer of the Open System Interconnection Model (OSI Model).
The physical layer deals with bit-level transmission between different devices and supports
electrical or mechanical interfaces connecting to the physical medium for synchronized
communication. This layer plays with most of the network’s physical connections - wireless
transmission, cabling standards and types, connectors and types, network interface cards, and
more - as per network requirements. However, the physical layer does not deal with the
actual physical medium (like copper, fiber).

Data Link Layer


The data link layer is used for the encoding, decoding and logical organization of data bits. Data
packets are framed and addressed by this layer, which has two sub layers. The data link layer’s
first sub layer is the media access control (MAC) layer. It is used for source and destination
addresses. The MAC layer allows the data link layer to provide the best data transmission
vehicle and manage data flow control. The data link layer’s second sub layer is the logical link
control. It manages error checking and data flow over a network.

Network Layer
The network layer is the third level of the Open Systems Interconnection Model (OSI Model)
and the layer that provides data routing paths for network communication. Data is transferred
in the form of packets via logical network paths in an ordered format controlled by the network
layer. Logical connection setup, data forwarding, routing and delivery error reporting are the
network layer’s primary responsibilities.

66 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Transport layer
The transport layer is the layer in the open system interconnection (OSI) model responsible
for end-to-end communication over a network. It provides logical communication between
application processes running on different hosts within a layered architecture of protocols and
other network components. The transport layer is also responsible for the management of
error correction, providing quality and reliability to the end user. This layer enables the host
to send and receive error corrected data, packets or messages over a network and is the
network component that allows multiplexing.

Session Layer
In the Open Systems Interconnection (OSI) model, the session layer is the fifth layer, which
controls the connections between multiple computers. The session layer allows session
establishment between processes running on different stations.
It provides:
a. Session establishment, maintenance and termination: allows two application processes
on different machines to establish, use and terminate a connection, called a session.
b. Session support: performs the functions that allow these processes to communicate
over the network, performing security, name recognition, logging, and so on.

Presentation Layer
The presentation layer is layer 6 of the 7-layer Open Systems Interconnection (OSI) model.
It is used to present data to the application layer (layer 7) in an accurate, well-defined and
standardized format. The presentation layer is sometimes called the syntax layer.
The presentation layer provides:
a. Character code translation: for example, ASCII to EBCDIC.
b. Data conversion: bit order, integer-floating point, and so on.
c. Data compression: reduces the number of bits that need to be transmitted on the network.
d. Data encryption: encrypts data for security purposes. For example, password encryption.

Application Layer
The application layer is a layer in the Open Systems Interconnection (OSI) seven-layer model
and in the TCP/IP protocol suite. It consists of protocols that focus on process-to-process
communication across an IP network and provides a firm communication interface and end-
user services. The application layer serves as the window for users and application processes
to access network services.
This layer contains a variety of commonly needed functions:
a. Resource sharing and device redirection
b. Remote file access
c. Remote printer access

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 67


d. Inter-process communication
e. Network management
f. Directory services
g. Electronic messaging (such as mail)
h. Network virtual terminals

Internet Protocol Addressing


IP stands for “Internet Protocol,” which is the set of rules governing the format of data sent via
the internet or local network. An Internet Protocol address is also known as IP address. It is a
numerical label which assigned to each device connected to a computer network which uses
the IP for communication. IP addresses are the identifier that allows information to be sent
between devices on a network: they contain location information and make devices accessible
for communication. The internet needs a way to differentiate between different computers,
routers, and websites. IP addresses provide a way of doing so and form an essential part of
how the internet works.
Each IP address is a series of characters, such as ‘192.168.1.1’. Each IP packet will contain both
the IP address of the device or domain sending the packet and the IP address of the intended
recipient, much like how both the destination address and the return address are included on
a piece of mail.

Understanding IPv4 and IPv6


IPv4
IPv4 was the first version of IP. It was deployed for production in the ARPANET in 1983. Today
it is most widely used IP version. It is used to identify devices on a network using an addressing
system. The IPv4 uses a 32-bit address scheme allowing to store 2^32 addresses which is
more than 4 billion addresses. Till date, it is considered the primary Internet Protocol and
carries 94% of Internet traffic.

IPv6
IPv6 is the most recent version of the Internet Protocol. Internet Engineer Taskforce initiated
it in early 1994. The design and development of that suite is now called IPv6. This new IP
address version is being deployed to fulfill the need for more Internet addresses. It was aimed
to resolve issues which are associated with IPv4. With 128-bit address space, it allows 340
undecillion unique address space. IPv6 also called IPng (Internet Protocol next generation).

How to look up IP addresses


In Windows:
a. Use the command prompt.
b. Search for “cmd” (without the quotes) using Windows search
c. In the resulting pop-up box, type “ipconfig” (no quote marks) to find the information.

68 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concepts Review
Topic Key Concepts
Computer Network Computer network is a communication system connecting
two or more computers that work together to exchange
information and share resources.
The electromagnetic or light waves that transfer data from
one device to another device in encoded form are called
signals.
The process of changing some characteristics (amplitude,
frequency or phase) of a carrier wave in accordance with
the intensity of the signal is known as modulation.
Computer Network Models Computer network model is a design specifications for how
the nodes on a network interact and communicate.
Centralized computing network is a network model in
which a host computer connected to other computers or
terminals provide data or computing services via a network.
Client/server network is the workhorse of the network
world and consists of at least one server (with shared
resources) and the other computers on the network, called
clients, makes a service request from the server.
Peer-to-peer network is a network model in which
resource sharing, processing, and communications control
are completely decentralized.
Computer Network Local Area Network is a self-contained network that spans a
Categories small area, such as a single building, floor, or a room.
Metropolitan Area Network is a large computer network
that spans a metropolitan area or campus.
Wide Area Network is a telecommunications network,
usually used for connecting computers, that spans a wide
geographical area.
Topology for LAN A physical bus topology is a network topology in which all
the computers and peripheral devices are connected to a
common single cable called bus.
A physical ring topology is a network topology or circuit
arrangement in which each network node is attached along
the same signal path to two other devices, forming a path in
the shape of a ring.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 69


Topic Key Concepts
A physical star topology is a network topology where each
of the devices and computers on a network connect to one
central switch, hub or computer.
A tree topology is a type of network topology that includes
at least three specific levels in a topology hierarchy.
In a mesh network topology, each of the network node,
computer and other devices, are interconnected with one
another.
Communication Media Communication media refers to the mode of physical
connection needed for data transmission.
Guided (Bounded) media is any network media that travels
in a contained conductor.
Unbounded media uses a transmission carrier to send data
signals through the air instead of cables.

Transmission Impairments Jitter is the variation in the time between data packets arriving,
Terminology caused by network congestion, or route changes.
Crosstalk is a disturbance caused by the electric or magnetic fields
of one telecommunication signal affecting a signal in an adjacent
circuit.
The random or unwanted signal that mixes up with the original
signal is called noise.
Networking Terminology IP address stands for internet protocol address; it is an
identifying number that is associated with a specific computer
or computer network.
A subnet mask is a 32 bits address used to distinguish
between a network address and a host address in IP address.
Gateway is a network device that connects dissimilar
networks with different protocols.
MAC address is a unique identifier that is assigned to a NIC
(Network Interface Controller/ Card).
OSI Model and Internet OSI (Open Systems Interconnection) is reference model
Protocol Addressing for how applications can communicate over a network.
An Internet Protocol address is a numerical label which
assigned to each device connected to a computer network
which uses the IP for communication.
The IPv4 uses a 32-bit address scheme allowing to store
2^32 addresses which is more than 4 billion addresses.

70 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Section 1.1 (Very Short Questions)
a. What is data communication?
b. What is computer network?
c. What is data transmission? Name the two forms of data transmission.
d. What is centralized computing network?
e. Define the following terms: Jitter, Crosstalk and Distortion

Section 1.2 (Short Questions)


a. What is data communication? Mention the components of data communications.
b. List the importance of computer network.
c. What is the difference between client/server network and peer-to-peer network?
d. Explain the differences between LAN and WAN.
e. What is a network topology? What are the different types of physical topologies for LANs?

Section 1.3 (Long Questions)


a. What is modulation? Explain the three types of modulation.
b. Explain the differences between simplex mode communication and full duplex mode
communication.
c. What is a communication media? Explain the different types of communication media
used in computer network.
d. Write short notes on: Subnet Mask, Intranet and Packet Tracer.
e. What is OSI (Open Systems Interconnection)? Explain the different layers of OSI model?
f. What is Internet Protocol Addressing? Differentiate between IPv4 and IPv6.
Conduct an informal survey of at least 20 friends, relatives, neighbours, or
students in another class asking them what type of computer network they
use. Compile your results and create a table or chart in a word processor to
show the result.

Teaching Manual
While teaching this chapter, the key concepts that need to be emphasized upon include:
a. Concept of computer network, the advantages and disadvantages of computer network,
and the main components essential for the successful operation of a computer network.
b. The network categories and network models, the various types of communication media,
networking devices and concept of packet-switching.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 71
Chapter
Web
3 Technology

Concept
The World Wide Web (WWW) is the fastest growing part of the Internet. It is a collection
of billions of files stored on the millions of computers (called Web servers) all over the
world. These files represent text documents, pictures, video, sounds, programs, and
interactive environment. It is an information-sharing model that is built on top of the
Internet. The flow of information is controlled by a protocol. The protocol used in this
exchange is called Hypertext Transfer Protocol (HTTP). The World Wide Web has
gained popularity largely because it has a graphical interface and multimedia capabilities.
The World Wide Web was developed by British physicist and computer scientist Timothy
Berners-Lee as a project within the European Organization for Nuclear Research
(CERN) in Geneva, Switzerland.

72 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


The Internet
The Internet is one of the most exciting and fastest
growing applications of information technology.
This technology has not only changed the way
computers worked and the way people worked
with computers, but has also made a profound
impact on different areas, especially in those
of learning and communicating. It has shrunk
the world and brought people together. The
influence of this technology can be found in
almost every walk of life.
Internet can be defined as a global network of over a million of smaller heterogeneous
computer networks. It is a network of networks that consists of millions of private, public,
academic, business, and government networks, of local to global scope, that are linked by a
broad array of electronic and optical networking technologies. The Internet carries a vast range
of information resources and services, such as the inter-linked hypertext documents of the
World Wide Web (WWW) and the infrastructure to support electronic mail.

Uses of the Internet


Today individuals, companies, and institutions use the Internet in many ways as mentioned below:
a. The Internet allows to easily connect ordinary personal computers to share huge pool of
information.
b. Companies carry out electronic commerce (commerce on internet) including advertising,
selling, buying, distributing products and providing after sales services.
c. Businesses and institutions use the Internet for voice and video conferencing and other
forms of communication that enable people to telecommunicate, or work from a distance.
d. Individuals use the Internet for communication, entertainment, finding information, and to
buy and sell goods and services.
e. The use of electronic mail (e-mail) over the Internet has greatly speeded communication
between companies among coworkers, and between other individuals.
f. Media and entertainment companies use the Internet to broadcast audio and video,
including live radio and television programs. They also offer online chat groups, in which
people carry on discussions using written text, and online news and weather programs.
g. Scientists and scholars use the Internet to communicate with colleagues, to perform
research, to distribute lecture notes and course materials to students, and to publish
papers and article.
h. Educators are using the Internet for teaching and sharing our knowledge and experience
with the world.
i. Hundreds of websites help us in handling daily transactions, transfers, management, and
budget planning.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 73


History of Internet
The Internet originated from an experimental network called ARPANET created in 1969 by
the U.S. Department of Defence’s Advanced Research Projects Agency. It had a very modest
start and was limited to one computer located in California and three in Utah. The aim of
this network was to establish a computer network which could carry government as well as
military information and which could withstand adverse conditions such as nuclear attacks. It
was replaced by the NSFnet, which was run by the National Science Foundation. NSFnet
permitted universities and research agencies to link up with its supercomputers. Many private
companies built their own networks, which were later interconnected along with ARPANET
and NSFnet to form Internet. Today, the Internet connects computers all over the globe and
supplies information to people of all ages and interests.

How the Internet works?


The Internet is a network of interconnected communication lines that creates a sort of
highway system for transporting data. The main routes of the Internet are referred to as the
Internet backbone. In addition to the backbone, the Internet also consists of regional and
local communication links. These links can include local telephone systems, cable television
lines, cellular telephone systems and personal satellite dishes. The Internet’s communication
system transports data to and from millions of computers and other electronic devices.
Communication between all the different devices on the Internet is made possible by TCP/IP.
TCP/IP (Transmission Control Protocol/Internet Protocol) is the basic communication language
or protocol of the Internet. TCP/IP is a two-layer program. The higher layer, Transmission
Control Protocol, manages the assembling of a message or file into smaller packets that are
transmitted over the Internet and received by a TCP layer that reassembles the packets into
the original message. The lower layer, Internet Protocol, handles the address part of each
packet so that it gets to the right destination. Each gateway computer on the network checks
this address to see where to forward the message. Even though some packets from the same
message are routed differently than others, they will be reassembled at the destination.

PC

PC
t Host
Interne
TCP/IP
Serve
r
Router
Internet

PC

74 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Client Side Scripting and Server Side Scripting
Client side scripting
Web browsers execute client side scripting. It is used when browsers has all code. Source
code used to transfer from web server to user’s computer over internet and run directly on
browsers. It is also used for validations and functionality for user events.
It allows for more interactivity. It usually performs several actions without going to user. It
cannot be basically used to connect to databases on web server. These scripts cannot access
file system that resides at web browser. Pages are altered on basis of users choice. It can also
used to create “cookies” that store data on user’s computer.

Server side scripting


Web servers are used to execute server side scripting. They are basically used to create dynamic
pages. It can also access the file system residing at web server. Server-side environment that
runs on a scripting language is a web-server.
Scripts can be written in any of a number of server-side scripting language available. It is used
to retrieve and generate content for dynamic pages. It is used to require to download plugins.
In this load times are generally faster than client-side scripting. When you need to store and
retrieve information a database will be used to contain data. It can use huge resources of
server. It reduces client-side computation overhead. Server sends pages to request of user/
client.

Difference between Server Side Scripting and Client Side Scripting


Client Side Scripting Server Side Scripting
Source code is visible to user. Source code is not visible to user because it’s
output of server side is a HTML page.
It usually depends on browser and it’s version. In this any server side technology can be use
and it does not depend on client.
It runs on user’s computer. It runs on web server.
There are many advantages like response The primary advantage is it’s ability to highly
times and a more interactive application. customize, response requirements, access
rights based on user.

It does not provide security for data. It provides more security for data.

It is a technique use in web development in It is a technique that uses scripts on web


which scripts runs on clients browser. server to produce a response that is
customized for each clients request.
HTML, CSS and javascript are used. PHP, Python, Java, Ruby are used.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 75


Introduction to JavaScript
JavaScript is a scripting language used to create and control dynamic website content, i.e.
anything that moves, refreshes, or otherwise changes on your screen without requiring you to
manually reload a web page. JavaScript is very easy to implement because it is integrated with
HTML. It is open and cross-platform. It was created in 1995 by Brendan Eich while he was an
engineer at Netscape. It was originally going to be named LiveScript but was renamed. Unlike
most programming languages, the JavaScript language has no concept of input or output.
It is designed to run as a scripting language in a host environment, and it is up to the host
environment to provide mechanisms for communicating with the outside world. The most
common host environment is the browser.

Features of JavaScript
Some important features of JavaScript are:
a. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
b. JavaScript supports dynamic typing which means types of the variable are defined based
on the stored value. For example, if you declare a variable x then you can store either a
string or a Number type value or an array or an object. This is known as dynamic typing.
c. JavaScript is platform-independent which means that you can simply write the script once
and run it anywhere and anytime.
d. JavaScript is a prototype-based scripting language.
e. JavaScript is an interpreted language which means the script written inside javascript is
processed line by line.
Along with all these features, JavaScript provides the following useful features too:
i. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
ii. Extensive in-built library with many useful functions for validation, data type conversion,
string operations, etc.
iii. It is an object-centered language with Window Object being the most important
object in JavaScript and it also supports Polymorphism.
iv. Support for commonly used complex data types like array, Maps, List, etc. with
support of in-built functions to operate on them.

Limitations of JavaScript
JavaScript has some limitations which are given below:
a. Client-side JavaScript does not allow the reading or writing of files.
b. It cannot be used for networking applications because there is no such support available.
c. It does not have any multithreading or multiprocessor capabilities.

76 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Include JavaScript in HTML
The JavaScript code can be inserted in HTML file by using the HTML <script> tag. When an
HTML document is loaded with the <script> tag in the web browser, the browser processes
the content enclosed inside the script tag as JavaScript code.
The script tag can contain either scripting statements or refer to an external JavaScript file. The
script tag provides a src attribute that allows us to add a reference to an external script file.
JavaScript is the default scripting language for most of the browsers.
Syntax:
<script src=”JS_FILE_URL” type=”...”></script>
Similarly, we can use the <script> tag to directly add the JavaScript code too, like this:
<script type=”text/javascript”>
// JS code here
</script>

There are five attributes of script tag which are listed below in the table:
Attributes Values Description
async • true It specifies whether the script should be
• false executed asynchronously or not.
type • text/ECMAScript It specifies the Multipurpose Internet Mail
• text/javascript Extensions (MIME) type of script. Generally,
• application/ text/javascript value is used.
ECMAScript
• application/
javascript
• text/VBScript
charset charset It specifies the type of character encoding
used in the script
defer • true It specifies whether the browser continues
• false parsing the web page or not.

src URL It specifies the uniform source locator(URL)


of a file that contains the script.
JavaScript in HTML Webpage
You can use script tag inside an HTML web page to add JavaScript code in the following ways:
In the HEAD element (<head>...</head>)
In the BODY element (<body>...</body>)
To include an External JavaScript File
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 77
JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows:

Solved Example
<html>
<head>
<script type = “text/javascript”>
<!--
function sayHello() {
alert(“Hello World”)
}
//-->
</script> Output
</head> StartUp Computing

<body>
<input type = “button” onclick = “sayHello()” value = “StartUp Computing” />
</body>
</html>

JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, you would not have
any function defined using JavaScript.

Solved Example
<html>
<body>
<script type = “text/javascript”>
<!--
document.write(“Hello World”)
//-->
</script>
<p>StartUp Computing</p> Output
</body> StartUp Computing
</html>

78 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


JavaScript in <body> and <head> Sections
Scripts can be placed inside the body or the head section of an HTML page or inside both
head and body.

Solved Example
<html>
<head>
<script type = “text/javascript”>
<!--
function sayHello() {
alert(“Hello World”)
}
//-->
</script>
</head> Output
<body> Hello World Say Hello
<script type = “text/javascript”>
<!--
document.write(“Hello World”)
//-->
</script>
<input type = “button” onclick = “sayHello()” value = “Say Hello” />
</body>
</html>

JavaScript Code in External File


JavaScript can also be used as external files. JavaScript files have file extension .js . To use an
external script put the name of the script file in the src attribute of a script tag. External scripts
cannot contain script tags.

Solved Example
<!DOCTYPE html>
<html>
<center>
<body>
<h2>External JavaScript</h2>
<p id=”demo”>Startup Computing</p>
<button type=”button” onclick=”myFunction()”>Try it</button>
<script src=”myScript.js”></script>
</body>
<center>
</html>
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 79
JavaScript Data Types
JavaScript Data types are used to identify the type of data that is stored inside a variable during
the script execution. JavaScript broadly supports three types of data types. They are:
a. Primitive Type
b. Reference Type
c. Special Data Type

JavaScript Primitive Data Type


JavaScript Primitive data types can be classified further into the following types:
a. String Data Type
b. Boolean Data Type
c. Number Data Type
These are the most common data types, used for storing sequences of characters, true/false
and numeric values respectively.

The String Data Type


The string data type is used to represent textual data (i.e. sequences of characters). Strings are
created using single or double quotes surrounding one or more characters.

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript String Data Type</title>
</head>
<body>
<script>
// Creating variables
var a = ‘Hi there!’; // using single quotes
var b = “Hi there!”; // using double quotes

// Printing variable values


document.write(a + “<br>”);
document.write(b);
</script>
</body>
</html>

80 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


The Number Data Type
The number data type is used to represent positive or negative numbers with or without
decimal place, or numbers written using exponential notation e.g. 1.5e-4 (equivalent to
1.5x10-4).

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Number Data Type</title>
</head>
<body>
<script>
// Creating variables
var a = 25;
var b = 80.5;
var c = 4.25e+6;
var d = 4.25e-6;

// Printing variable values


document.write(a + “<br>”);
document.write(b + “<br>”);
document.write(c + “<br>”);
document.write(d);

JavaScript Boolean Data type


The boolean data type is used in conditional based programming. It can have two values,
either true or false.

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 81


Continued...
<title>JavaScript Boolean Data Type</title>
</head>
<body>
<script>
// Creating variables
var isReading = true; // yes, I’m reading
var isSleeping = false; // no, I’m not sleeping

// Printing variable values


document.write(isReading + “<br>”);
document.write(isSleeping);
</script>
</body>
</html>
JavaScript Composite Data types
These data types can hold collections of values and more complex entities. It is further divided
into Object, Array and Function.
a. Object data type
b. Array data type
c. Function data type

The Object Data Type


The object is a complex data type that allows you to store collections of data.
An object contains properties, defined as a key-value pair. A property key (name) is always a
string, but the value can be any data type, like strings, numbers, booleans, or complex data
types like arrays, function and other objects.

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Object Data Type</title>
</head>
<body>
<script>

82 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Continued...
var emptyObject = {};
var person = {“name”: “Raj”, “surname”: “Rai”, “age”: “36”};

// For better reading


var car = {
“modal”: “BMW X3”,
“color”: “white”,
“doors”: 5
}

// Print variables values in browser’s console


console.log(person);
console.log(car);
</script>
<p><strong>Note:</strong> Check out the browser console by pressing
the f12 key on the keyboard.</p>
</body>
</html>

The Array Data Type


An array is a type of object used for storing multiple values in single variable. Each value (also
called an element) in an array has a numeric position, known as its index, and it may contain
data of any data type-numbers, strings, booleans, functions, objects, and even other arrays.
The array index starts from 0, so that the first array element is arr[0] not arr[1].
The simplest way to create an array is by specifying the array elements as a comma-separated
list enclosed by square brackets

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Array Data Type</title>
</head>
<body>
<script>

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 83


<script>
// Creating arrays
var colors = [“Red”, “Yellow”, “Green”, “Orange”];
var cities = [“London”, “Paris”, “New York”];

// Printing array values


document.write(colors[0] + “<br>”); // Output: Red
document.write(cities[2]); // Output: New York
</script>
</body>
</html>

The Function Data Type


The function is callable object that executes a block of code. Since functions are objects, so it
is possible to assign them to variables.

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Function Data Type</title>
</head>
<body>
<script>
var greeting = function(){
return “Hello World!”;
}

// Check the type of greeting variable


document.write(typeof greeting) // Output: function
document.write(“<br>”);
document.write(greeting()); // Output: Hello World!
</script>
</body>
</html>

84 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


JavaScript Special Data types
JavaScript also has some special data types, although seeing function called as a data type would
have already been special for you. But there are two more.
a. Undefined Data type
b. Null Data type

The Undefined Data Type


The undefined data type can only have one value-the special value undefined. If a variable has
been declared, but has not been assigned a value, has the value undefined.

Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Undefined Data Type</title>
</head>
<body>
<script>
// Creating variables
var a;
var b = “Hello World!”

// Printing variable values


document.write(a + “<br>”);
document.write(b);
</script>
</body>
</html>

The Null Data Type


The Null data type is a special data type that can have only one value-the null value. A null
value means that there is no value. It is not equivalent to an empty string (“”) or 0, it is simply
nothing.
A variable can be explicitly emptied of its current contents by assigning it the null value.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 85


Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Null Data Type</title>
</head>
<body>
<script>
var a = null;
document.write(a + “<br>”); // Print: null

var b = “Hello World!”


document.write(b + “<br>”); // Print: Hello World!

b = null;
document.write(b) // Print: null
</script>
</body>
</html>

JavaScript Variable
A JavaScript variable is a name of storage location. There are two types of variables in JavaScript
: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
Correct JavaScript variables
var x = 10;
var _value=”sonoo”;

Incorrect JavaScript variables


var 123=30;
var *aa=320;

86 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Example of JavaScript variable
Let’s see a simple example of JavaScript variable.
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>

Solved Example
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>

JavaScript Local Variable


A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:

Solved Example
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 87


Continued...
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

<html>
<body>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
</body>
</html>

JavaScript Operators
Operators are used to perform operation on one, two or more operands. Operator is
represented by a symbol such as +, =, *, % etc. The operators supported by javascript are:
a. Arithmetic Operators
b. Comparison Operators
c. Logical (or Relational) Operators
d. Assignment Operators
e. Conditional (or ternary) Operators

Arithmetic Operators
The arithmetic operators supported by javascript are:

88 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Operator Description Example
+ Add two operands. 10 + 10 will give 20
- Subtract second operand from the first. 10 – 10 will give 0
* Multiply two operands. 10 * 30 will give 300
/ Divide numerator by denominator 10/10 will give 1
It is called modulus operator and gives remainder of the
% 10 % 10 will give 0
division.
++ Increment operator, increases integer value by one 10 ++ will give 11
-- Decrement operator, decreases integer value by one 10 – will give 9

Comparison Operators
The comparison operators supported by javascript are:

Operator Description Example


Checks if values of two operands are equal or not, If yes 10 == 10 will give
==
then condition becomes true. true
Not Equal to operator
10 !=10 will give
!= Checks if the value of two operands is equal or not, if false
values are not equal then condition becomes true.
Greater than operator
20 > 10 will give
> Checks if the value of left operand is greater than the value true
of right operand, if yes then condition becomes true.
Less than operator
10 < 20 will give
< Checks if the value of left operand is less than the value of true
right operand, if yes then condition becomes true.
Greater than or equal to operator
>= Checks if the value of left operand is greater than or 10 >=20 will give
equal to the value of right operand, if yes then condition false
becomes true.
Less than or equal to operator
<= Checks if the value of left operand is less than or equal to 10 <=20 will give
the value of right operand, if yes then condition becomes true.
true.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 89


Logical Operators
The logical operators supported by javascript are:

Operator Description Example


Logical AND operator returns true if both operands are 10 && 10 will give
&&
non zero. true.
Logical OR operator returns true If any of the operand is
|| 10 || 0 will give true.
non zero
Logical NOT operator complements the logical state of its ! (10 && 10) will give
!
operand. false.

Assignment Operators
The assignment operators supported by javascript are:
Operator Description Example
Simple Assignment operator C = A + B will assign
=
Assigns values from right side operands to left side operand. value of A + B into C
Add AND assignment operator
C += A is equivalent
+= It adds right operand to the left operand and assign the to C = C + A
result to left operand
Subtract AND assignment operator
C -= A is equivalent
-= It subtracts right operand from the left operand and assign to C = C - A
the result to left operand
Multiply AND assignment operator
C *= A is equivalent
*= It multiplies right operand with the left operand and assign to C = C * A
the result to left operand
Divide AND assignment operator
C /= A is equivalent
/= It divides left operand with the right operand and assign the to C = C / A
result to left operand
Modulus AND assignment operator
C %= A is equivalent
%= Modulus AND assignment operator, It takes modulus using to C = C % A
two operands and assign the result to left operand

Conditional Operator
Conditional operator is also called ternary operator, since it has three operands.
Operator Description Example
?: Conditional Expression If Condition is true? Then value X : Otherwise value Y

90 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


JavaScript Functions
Functions are one of the fundamental building blocks in JavaScript. JavaScript function is a block
of code designed to perform a particular task. In JavaScript, a function allows you to define a
block of code, give it a name and then execute it as many times as you want.

Benefits of using a Function


a. Function makes the code reusable. You can declare it once and use it multiple times.
b. Function makes the program easier as each small task is divided into a function.
c. Function increases readability.

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}

Solved Example
<!DOCTYPE html>
<html>
<body> Output
<h1>JavaScript function</h1> Hello World!
<script>
function ShowMessage() { OK
alert(“Hello World!”);
} JavaScript function

ShowMessage();
</script>
</body>
</html>

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 91


Control Structure
A control structure is like a block of programming that analyses variables and chooses a direction
in which to go based on given parameters. The control structure supported by javascript are:
a. if … else
b. if...else if
b. switch case
c. do while loop
d. while loop
d. for loop

if … else Statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.

Syntax:
if (expression){
Statement(s) to be executed if expression is true
}

Solved Example
<script type=”text/javascript”>
<!--
var age = 20;
if( age > 18 ){
document.write(“<b>Qualifies for driving</b>”);
}
//-->
</script>

if...else if Statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.

92 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Solved Example
<html>
<head>
<script type=”text/javascript”>
var one = prompt(“Enter the first number”);
var two = prompt(“Enter the second number”);
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + “ is equal to “ + two + “.”);
else if (one<two)
document.write(one + “ is less than “ + two + “.”);
else
document.write(one + “ is greater than “ + two + “.”);
</script>
</head>
<body>
</body>
</html>

switch case Statement


The switch statement evaluates an expression, matching the expression’s value to a case
clause, and executes statements associated with that case, as well as statements in cases that
follow the matching case.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 93


Syntax:
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

Solved Example
<script type=”text/javascript”>
<!--
var grade=’A’;
document.write(“Entering switch block<br/>”);
switch (grade) {
case ‘A’: document.write(“Good job<br/>”);
break;
case ‘B’: document.write(“Pretty good<br/>”);
break;
case ‘C’: document.write(“Passed<br/>”);
break;
case ‘D’: document.write(“Not so good<br/>”);
break;
case ‘F’: document.write(“Failed<br/>”);
break;
default: document.write(“Unknown grade<br/>”)
}
document.write(“Exiting switch block”);
//-->
</script>

94 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


do while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax:
do{
Statement(s) to be executed;
} while (expression);

Solved Example
<script type=”text/javascript”>
<!--
var count = 0;
document.write(“Starting Loop” + “<br/>”);
do{
document.write(“Current Count : “ + count + “<br/>”);
count++;
}while (count < 0);
document.write(“Loop stopped!”);
//-->
</script>

This will produce following result:


Starting Loop
Current Count : 0
Loop stopped!

while Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 95


Syntax:
while (expression){
Statement(s) to be executed if expression is true
}

Solved Example
<script type=”text/javascript”>
<!--
var count = 0;
document.write(“Starting Loop” + “<br/>”);
while (count < 10){
document.write(“Current Count : “ + count + “<br/>”);
count++;
}
document.write(“Loop stopped!”);
//-->
</script>

This will produce following result:


Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

96 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


for Loop
The for loop is the most compact form of looping and includes the following three important
parts:
a. The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
b. The test statement which will test if the given condition is true or not. If condition is true,
then code given inside the loop will be executed otherwise loop will come out.
c. The iteration statement where you can increase or decrease your counter.
Syntax:
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}

Solved Example
<script type=”text/javascript”>
<!--
var count;
document.write(“Starting Loop” + “<br/>”);
for(count = 0; count < 10; count++){
document.write(“Current Count : “ + count );
document.write(“<br/>”);
}
document.write(“Loop stopped!”);
//-->
</script>

This will produce following result which is similar to while loop:


Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 97


Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

Object Definition
You define (and create) a JavaScript object with an object literal:

Solved Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id=”demo”></p>
<script>
// Create an object:
var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
// Display some data from the object:
document.getElementById(“demo”).innerHTML =
person.firstName + “ is “ + person.age + “ years old.”;
</script>
</body>
</html>
Object Properties
The name:values pairs in JavaScript objects are called properties.

Property Property Value


firstName John
lastName Doe
age 50
eyeColor blue

98 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName[“propertyName”]

Solved Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>There are two different ways to access an object property.</p>
<p>You can use person.property or person[“property”].</p>
<p id=”demo”></p>
<script>

// Create an object:
var person = {
firstName: “Raj”,
lastName : “Rai”,
id : 5566
};
// Display some data from the object:
document.getElementById(“demo”).innerHTML =
person.firstName + “ “ + person.lastName;
</script>
</body>
</html>

Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 99


Property Property Value
firstName Raj
lastName Rai
age 50
eyeColor blue
fullName function() {return this.firstName + “ “ + this.lastName;}

Solved Example
var person = {
firstName: “Raj”,
lastName : “Rai”,
id : 5566,
fullName : function() {
return this.firstName + “ “ + this.lastName;
}
};

The this Keyword


In a function definition, this refers to the “owner” of the function.
In the example above, this is the person object that “owns” the fullName function.
In other words, this.firstName means the firstName property of this object.

Accessing Object Methods


You access an object method with the following syntax:
objectName.methodName()

Solved Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>
<p id=”demo”></p>

100 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


<script>
// Create an object:
var person = {
firstName: “Raj”,
lastName : “Rai”,
id : 5566,
fullName : function() {
return this.firstName + “ “ + this.lastName;
}
};
// Display data from the object:
document.getElementById(“demo”).innerHTML = person.fullName();
</script>
</body>
</html>

Do Not Declare Strings, Numbers, and Booleans as Objects


When a JavaScript variable is declared with the keyword “new”, the variable is created as an
object:
var x = new String(); // Declares x as a String object
var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object

JavaScript Events
HTML events are “things” that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can “react” on these events.

HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
a. An HTML web page has finished loading.
b. An HTML input field was changed.
c. An HTML button was clicked.
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 101


JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
<element event=’some JavaScript’>
With double quotes:
<element event=”some JavaScript”>
In the following example, an onclick attribute (with code), is added to a <button> element

Solved Example
<!DOCTYPE html>
<html>
<body>
<button onclick=”document.getElementById(‘demo’).innerHTML=Date()”>The
time is?</button>
<p id=”demo”></p>
</body>
</html>

Common HTML Events


Some common HTML events are:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
What can JavaScript Do?
Event handlers can be used to handle and verify user input, user actions, and browser actions:
a. Things that should be done every time a page loads
b. Things that should be done when the page is closed
c. Action that should be performed when a user clicks a button
d. Content that should be verified when a user inputs data
e. And more ..

102 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Many different methods can be used to let JavaScript work with events:
a. HTML event attributes can execute JavaScript code directly
b. HTML event attributes can call JavaScript functions
c. You can assign your own event handler functions to HTML elements
d. You can prevent events from being sent or being handled
e. And more ...

JavaScript Form Validation


HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the
form from being submitted.

Solved Example
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms[“myForm”][“fname”].value;
if (x == “”) {
alert(“Name must be filled out”);
return false;
}
}
</script>
</head>
<body>
<form name=”myForm” action=”/action_page.php” onsubmit=”return
validateForm()” method=”post”>
Name: <input type=”text” name=”fname”>
<input type=”submit” value=”Submit”>
</form>
</body>
</html>

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 103


JavaScript Can Validate Numeric Input
JavaScript is often used to validate numeric input:
Please input a number between 1 and 10.

Solved Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Can Validate Input</h2>
<p>Please input a number between 1 and 10:</p>
<input id=”numb”>
<button type=”button” onclick=”myFunction()”>Submit</button>
<p id=”demo”></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id=”numb”
x = document.getElementById(“numb”).value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = “Input not valid”;
} else {
text = “Input OK”;
}
document.getElementById(“demo”).innerHTML = text;
}
</script>

</body>
</html>

104 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being submitted:

Solved Example
<!DOCTYPE html>
<html>
<body>
<form action=”/action_page.php” method=”post”>
<input type=”text” name=”fname” required>
<input type=”submit” value=”Submit”>
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>

Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
a. has the user filled in all required fields?
b. has the user entered a valid date?
c. has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
a. Constraint validation HTML Input Attributes
b. Constraint validation CSS Pseudo Selectors
c. Constraint validation DOM Properties and Methods

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 105


Constraint Validation HTML Input Attributes
Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element

Constraint Validation CSS Pseudo Selectors


Selector Description
:disabled Selects input elements with the “disabled” attribute specified

:invalid Selects input elements with invalid values

:optional Selects input elements with no “required” attribute specified

:required Selects input elements with the “required” attribute specified


:valid Selects input elements with valid values

Concept of jQuery
jQuery is a lightweight, “write less, do more”, JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
The jQuery library contains the following features:
a. HTML/DOM manipulation
b. CSS manipulation
c. HTML event methods
d. Effects and animations
e. AJAX
f. Utilities

106 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Why jQuery?
There are lots of other JavaScript libraries out there, but jQuery is probably the most popular,
and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
a. Google
b. Microsoft
c. IBM
d. Netflix

jQuery Syntax:
The jQuery syntax is tailor-made for selecting HTML elements and performing some action
on the element(s).
Basic syntax is: $(selector).action()
a. A $ sign to define/access jQuery
b. A (selector) to “query (or find)” HTML elements
c. A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$(“p”).hide() - hides all <p> elements.
$(“.test”).hide() - hides all elements with class=”test”.
$(“#test”).hide() - hides the element with id=”test”.

Server Side Scripting Using PHP


Server-side scripts are discrete blocks of program code that execute on a web server (as
opposed to a web client) computer. They are generally used to create dynamic web pages.
This means that the page displayed to the user does not exist as a document on the server
in its own right, and is only brought into existence in response to a user request. Often, a
server-side script provides the interface between a web-based user interface and a database
that resides on a web server. PHP is a server side scripting language used to create dynamic
web pages. PHP is well suited for web development. PHP stands for Hypertext Preprocessor.
It is an interpreted language.It is embedded in HTML. It is an open source language. PHP was
created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is the latest
version of PHP, which was released on 28 November.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 107


Some important points need to be noticed about PHP are as followed:
a. PHP stands for Hypertext Preprocessor.
b. PHP is an interpreted language, i.e., there is no need for compilation.
c. PHP is faster than other scripting languages, for example, ASP and JSP.
d. PHP is a server-side scripting language, which is used to manage the dynamic content of
the website.
e. PHP can be embedded into HTML.
f. PHP is an object-oriented language.
g. PHP is an open-source scripting language.

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.
a. It handles dynamic content, database as well as session tracking for the website.
b. You can create sessions in PHP.
c. It can access cookies variable and also set cookies.
d. It helps to encrypt the data and apply validation.
e PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many
more.
f. Using PHP language, you can control the user to access some pages of your website.
g. As PHP is easy to install and set up, this is the main reason why PHP is the best language
to learn.
h. PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user.

PHP Features
PHP is very popular language because of its simplicity and open source. Some of the important
features of PHP are:

Performance
PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.

Open Source
PHP source code and software are freely available on the web. You can develop all the versions
of PHP according to your requirement without paying any cost. All its components are free to
download and use.

108 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Familiarity with syntax
PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded
PHP code can be easily embedded within HTML tags and script.

Platform Independent
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.

Database Support
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting
PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language


PHP allows us to use a variable without declaring its datatype. It will be taken automatically at
the time of execution based on the type of data it contains on its value.

Web Servers Support


PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft
IIS, etc.

Security
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.

Control
Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.

A Helpful PHP Community


It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 109


Object Oriented Programming with Server Side Scripting
PHP is a server-side scripting language, mainly used for web development but also used as
a general-purpose programming language. Object-Oriented Programming (PHP OOP), is
a type of programming language principle added to php5, that helps in building complex,
reusable web applications. The Object-Oriented Programming concepts are:
a. Class and Objects
A class represents a group of similar objects. Object has properties and behaviour. A class
is a way to bind the data describing an entity and its associated functions together.

b. Encapsulation
Encapsulation refers to wrapping up data and associated functions into one single unit.
The main purpose of encapsulation is to:
Reduce software development complexity-by hiding the implementation details and only
exposing the operations, using a class becomes easy.
Protect the internal state of an object-access to the class variables is via methods such as
get and set, this makes the class flexible and easy to maintain.
The internal implementation of the class can be changed without worrying about breaking
the code that uses the class.

c. Inheritance
Inheritance is the procedure in which one class inherits the attributes and methods of
another class. The class whose properties and methods are inherited is known as the
Parent class. And the class that inherits the properties from the parent class is the Child
class. The main purpose of inheritance is;
Re-usability-a number of children, can inherit from the same parent. This is very useful
when we have to provide common functionality such as adding, updating and deleting
data from the database.

d. Polymorphism
Polymorphism is an object-oriented programming concept that refers to the ability of
a variable, function or object to take on multiple forms. In a programming language
exhibiting polymorphism, class objects belonging to the same hierarchical tree (inherited
from a common parent class) may have functions with the same name, but with different
behaviors.

OOPs Concepts in PHP


PHP is an object oriented scripting language; it supports all of the above principles. The above
principles are achieved via:
Encapsulation - via the use of “get” and “set” methods etc.
Inheritance - via the use of extends keyword
Polymorphism - via the use of implements keyword

110 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Basics of PHP
Setting up the environment
To run PHP a web development environment is needed.This needs a PHP compatible web
server and interpreter. Packages like WAMP, LAMP, XAMPP, etc can be used which includes a
web server.

Writing the code and running the script


PHP scripts are plain text. A PHP script begins with <?PHP and ends with ?>. The PHP code
is saved with extension .PHP and is saved in the root directory of web server.
The syntax of PHP tag is given below:
<?php
//your code here
?>

Embedding HTML and PHP


PHP codes are embedded in HTML document using the <?PHP and ?> tags.

Comments in PHP
Comments are used to make code more readable. There are two types of comments-Single
line and Multi-line comments. A single line comment starts with // while multi-line comment
begins with /* and ends with */ .

Output statements in PHP


There are two methods for displaying statements in PHP, by using
a. echo and print
Both echo and print are used to display result(Statements). The echo and print statement
can be used with or without parentheses.

b. Var_dump ( )
The var_dump ( ) function is used to display data type and value of a variable.

File: first.php
<!DOCTYPE>
<html>
<body>
<?php
echo “<h2>Hello First PHP</h2>”;
?>
</body>
</html>

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 111


PHP Case Sensitivity
In PHP, keyword (e.g., echo, if, else, while), functions, user-defined functions, classes are not
case-sensitive. However, all variable names are case-sensitive.
In the below example, you can see that all three echo statements are equal and valid:
<!DOCTYPE>
<html>
<body>
<?php
echo “Hello world using echo </br>”;
ECHO “Hello world using ECHO </br>”;
EcHo “Hello world using EcHo </br>”;
?>
</body>
</html>

Output:
Look at the below example that the variable names are case sensitive. You can see the example
below that only the second statement will display the value of the $color variable. Because it
treats $color, $ColoR, and $COLOR as three different variables:
<html>
<body>
<?php
$color = “black”;
echo “My car is “. $ColoR .”</br>”;
echo “My dog is “. $color .”</br>”;
echo “My Phone is “. $COLOR .”</br>”;
?>
</body>
</html>

Output:
Notice: Undefined variable: ColoR in D:\xampp\htdocs\program\p2.php on line 8
My car is
My dog is black
Notice: Undefined variable: COLOR in D:\xampp\htdocs\program\p2.php on line 10
My Phone is
Only $color variable has printed its value, and other variables $ColoR and $COLOR are
declared as undefined variables. An error has occurred in line 5 and line 7.

112 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
a. String
b. Integer
c. Float (floating point numbers - also called double)
d. Boolean
e. Array
f. Object
g. NULL
h. Resource

PHP String
A string is a sequence of characters, like “Hello world!”.
A string can be any text inside quotes. You can use single or double quotes:

Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = “Hello world!”;
$y = ‘Hello world!’;

echo $x;
echo “<br>”;
echo $y;
?>

</body>
</html>

PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
a. An integer must have at least one digit
b. An integer must not have a decimal point
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 113
c. An integer can be either positive or negative
d. Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or
binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:

Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5985;
var_dump($x);
?>

</body>
</html>

PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:

Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = 10.365;
var_dump($x);
?>

</body>
</html>

114 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in
a later chapter of this tutorial.

PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:

Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array(“Volvo”,”BMW”,”Toyota”);
var_dump($cars);
?>

</body>
</html>

PHP Object
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.

Let’s assume we have a class named Car. A Car can have properties like model, color, etc.
We can define variables like $model, $color, and so on, to hold the values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 115


Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
class Car {
public $color;
public $model;
public function _construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return “My car is a “ . $this->color . “ “ . $this->model . “!”;
}
}

$myCar = new Car(“black”, “Volvo”);


echo $myCar -> message();
echo “<br>”;
$myCar = new Car(“red”, “Toyota”);
echo $myCar -> message();
?>

</body>
</html>

116 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:

Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = “Hello world!”;
$x = null;
var_dump($x);
?>

</body>
</html>

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
a. A variable starts with the $ sign, followed by the name of the variable
b. A variable name must start with a letter or the underscore character
c. A variable name cannot start with a number
d. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
e. Variable names are case-sensitive ($age and $AGE are two different variables)

Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 117


Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$txt = “Asia.com”;
echo “I love $txt!”;
?>

</body>
</html>

PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
a. Arithmetic operators
b. Assignment operators
c. Comparison operators
d. Increment/Decrement operators
e. Logical operators
f. String operators
g. Array operators
h. Conditional assignment operators

PHP Arithmetic Operators


The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication, etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y’th power

118 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.

Assignment Same as... Description


x=y x = y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are
of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they
are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to


equal to $y
<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y
to
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, depending on if $x is less
than, equal to, or greater than $y.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 119


PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators


PHP has two operators that are specially designed for strings.

Operator Name Example Result


. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Array Operators


The PHP array operators are used to compare arrays.

120 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Operator Name Example Result
+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same key/


value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of the
same types
!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y


!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result


?: Ternary $x = expr1 ? expr2 : Returns the value of $x.
expr3 The value of $x is expr2 if expr1 =
TRUE.
The value of $x is expr3 if expr1 =
FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or is NULL,
the value of $x is expr2.
Introduced in PHP 7
Variable Manipulation in PHP
Variable manipulation is a method of specifying or editing variables in a computer program. PHP
supports all the basic mathematical operations of any programming language, including addition
and multiplication as well as a wide range of trigonometric and logarithmic functions. Beyond
mathematical manipulations, PHP supports an even greater amount of string manipulation
functions.
PHP supports all the common mathematical standards for operator precedence, groupings,
and so on for both integers and floating-point numbers.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 121


For instance, performing simple mathematics in PHP can be accomplished as follows:
<?php
$answer = 5 + 4; /* $answer now equals 9 */
$answer = $answer - 5; /* $answer now equals 4 */
$answer = $answer / 2; /* $answer now equals 2 */
$answer = 1/3; /* $answer is now 0.333333 */
$answer = ((5 + 4)*2) % 7; /* $answer now equals 4 */
?>

PHP also supports a form of shorthand.


<?php
$answer = 5; /* Assign Original value */
$answer += 2; /* Equivalent to: $answer = $answer + 2; */
$answer *= 2; /* Answer is now 14 */
$answer %= 5; /* Answer is now 4 */
?>

There is even a shorter shorthand for the common task of adding 1 or subtracting 1 from a
variable. To add one to a variable or “increment” use the “++” operator:
<?php
$answer++; /* Increment $answer by 1 */
$answer--; /* Decrement $answer by 1 */
++$answer; /* Increment by 1, (see note) */
?>

Along with simple mathematics, PHP also supports trigonometric and logarithmic operations
for advanced calculations in the following fashion:
<?php
$cos = cos(2 * M_PI); /* cos of 2*PI is 1 */
?>

Database Connectivity
The database is one of the important components of any programming language. To deal
with a dynamic project and data management, we need to have a database. PHP supports
various kinds of database connections with it. MySQL is one of the most widely used relational
databases, and it is mostly used with PHP as well. Considering the term database connection
in PHP, MySQL itself have various way to make connections in an application to play with the
database operations. After making the connection of PHP-MYSQL, we can do various things
like – insertion of records, deletion of records, updating the records, etc.

122 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


MySQL Connection Using PHP Script
PHP provides mysql_connect() function to open a database connection. This function takes
five parameters and returns a MySQL link identifier on success or FALSE on failure.
Syntax:
connection mysql_connect(server,user,passwd,new_link,client_flag);
Sr.No. Parameter & Description
1. server Optional − The host name running the database server. If not specified,
then the default value will be localhost:3306.
2. user Optional − The username accessing the database. If not specified, then the
default will be the name of the user that owns the server process.
3. passwd Optional − The password of the user accessing the database. If not
specified, then the default will be an empty password.
4. new_link Optional − If a second call is made to mysql_connect() with the same
arguments, no new connection will be established; instead, the identifier of
the already opened connection will be returned.
5. client_flags Optional − A combination of the following constants −
MYSQL_CLIENT_SSL − Use SSL encryption.
MYSQL_CLIENT_COMPRESS − Use compression protocol.
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of
inactivity before closing the connection.
You can disconnect from the MySQL database anytime using another PHP function mysql_
close(). This function takes a single parameter, which is a connection returned by the mysql_
connect() function.

Syntax:
bool mysql_close ( resource $link_identifier );
If a resource is not specified, then the last opened database is closed. This function returns true
if it closes the connection successfully otherwise it returns false.
Solved Example
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = ‘localhost:3306’;
Approved by Curriculum Development Center
$dbuser = ‘guest’; Asia’s Start Up Computing - Book 12 123
$dbpass = ‘guest123’;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die(‘Could not connect: ‘ . mysql_error());
}
echo ‘Connected successfully’;
mysql_close($conn);
?>
</body>
</html>

Syntax:
Here is a generic SQL syntax to create a MySQL table:
CREATE TABLE table_name (column_name column_type);
Now, we will create the following table in the TUTORIALS database.
create table tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT,
tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( tutorial_id )
);

Here, a few items need explanation:


a. Field Attribute NOT NULL is being used because we do not want this field to be NULL.
So, if a user will try to create a record with a NULL value, then MySQL will raise an error.
b. Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available
number to the id field.
c. Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple
columns separated by a comma to define a primary key.

Creating Tables from Command Prompt


It is easy to create a MySQL table from the mysql> prompt. You will use the SQL command
CREATE TABLE to create a table.

124 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
root@host# mysql -u root -p
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> CREATE TABLE tutorials_tbl(
-> tutorial_id INT NOT NULL AUTO_INCREMENT,
-> tutorial_title VARCHAR(100) NOT NULL,
-> tutorial_author VARCHAR(40) NOT NULL,
-> submission_date DATE,
-> PRIMARY KEY ( tutorial_id )
-> );
Query OK, 0 rows affected (0.16 sec)
mysql>

NOTE : MySQL does not terminate a command until you give a semicolon (;) at the end of
SQL command.

Creating Tables Using PHP Script


To create new table in any existing database you would need to use PHP function mysql_
query(). You will pass its second argument with a proper SQL command to create a table.

Solved Example
<html>
<head>
<title>Creating MySQL Tables</title>
</head>

<body>
<?php

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 125


Solved Example
$dbhost = ‘localhost:3036’;
$dbuser = ‘root’;
$dbpass = ‘rootpassword’;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die(‘Could not connect: ‘ . mysql_error());
}
echo ‘Connected successfully<br />’;
$sql = “CREATE TABLE tutorials_tbl( “.
“tutorial_id INT NOT NULL AUTO_INCREMENT, “.
“tutorial_title VARCHAR(100) NOT NULL, “.
“tutorial_author VARCHAR(40) NOT NULL, “.
“submission_date DATE, “.
“PRIMARY KEY ( tutorial_id )); “;
mysql_select_db( ‘TUTORIALS’ );
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die(‘Could not create table: ‘ . mysql_error());
}
echo “Table created successfully\n”;
mysql_close($conn);
?>
</body>
</html>

Select Data With MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests
table and displays it on the page:

Solved Example
<!DOCTYPE html>
<html>
<body>

<?php

126 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}

$sql = “SELECT id, firstname, lastname FROM MyGuests”;


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo “<br> id: “. $row[“id”]. “ - Name: “. $row[“firstname”]. “ “ .
$row[“lastname”] . “<br>”;
}
} else {
echo “0 results”;
}

$conn->close();
?>

</body>
</html>

Explanation:
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into
an associative array that we can loop through. The while() loop loops through the result set
and outputs the data from the id, firstname and lastname columns.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 127
Solved Example
<!DOCTYPE html>
<html>
<body>

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}

$sql = “SELECT id, firstname, lastname FROM MyGuests”;


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo “id: “ . $row[“id”]. “ - Name: “ . $row[“firstname”]. “ “ . $row[“lastname”].
“<br>”;
}
} else {
echo “0 results”;
}

mysqli_close($conn);
?>

</body>
</html>

128 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Getting Data From MySQL Database
Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP
function mysql_query. You have several options to fetch data from MySQL.
The most frequently used option is to use function mysql_fetch_array(). This function returns
row as an associative array, a numeric array, or both. This function returns FALSE if there are
no more rows.

Solved Example
<?php
$dbhost = ‘localhost:3036’;
$dbuser = ‘root’;
$dbpass = ‘rootpassword’;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die(‘Could not connect: ‘ . mysql_error());
}

$sql = ‘SELECT emp_id, emp_name, emp_salary FROM employee’;


mysql_select_db(‘test_db’);
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die(‘Could not get data: ‘ . mysql_error());
}

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {


echo “EMP ID :{$row[‘emp_id’]} <br> “.
“EMP NAME : {$row[‘emp_name’]} <br> “.
“EMP SALARY : {$row[‘emp_salary’]} <br> “.
“--------------------------------<br>”;
}

echo “Fetched data successfully\n”;

mysql_close($conn);
?>

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 129


Concepts Review
Topic Key Concepts
Concept of Web Technology The World Wide Web (WWW) is the fastest growing part
of the Internet.
World Wide Web (WWW) is a collection of millions of files
stored on thousands of computers (called Web servers) all
over the world.
Internet can be defined as a global network of over a million
of smaller heterogeneous computer networks.
The Internet originated from an experimental network
called ARPANET created in 1969 by the U.S. Department
of Defence’s Advanced Research Projects Agency.
Introduction to JavaScript JavaScript is a lightweight, interpreted programming
language.
JavaScript supports dynamic typing which means types of
the variable are defined based on the stored value.
The JavaScript code can be inserted in HTML file by using
the HTML <script> tag.
JavaScript Data types are used to identify the type of data
that is stored inside a variable during the script execution.
Control structure controls the flow of execution of a
program.
Data validation is the process of ensuring that user input is
clean, correct, and useful.
Concept of JQuery jQuery is a lightweight, “write less, do more”, JavaScript
library.
The purpose of jQuery is to make it much easier to use
JavaScript on your website.
The jQuery syntax is tailor-made for selecting HTML
elements and performing some action on the element(s).
Concept of PHP PHP is an open-source, interpreted, and object-oriented
scripting language that can be executed at the server-side.
PHP is a server-side scripting language, which is used to
design the dynamic web applications with MySQL database.
PHP provides mysql_connect() function to open a database
connection.

130 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Section 1.1 (Very Short Questions)
a. What is the Internet?
b. What is JavaScript?
c. What is a JavaScript variable?
d. What is an operator?
e. What is PHP?

Section 1.2 (Short Questions)


a. How does the Internet work?
b. List the important features of JavaScript.
c. How do you include JavaScript in HTML? Name the five attributes of script tag.
d. Define three types of data types in JavaScript with examples.
e. What are the rules while declaring a JavaScript variable?
f. Explain the operators supported by Javascript.
g. What is a control structure? Name the control structure supported by Javascript.
h. Write the function and syntax of the following control structure.
If … else, Switch case, Do while Loop, For Loop
i. What is jQuery? Write the syntax of jQuery.
j. What are the data types supported by PHP? Explain with examples.
k. What is PHP variable? What are the rules for naming PHP variables?

Section 1.3 (Long Questions)


a. Explain the brief the history of the Internet.
b. Explain the differences between Server Side Scripting and Client Side Scripting.
c. Explain the uses of PHP.
d. Explain the features of PHP.
e. What is PHP operator? Explain the different categories of operators supported by PHP.
f. Explain MySQL Connection Using PHP Script with example.

In the Lab
1. Write a JavaScript code block using arrays and generate the current data in
words, this should include the day, the month and the year.
The output should be as follows, Sunday, August 08,1999
2. Write a JavaScript code block, which checks the contents entered in a form’s Text
element. If the text entered is in the lower case, convert to upper case. Make use
of function to Uppercase().

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 131


3. Create a web page which accepts user information and user comments on the
web site. Design the web page using form elements and check if all the Text fields
have being entered with data else display an alert. Obtain an output as shown in
the diagrams.

INFONET SERVICES

First Name
Last Name
E-mail Address
Address
City
State Postal Code Country
Please choose the most appropriate statement

Please choose the most appropriate statement


I regularly purchase items online
I have on occasion purchased items online
I have not purchased anything online, but I would consider it
I prefer to shop in real stores

I’m interested in (choose all that apply)

Hiking
Mountain Biking
Camping
Rock Climbing
Off-Road 4WD
Cross-country Skiing
I learned about this site from
Print Ads

132 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Camping
Rock Climbing
Off-Road 4WD
Cross-country Skiing
I learned about this site from
Print Ads
Comments
Please type any comments here

Submit Start Over

PROJECT SPECIFICATIONS
Since the learning of JavaScript has now been completed, it is time to consolidate this
learning by building a small guest book.
A Guest Book is used to store any comments that a visitor to the site may have
regarding the site. The comments (if applicable) help improve the functionality of the
site.
The structure of the guest book is given in the following pages along with html source
code. This is a description of how the guest book will be used by the person signing-
in. The Java script code working with Html which provides for various client side data
capture validations.
The guest book is a html document with
Simple visuals in the form of .gif .jpeg files.
Java Script embedded HTML code.
The files required to construct these pages is available on the accompanying CD-ROM
for immediate use.
If required run the HTML files first in a web browser and get a look and feel of what
the project could be like. Once this is done, code the web pages according to what you
believe is appropriate.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 133


For a visitor to leave comments about the site, or comments in general, the HTML
form used in diagram 1 is used. This is the guest book page.
This form captures the following:
Visitors Name (Not compulsory)
Emailid (Mandatory)
A visitors Comments (Mandatory)

Silicon Chip Technologies


OUR GUEST BOOK
Please take a few moments to let us know you were here today.

Please Give Us Your Name

Please Give Us Your Email Address

Bouquets Or Brickbats Are Welcome

Can we contact you with information about our products or services.

Yes NO,Thanks!

Submit Reset About

Thank You For Stopping By Our Web Site

Each HTML file is really just a simple guideline to what the web page could look like.
Java script is added to perform simple client side validations.
For your guidance:
The source code is provide in the document file.
Client Side Validations:
The Client side validations to be coded in Java script are as follows
Emailid, General Comments, cannot be left empty
The Emailid needs to be scanned for the presence an ‘@’ and ‘.’ symbol.
The length of the Name and Emailid fields cannot exceed 30 characters.

134 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Chapter
Programming
in
4 C-Language

Concept
C is a general-purpose, block structured, procedural computer programming language
developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the
Unix operating system. C gained more popularity in programming environment because
it is reliable, simple and easy to use. C stands between high level language and low level
language. That is why it is called a middle level language. It provides low-level access to
memory, provides language constructs that map efficiently to machine instructions and
require minimal run-time support. The C program can be compiled for a very wide
variety of computer platforms and operating systems with minimal change to its source
code. The language has become available on a very wide range of platforms, from
embedded micro controllers to supercomputers.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 135


Definition and Features of C-Program
C is a high-level and general purpose programming language that is ideal for developing
firmware or portable applications. Originally intended for writing system software, C was
developed at Bell Labs by Dennis Ritchie for the Unix Operating System (OS) in the early
1970s. C belongs to the structured, procedural paradigms of languages. It is proven, flexible
and powerful and may be used for a variety of different applications. Although high-level, C and
assembly language share many of the same attributes.
C-Language is a programming language widely used for systems programming. It exhibits the
following specific characteristics:
a. Fixed number of keywords, including a set of control primitives, such as if, for, while,
switch and do while.
b. Multiple logical and mathematical operators, including bit manipulators.
c. Multiple assignments may be applied in a single statement.
d. Function return values are not always required and may be ignored if unneeded.
e. Typing is static. All data has type but may be implicitly converted.
f. Basic form of modularity, as files may be separately compiled and linked.
g. Control of function and object visibility to other files via extern and static attributes.

Advantages of C-Program
C Language has a list of advantages due to this it is very much popular language around the
world and best suitable for the programmer to learn at the first stage of the programming.
1. C language is a building block for many other currently known languages. C language has
variety of data types and powerful operators. Due to this, programs written in C language
are efficient, fast and easy to understand.
2. C is highly portable language. This means that C programs written for one computer can
easily run on another computer without any change or by doing a little change.
3. There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several
standard functions are available which can be used for developing programs.
4. Another important advantage of C is its ability to extend itself. A C program is basically
a collection of functions that are supported by the C library this makes us easier to add
our own functions to C library. Due to the availability of large number of functions, the
programming task becomes simple.
5. C language is a structured programming language. This makes user to think of a problem
in terms of function modules or blocks. Collection of these modules makes a complete
program. This modular structure makes program debugging, testing and maintenance
easier.
6. C programming language has a low level of abstraction. It is close enough to system
hardware descriptions.

136 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Disadvantages of C-Program
1. C programming language does not support Object Oriented Programming (OOP)
features such as inheritance, encapsulation and polymorphism.
2. C language is a procedure oriented language. So, you should develop your program using
procedure oriented language only and you have to implement any algorithms as a set of
function calls.
3. C programming language does not offer support for namespace like C++. Without
Namespace, we can’t declare two variables of same name and you can’t use the same
variable name again in one scope.
4. C language doesn’t perform Run Time Type Checking. It compiles time type checking
only at run time. C language doesn’t ensure whether correct data type is used instead it
performs automatic type conversion.
5. C language doesn’t have the concept of constructor or destructor. It does not offer the
object oriented feature. So, it does not have Constructor and Destructor features.

Structure of C-Program
Every C-program has an anatomy. Unlike human anatomy, the parts of C programs are not
always in the same place. C-programs have parts and components that serve specific purposes.
A C program basically consists of the following parts:
a. Preprocessor commands
b. Functions
c. Variables
d. Statements and Expressions
e. Comments

Solved Example
#include <stdio.h>
int main()
{
/* my first program in C */
printf(“Hello, World! \n”);
Program Output
return 0; Hello, World!
}

Let us take a look at the various parts of the above program:


1. The first line of the program #include <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 137


2. The next line int main() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program. .
4. The next line printf(...) is another function available in C which causes the message “Hello,
World!” to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.

Compile and Execute C Program


Let us see how to save the source code in a file, and how to compile and run it. Following are the
simple steps:
1. Open a text editor and develop the program (source code).
2. Select a suitable file name under which you would like to Source Code
store the program.
3. Create the program in the computer and save it under
filename you have decided. This file is known as source code Compiler
file.
4. Compile the source code. The file containing the translated
code is called object code. If there are any errors, debug Object Code
them and compile the program again.
5. Link the object code with library code that are required for Other object
codes Libraries
execution. Linker
6. The resulting code is called executable code. If there are
errors in linking, correct them and compile the program again.
7. Debug the program, if any errors are found in the output. Executable Code
8. Go to step 4 and repeat the process again.
C Preprocessor
The C preprocessor is a program that is called into operation before the actual code begins. The
preprocessor will look through the source code and when necessary, it will modify the source
code. Once that is done it will return the modified code to the compiler. The Preprocessor
looks through the program trying to find out specific instructions called Preprocessor directives
that it can understand. All Preprocessor directives begin with the # (hash) symbol and do not
require any semicolon at the end.
A set of commonly used preprocessor directives are:
Directive Function
#define To define values or macros that are used by the preprocessor
to manipulate the program source code before it is compiled.
#include Causes the contents of another file to be inserted into the
program.

138 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Header Files and their Purpose
C has several header files which have a file extension “h”. These header files contain predefined
functions that carry out specific tasks. The programmer can include these header files in the
program and then use the functions that are defined in it as part of the program.
The basic syntax of using these header files is:
#include <file> or #include “file”
Some of the header files are given below:
Name Function
stdio.h Input/Output Functions

conio.h console input/output

math.h Mathematics Functions

string.h String Functions

time.h Date and Time Functions

a. What is C program? What are the features of C program?


b. List the advantages and disadvantages of C program.
c. Explain C compilation process with diagram.
d. What is a preprocessor? Explain its types.
e. What is a header file? List any three header files with their functions.

Fundamentals of C-Program
Character Set
Character set is a set of valid characters that a language can recognize. C uses the uppercase l
etters A to Z, the lower case letters a to z, the digit 0 to 9 and certain special characters( +,-
,*,!,=,&,?,>,<,{,},[],,:. ..etc)as building blocks to form basic program elements.

Comments
Comments are notes of explanation that document lines or sections of a program. Comments
are part of the program, but the compiler ignores them. They are intended for people who
may be reading the source code.
Comments can be written in two forms:
a. // Single Line Comments
b. /Block Comment......................
................................................/
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 139
Tokens, Keywords and Identifiers
The smallest unit of a C program coding is known as token. All programming languages have
a set of elements that together make up a program. The different types of C tokens are
keywords, identifiers, constants, operators, strings and special symbols.

Keywords
‘C’ keywords are words which have special meaning for the compiler. They are used for some
special purposes. These are also known as reserved word, which means these words cannot
be used as identifiers.
The following table is the complete list of the C keywords. All the keywords are in lowercase
characters.
C Keywords
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while

Identifiers
Identifiers are the names that are used to identify the programming elements included by the
programmer. It is a requirement of all programming languages where the programmer has to
include items like variables, functions, classes, arrays, etc., and each one of these are given a
unique name by the programmer which are used to identify them. Following are the rules that
are applicable in C.
a. A keyword cannot be used as a variable/identifier name.
b. Only alphabets, digits and underscore can be used in the names. No special character
other than underscore is permitted in the identifier names.
c. An identifier name cannot start with a digit.
d. Upper-case alphabets are distinct from lower-case alphabets.

Identifier Legal or Illegal?


dayOfweek Legal
3dGraph Illegal. Variable names cannot begin with a digit.
_employee_num Legal
Illegal. Variable names may only use alphabets, letters, digits or
Mixture#3
underscores.

140 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Data Types
Data type is an instruction that is used to declare the category or type of variables being used
in the program. The language usually specifies the range of values for a given data type, how
the values are processed by the computer, and how they are stored. C language supports two
different type of data types:

Primary data types


The basic fundamental of data having unit feature on C programming is called primary data
type. These are the origin of declaration data within C programming language. These are
fundamental data types in C namely integer (int), floating point(float), character(char) and void.

Data Type Byte Range

char 1 0 to 255
unsigned char 1 0 to 255
int 2 −32,768 to 32,767
unsigned int 2 0 to 65,535
short int 2 −32,768 to 32,767
long int 4 -2,147,483,648 to 2,147,483,647
unsigned short int 2 0 to 65,535
unsigned long int 4 0 to 4,294,967,295
float 4 1.2E-38 to
double 8 2.2e-308 to
long double 10 3.4E-4932 to 1.1E+49352
void 0 0

Derived data types


Derived data types are nothing but primary data types but a little twisted or grouped together
like array, structure, union and pointer. These are discussed in details later.

Variables
Variable is the most fundamental part of any language. It is a named location in the memory
that is used to store a value during a program execution. It has a name and a value. Each
variable has a type that determines what you can store in it. The information stored in variables
may change while the program is running.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 141


Rules for naming variables in C-Language:
The C-Language defines certain rules for naming variables. You must name variables according
to these rules; otherwise, your program will not compile.
a. Variable name must begin with a letter or an underscore (’_’), which may be followed by
a sequence of letters, digits (0-9), or “_”.
b. Variable names must be unique.
c. ‘C’ keywords should not be used as variable names.
d. Both upper case and lower case letters are permitted.
e. The name of a variable needs to be without any embedded space.

Variable Definition
The definition of a variable causes memory to be allocated to it. The general format is:
Data type variable name, variable name
For example,
a. int a;
b. char firstname;

Variable Initialization
The process of assigning an initial value to a variable is known as initialization of variable. A
variable is allocated a value either at the time of its definition or anywhere in the program after
its definition and before its use. Assignment operator is used to initialize values to variables.
The general format is:
Data type variable name=value;
or
Data type variable name;
variable name = value;

Declaration of an array variable


Array variable must be followed by a pair of square brackets with positive number for its size.
Syntax:
Data type variable name[size];
Examples:
char text[20];
There are three basic places in a C program to declare variables. They are
a. Local variables are declared inside a function. They are unknown to other functions.
b. Global Variables are declared outside of any function. They may be accessed by expression
of any function.
c. Arguments of function are declared after the function name and before the opening brace
of a function.
Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
142
Constants
Constant is a value that do not change during the execution of a program. It is often referred
to as literals.
The C-Language provides several different kinds of constants:
Integer constant
Integer constant is a whole number without any fractional part. It may contain + or -sign. A
number with no sign is assumed to be positive. Commas cannot appear in an integer constant.
For example,
• int n=200

Real constant
Real constant is a number having fractional parts. It may also have either + or - sign preceding
it. A real constant with no sign is assumed to be positive.
For example,
• float n=125.60;

Character constant
Character constant is a constant which can be assigned with a single character. It is enclosed
in single quotes.
For example,
• char ch=’p’;

String constant
String constant is a set of characters enclosed within double quotes. All the characters of a
string can be stored in sequential locations in memory.
For example,
• char str[10]

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn’t represent itself
when used inside string literal or character. It is composed of two or more characters starting
with backslash \. Table below shows a list of common escape or sequence.
Escape Sequence Legal or Illegal?
\a Alarm or Beep
\b Backspace
\n New Line
\r Carriage Return
\t Horizontal tab

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 143


Types of Specifier
Format specifiers can be defined as the operators which are used in association with printf()
function for printing the data that is referred by any object or any variable. Format specifiers
start with a percentage % operator and followed by a special character for identifying the type
of data.

Format Specifier Description


%d Integer Format Specifier
%f Float Format Specifier
%c Character Format Specifier
%s String Format Specifier
%u Unsigned Integer Format Specifier
%ld Long Int Format Specifier

a. What is a variable? How does it differ from constant?


b. List any five escape sequence constants.

Statement
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input. A computer program is made up of a
series of statements. There are two types of statements in C language. They are:

Simple Statement
A simple statement is a basic part of program. It consists of an expression followed by a
semicolon. The execution of a simple statement causes the expression to be evaluated. For
example:
float pi, r, a;
pi=3.141;
r=5

Compound Statement
Compound statement is combination of several expression statements. Compound Statement
is Enclosed within the Braces { }. Compound statement is also called as block statement. For
example:
{
int a=10,b=20,c;
c = a + b;
printf(“value of C is : %d n”,c);
}
144 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
Concepts Review
Topic Key Concepts
Fundamentals of C-Program C is a high-level and general purpose programming language
that is ideal for developing firmware or portable applications.
C-Language is a programming language widely used for
systems programming.
Character set is a set of valid characters that a language can
recognize.
‘C’ keywords are words which have special meaning for the
compiler.
Variable is a named location in the memory that is used to
store a value during a program execution.
Constant is a value that do not change during the execution
of a program.
Integer constant is a whole number without any fractional
part. It may contain + or -sign.
Real constant is a number having fractional parts. It may also
have either + or - sign preceding it. A real constant with no
sign is assumed to be positive.
Character constant is a constant which can be assigned with
a single character.
String constant is a set of characters enclosed within double
quotes.

a. What is C-program? What are the characteristics of C-program?


b. Define C-preprocessor. State the functions of preprocessor directives.
c. What are the important elements of C programming?
d. What are C keywords? Give examples.
e. What is a variable? How does it differ from constant?
f. What rules are followed while naming the variables?
g. What are the different types of constants in C programming?
h. What is a statement? What are the two types of statements?

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 145


Operators
C-Language provides a rich operator environment. Operators are special symbols that
are meant for specific-tasks or operations. The value or variable on which the operation
is performed is called operand. The operators provided by C programming language are
classified under different categories. They are: Arithmetic operators, Arithmetic assignment
operators, Unary operators, Relational operators, Logical operators and Ternary operator.

Arithmetic operators
Arithmetic operators are the operators that are used for manipulating arithmetic data and
perform arithmetic operations. C programming provides five basic arithmetic operators. They
are addition, subtraction, multiplication, division and modulus, which are +, -, *, / and %
respectively. These operators work on all the data types. Each operator requires at least two
values called operands. The following table lists the arithmetic operators:
Operator Meaning Example
+ Addition s=a+b
- Subtraction s=a-b
* Multiplication s=a*b
/ Division s=a/b
% Modulo division s=a%b
Relational operators
Relational operator is used to evaluate and compare two values of the same type, either both
numeric or both string. The result of comparison is either TRUE or FALSE. This result can
then be used to make decision regarding program flow. The relational operators used in C
programming are:

Operator Meaning Example


== Equal to a == b
< Less than a<b
> Greater than a>b
<= Less than or equal to a <= b
>= Greater than or equal to a >= b
!= Not equal to a !=b
Assignment operator
Assignment operator is represented by the symbol ‘=’. The assignment operator takes the
value on the right side and stores it in the variable on the left side. The syntax is as follows:
x <operator>=y

146 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Operator Meaning Example
= Assignment x=y
+= Add to x+=y
-= Subtract from x-= y
*= Multiply by x*=y
/= Divided by x/=y
%= Modulo by x%=y
Unary operators
The unary operators operate on one operand-variable or constant. C-Language supports two
important operators called increment and decrement operators or unary operators.
Operator Meaning Example
Increases the value of the
++ x++
operand
Increases the value of the
-- x--
operand
Logical operators
Logical operators connect two or more relational expressions into one, or reverse the logic
of an expression. These values can be used to make decisions about program flow. The
commonly used logical operators in C-Language are:
Operator Meaning Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a
Rules of logical operators
a. && operator connects two expressions into one. Both expressions must be true for the
overall expression to be true.
b. || connects two expressions into one. One or both expressions must be true for the
overall expression to be true. It is only necessary for one to be true, and it does not
matter which.
c. ! operator reverses the “truth” of an expression. It makes a true expression false, and a
false expression true.

a. Define operators. What are the different classes of operators?

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 147


Conditional operator
Conditional operator is also called ternary arithmetic operator as it takes three operands. It
provides a “shorthand” method of expressing a simple if/else statement. The operator consists
of the question-mark (?) and the colon (:). The general format is:
expression ? expression : expression;
For example:
x < 0 ? y = 10 : z = 20;
The statement above is called a conditional expression and consists of three sub-expression
separated by the ? and : symbols. The expressions are x<0, y=10, and z=20, as illustrated
below:
x<0 ? y=10 : z=20;
Note: Since it takes three operands, the conditional operator is considered a ternary operator.

Comma operator
Comma operator is special kind of operator which is widely used in programming to separate
the declaration of multiple variable. Comma operator returns the value of the right-most
operand when multiple comma operators are used inside an expression. Comma operator
has lowest precedence i.e it is having lowest priority so it is evaluated at last.
For example:
total=(a=5, b=10, a+b);
The value 5 is assigned to a and 10 is assigned to b and finally 15 is assigned to total.

The Sizeof operator


The sizeof operator is the most common operator in C. It is a compile-time unary operator
and used to compute the size of its operand. It returns the size of a variable. It can be applied
to any data type, float type, pointer type variables.

Solved Example
#include <stdio.h>
int main() {
int a = 16;
printf(“Size of variable a : %d\n”,sizeof(a));
printf(“Size of int data type : %d\n”,sizeof(int));
return 0;}

Program Output:
Size of variable a : 4
Size of int data type : 4
148 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
Precedence and Associativity
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left. Let’s understand the precedence by the example given below:
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).
The precedence and associativity of C operators is given below:

Category Operator Associativity


Postfix () [] -> Left to right
Unary ++ - - Right to left
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |=

Comma , Left to right

Expressions
An expression is a combination of variables constants and operators written according to
the syntax of C language. In C every expression evaluates to a value i.e., every expression
results in some value of a certain type that can be assigned to a variable. Some examples of C
expressions are shown in the table given below.

Algebraic Expression Expression in C


a+bxc a+b*c
(a+b+c)d (a+b+c)*d
axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 149


Type Casting and Conversion
Typecasting is converting one data type into another one. It is also called as data conversion
or type conversion. It is one of the important concepts introduced in ‘C’ programming.‘C’
programming provides two types of type casting operations: Implicit type casting and Explicit
type casting.

Implicit Type casting


Implicit type casting means conversion of data types without losing its original meaning. This
type of typecasting is essential when you want to change data types without changing the
significance of the values stored inside the variable.
Implicit type conversion happens automatically when a value is copied to its compatible data
type. During conversion, strict rules for type conversion are applied. If the operands are of
two different data types, then an operand having lower data type is automatically converted
into a higher data type.

Solved Example
#include<stdio.h>
int main()
{
short a=10; //initializing variable of short data type
int b; //declaring int variable
b=a; //implicit type casting
printf(“%d\n”,a);
printf(“%d\n”,b);
}

Program Output:
10
10
Explicit Type casting
The type conversion which is enforced by the programmer is called explicit type conversion.
Basically, the programmer forces an expression to be of a specific type.
The general format of explicit type conversion is as follows:
(type-name) expression
Here,
The type name is the standard ‘C’ language data type.
An expression can be a constant, a variable or an actual expression.

150 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
#include<stdio.h>
int main()
{
float a = 1.2;
//int b = a; //Compiler will throw an error for this
int b = (int)a + 1;
printf(“Value of a is %f\n”, a);
printf(“Value of b is %d\n”,b);
return 0;
}

Program Output:
Value of a is 1.200000
Value of b is 2

Introduction to Library Functions


The C library functions are provided by the system and stored in the library. The C library
function is also called an inbuilt function in C programming. To use Inbuilt Function in C, you
must include their respective header files, which contain prototypes and data definitions of the
function.
Library Functions Meaning
tolower() Converts alphabet to lowercase
toupper() Converts to lowercase alphabet
cos() Computes the cosine of an argument
Computes the exponential raised to the
exp()
argument
Computes natural logarithm of an
log()
argument
pow() Computes power of a number
sin() Compute sine of a number
sqrt() Computes square root of a number
tan() Computes tangent
strcat() Concatenates two strings
strlen() Calculates the length of a string
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 151
Concepts Review
Topic Key Concepts
C-Program Operators Operators are special symbols that are meant for specific-
tasks or operations.
Arithmetic operators are the operators that are used
for manipulating arithmetic data and perform arithmetic
operations.
Relational operator is used to evaluate and compare two
values of the same type, either both numeric or both string.
The unary operators operate on one operand-variable or
constant.
Logical operators connect two or more relational
expressions into one, or reverse the logic of an expression.
Conditional operator is also called ternary arithmetic
operator as it takes three operands.
Comma operator is special kind of operator which is widely
used in programming to separate the declaration of multiple
variable.
The sizeof operator is a compile-time unary operator and
used to compute the size of its operand.
The precedence of operator species that which operator
will be evaluated first and next.

a. What are arithmetic operators? Name the arithmetic operators used in C programming.
b. What is unary operators? What are the two types of unary operators used in C
programming?
c. What is a logical operator? State the rules of logical operators.
d. What are increment and decrement operators?
e. How is prefix increment/ decrement operator different from postfix increment/decrement
operators?
f. What is type casting? Explain its types.

152 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concept of Library and User-Defined Function
Functions are the building blocks of C language and the place where all program activities
occurs. It is a collection of statements that performs a specific task. It can be invoked from
the other parts of the program and should return a value. It groups a number of program
statements into a single unit.
Every function has its own name, and when that name is encountered, the execution of the
program branches to the body of that function. When the function returns, execution resumes
on the next line of the calling function.
Functions come in two varieties: library functions and user defined functions.
a. Library functions are the functions that performs a specific task and are predefined in a
programming language. These functions are ready made, available to the programmer to
use without declaring or defining them. They are also called built-in functions. printf and
scanf belong to the category of library function.
b. User defined functions are the functions created by the user at the time of writing a
program. main is an example of user-defined function. In order to make use of a user-
defined function, we need to establish three elements that are related to functions.
i. Function definition
ii. Functional call
iii. Function declaration

Advantages of Functions
The advantages of a function are:
a. A function breaks up a program into a small and manageable unit.
b. A user-defined function helps to divide a program into a number of parts, which makes it
easier to understand a program.
c. If the same task has to be performed in several places in a program, a function can be
written and executed whenever it is needed. So, it reduces the size of a program.
d. The use of functions saves a programmer the problem of debugging a program that does
not function properly.

Need for user-defined function


a. User-defined function helps to divide a program to a number of parts, which makes easy
to understand a program.
b. Function reduces the size of a program because we can call a function whenever we
require it.
c. It is easy to find the errors and to debug them.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 153


Syntax:
Type_specifier Function_name(arguments)
Parameter declaration;
{
body of function;
}
Type Specifier : Specifies the type of data return by the function. The type specifier is
not compulsory, if it is missing function returns int type of data.

Arguments : Arguments of a function are data receives by the function when
function called from another part of a program.

Body of function : It may consists of one or more statements.

Outline of function
Header files
:
:
//Functions declaration or Prototype
void function1();
void function2();
:
:
main()
{
//calling functions1()
function1();
//calling function2()
function2();
……………………………………..
……………………………………..
:
:
}
//function definition
{
body of the function
…………………………………
…………………………………
}

154 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
Design a program to create a function to find out the sum of two numbers which are supplied
from the keyboard.
Solution :
#include<stdio.h>
// function to find sum of two numbers
float addition(float num1, float num2)
{
// declare variable
float sum;
// calculate sum value
sum = num1 + num2;
// return result
return sum;
}
int main()
{
// declare variables
float number1, number2, result;
// take input
printf(“Enter two number: “);
scanf(“%f %f”,&number1, &number2);
// find addition of two numbers
result = addition(number1, number2);
// display result
printf(“%.2f + %.2f = %.2f\n”,
number1, number2, result); Program Output:
return 0; Enter two number: 12.3 6.5
} 12.30 + 6.50 = 18.80

a. Write a program to calculate area of a triangle, whose sides are input by users by using
functions.
b. Write a program to print the greatest number between two numbers using functions.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 155


Using Functions
A selection statement selects among a set of statements depending on the value of a controlling
expression. Selection statements enable the computer to decide upon which of the several
possible actions to take

a. Function Declaration
C does not allow to use user defined function without telling to the compiler. So, it is
necessary to declare a function to inform the compiler that the function would use in
the later point. Generally function is declared at the beginning of the program. Function
declaration includes function name, arguments and their types and return type of
data. In the above given sample program void sum(); declares sum() function without
arguments.
void sum();
keyword void specifies that the function sum() does not return any value to the calling
program.

b. Calling a Function
A function can be called from the main program using function name followed by
arguments or without arguments ends with semicolon. When function name ends without
semicolon, compiler will understand that the function being defined. When function is
called, control transferred to the called function, executes statements of functions and
again program control will transfer to the next statement of the function call. In the above
program, sum(); statement calls the sum() function.
Main()
{
Sum();// calls sum() function
After executing the block of statements of sum() function, program control will transfer to the
statement printf(“Returned from the function”);

c. Function Arguments
Function Arguments means data passes from the calling function to the called function.
Argument may be passed as a value or reference.

d. Function Definition
Function definition contains the actual codes for the program. Body of the function follows
function declarator. Name of function declarator and name of function declaration should
be same with the same arguments and same return data type. Main difference between
function declaration and function declarator is that function declaration Is terminated with
semicolon but function declarator is terminated without semicolon. In the above sample

156 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program function definition is:
void sum() //function declarator
{
int a;
int b;
int t;
printf(“Enter value of A”);
scanf(“%d”,&a);
printf(“Enter value of B”);
scanf(“%d”,&b);
t=a+b;
printf(“Sum is %d\n\n”,t);
}

Body of Function

Solved Example
Design a program to create a function named sum(int,int) to pass two numbers as an argument
and find the sum.
Solution:
/* Calling a function with argument*/
# include <stdio.h>
# include <math.h>
void sum(int,int);//function declaration or prototyping with arguments
main()
{
printf(“Example of calling function\n”);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 157


Continued...
sum(15,10); //calling sum function
printf(“Returned from the function”);
}
//Function definition
void sum(int a,int b)
{
int t;
t=a+b;
printf(“Value of A = %d\n”,a);
printf(“Value of B =%d\n”,b);
printf(“Sum is %d\n\n”,t);
}

Program Explanation
In the above program, function void sum(int,int) is declared with two arguments written
within parenthesis. Arguments means data passes from the calling function to the called
function. Argument may be passed as a value or reference. For example sum(int,int)
means integer types of data passes to the sum() function from the calling function. When
the sum() function is called from the main(), constant values 15 and 10 passes to the
sum() function and stores in variables a and b respectively. sum() function prints value of
a, b and their sum. sum() does not return any value to the main() function.
Program Output
Example of calling function
Value of A = 15
Value of B = 10
Sum is 25
Returned from the function

a. Write a program to increase the salary of an employee using function.


b. Write a program using function to input the radius of circle and print its area using the
formula-2*22/7*r*r. The function should receive the radius as argument and should return
the calculated area.
c. Write a program to check user input number is even or odd by using function.
d. Write a program using function to find out factorial of any number.

158 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
Design a program to create a function named sum(int,int) to pass two numbers as an argument
and return a sum to the calling function.
Solution :
# include <stdio.h>
# include <math.h>
sum(int,int);//function declaration or prototyping
main()
{
int tot;
printf(“Example of calling function\n”);
tot= sum(15,10);
printf(“Returned from the function\n\n”);
printf(“Sum is %d\n\n”,tot);
}
//Function definition
sum(int a,int b)//function declarator
{
int t;
printf(“Value of A = %d\n”,a);
printf(“Value of B =%d\n”,b);
t=a+b;
return(t) /* t returns sum of a and b through t and store in tot*/
}

Program Explanation
In the above program, function sum() is called with arguments 15 and 10. Arguments
passes to the sum() function and stores in variable a and b respectively. sum() function
will print the value of a and b. Expression t=a+b; will find out the sum of a and b then
return(t) statement will return the value of t to the calling function main() and stores in
variable tot. So, in this program sum of a and b will print by variable tot at the main()
function.
Program Output
Example of calling function
Value of A =15
Value of B =10
Returned from the function
Sum is 25
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 159
Arguments Passed by Value
A process of passing value of variables is known as call by value. When arguments are passed
by value, the called function creates a new copy of variable of the same type as the arguments
and copies the arguments values into it. The changes made to the parameters of the called
function have no effect on the variables used to call the function.

Solved Example
# include <stdio.h>
# include <conio.h>
void change(int,int);//function declaration or prototyping
void main()
{
int a=15;
int b=20;
clrscr();//to clear the screen
printf(“Before calling function\n”);
printf(“Value of a=%d\n”,a);
printf(“Value of b=%d\n”,b);
printf(“After function called\n”);
change(a,b);
printf(“After returning from function\n”);
printf(“Value of a =%d\n”,a);
printf(“Value of b =%d\n”,b);
}
//Function definition
void change(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf(“Value of a =%d\n”,a);
printf(“Value of b =%d\n”,b);
}

160 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
The above program initialized value of a=15 and value of b=20. Before calling the function
change(), it prints value of a and b at the main() function. After printing change(a,b);
statement called the function change() by call by value method. When the function is
called by call by value method, called function creates copies of argument passed to the
function, so changes made in variables of called function will not affect on the variable of
calling function. In the above program, values swapping is done between a and b in the
function change(). So, function prints value of a=20 and value of b=15. After printing the
program, the control flow transferred to the statement after the function call prints the
original value of a and b.
Program Output
Before calling function
Value of a=15
Value of b=20
After function called
Value of a=20
Value of b=15
After returning from function
Value of a=15
Value of b=20

Note:
From the above program we will understand that when function is called by value the
called function creates a new copy of variable of the same type (it does not use original
variables of calling function) and copies the argument values into it. The changes made to
the variables of the function will not effect on the variables of calling function.

a. Write a program to print multiplication table of n numbers using function.


b. Write a program to print reverse of a number using function.
c. Write a program to input a number and check whether it is odd or even.

Arguments Passed by Reference


A process of passing addresses to a function is known as call by reference. When arguments are
passed by reference, the address of each argument is copied to the argument of the function.
The changes made to the parameter of the function will effect on the variables used at the
calling function because called function can access the original variables of the calling function.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 161


Solved Example
Design a program to create a function named sum(int,int) to pass two numbers as an argument
and return a sum to the calling function.
Solution :
/* Function called by reference*/
# include <stdio.h>
# include <conio.h>
void change(int &,int &);//function declaration with data type with address operator
(&)
main()
{
int a=15;
int b=20;
clrscr();//to clear the screen
printf(“Before calling function\n”);
printf(“Value of A=%d\n”,a);
printf(“Value of B=%d\n”,b);
printf(“After function called\n”);
change(a,b);//function called with passing reference
printf(“After returning from function\n”);
printf(“Value of A =%d\n”,a);
printf(“Value of B =%d\n”,b);
}
//Function definition
void change(int &a, int &b)
{ int t;
t=a;
a=b;
b=t;
printf(“Value of A =%d\n”,a);
printf(“Value of B =%d\n”,b);
}

162 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
From the above program we will understand that when function is called by reference the
called function receives addresses not the values. So, the changes made to the variables
of the called function will effect on the value of the variables of calling function. Following
output will clears the concept of arguments passed by reference.

Program Output
Before calling function
Value of A=15
Value of B=20
After function called
Value of A=20
Value of B=15
After returning from function
Value of A=20
Value of B=15

a. Write a program to input a radius of a circle and print its area. The function should receive
the radius as argument and return area.
b. Write a program to input two number and print the smaller one.

Return Statement
Return statement is used for returning a value from function definition to calling function.

Syntax of return statement


return (expression);

For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored
in variable sum in main() function. The data type of expression in return statement should also
match the return type of function.
# include <stdio.h>
int add (int a, int b);
int main ( )
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 163
{
................
sum=add(num1, num2);
................
}
return type of function sum=add
int add(int a, int b)
{
int add;
data type of add
.............
return add;
}
Types of User-Defined Functions
For better understanding of arguments and return type in functions, user-defined functions can
be categorized as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.
Let’s take an example to find whether a number is prime or not using above 4 categories of
user defined functions.

Function with no arguments and no return value


/*C program to check whether a number entered by user is prime or not using function with
no arguments and no return value*/
#include <stdio.h>
void prime();
int main(){
prime(); //No argument is passed to prime().
return 0;
}
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is void */
int num,i,flag=0;
printf(“Enter positive integer enter to check:\n”);
scanf(“%d”,&num);

164 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf(“%d is not prime”,num);
else
printf(“%d is prime”,num);
}
Function prime() is used for asking user a input, check for whether it is prime or not and display
it accordingly. No argument is passed and returned form prime() function.

Function with no arguments but return value


/*C program to check whether a number entered by user is prime or not using function with
no arguments but having return value */
#include <stdio.h>
int input();
int main()
{
int num,i,flag = 0;
num=input(); /* No argument is passed to input() */
for(i=2; i<=num/2; ++i)
{
if(num%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf(“%d is not prime”,num);
else
printf(“%d is prime”, num);
return 0;
}
int input(){/* Integer value is returned from input() to calling function */
int n;

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 165


printf(“Enter positive integer to check:\n”);
scanf(“%d”,&n);
return n;
}

There is no argument passed to input() function But, the value of n is returned from input() to
main() function.

Function with arguments and no return value


/*Program to check whether a number entered by user is prime or not using function with
arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main()
{
int num;
printf(“Enter positive enter to check:\n”);
scanf(“%d”,&num);
check_display(num); /* Argument num is passed to function. */
return 0;
}
void check_display(int n)
{
/* There is no return value to calling function. Hence, return type of function is void. */
int i, flag = 0;
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf(“%d is not prime”,n);
else
printf(“%d is prime”, n);
}

166 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Here, check_display() function is used for check whether it is prime or not and display it
accordingly. Here, argument is passed to user-defined function but, value is not returned from
it to calling function.

Function with argument and a return value


/* Program to check whether a number entered by user is prime or not using function with
argument and return value */
#include <stdio.h>
int check(int n);
int main(){
int num,num_check=0;
printf(“Enter positive enter to check:\n”);
scanf(“%d”,&num);
num_check=check(num); /* Argument num is passed to check() function. */
if(num_check==1)
printf(“%d is not prime”,num);
else
printf(“%d is prime”,num);
return 0;
}
int check(int n){
/* Integer value is returned from function check() */
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return 1;
}
return 0;
}

Recursive Function
A function that calls itself is known as recursive function and this technique is known as recursion
in C programming. Recursion is more elegant and requires few variables which make program
clean. Recursion can be used to replace complex nesting code by dividing the problem into
same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the
code containing recursion.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 167
Solved Example
Design a program to call the main() function three times to print the same output three times.
Solution :
/* Program for recursive function*/
/* Write a program to find out the sum of all the numbers from 1 to supplied
number*/
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
main()
{
static int z=1;// static initialized variable
printf(“Example of recursive function\n”);
z++;
if (z<=3)
main();
else
exit;
}

Program Explanation
In the above program main() function call itself three times and produced the following output:
Example of recursive function
Example of recursive function
Example of recursive function

a. Write a program using function to input number of the month and print the name of the
month. The function receives number and does not return any value.
b. Write a program using function to generate first 50 natural numbers and print their sum.

168 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Factorial of a Number using Recursion
The factorial of a number n is expressed as a series of repetitive multiplication as shown below:
Factorial of n=n(n-1)(n-2).......1.
For example,
Factorial of 4=4 x 3 x 2 x 1= 24
A function to evaluate factorial of n is as follows:
factorial (int n)
{
int fact;
if (n==1)
return (1);
else
fact=n*factorial (n-1);
return (fact);
}

Solved Example
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf(“Enter a positive integer: “);
scanf(“%d”,&n);
printf(“Factorial of %d = %ld”, n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Program Output
Enter a positive integer: 6
Factorial of 6 = 720
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 169
Fibonacci series using Recursion
Fibonacci series is a series of numbers formed by the addition of the preceding two numbers
in the series. The first two terms are zero and one respectively. The terms after this are
generated by simply adding the previous two terms. The nth term of a Fibonacci series is
defined using the following recurrence equation:
F1=1
F2=1
Fn=Fn-1 + Fn-2
Thus, the terms of the series are 1, 1, 2, 3, 5, 8, 13...

Solved Example
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf(“%d”,&n);
printf(“Fibonacci series\n”);
for ( c = 1 ; c <= n ; c++ )
{
printf(“%d\n”, Fibonacci(i));
i++;
}
return 0;
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

170 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Arrays and Functions
An array element used as an argument is treated like any other simple variable when you use
an array as a function argument. It is passed to a function by value or reference. In the call
by value, we pass values of array elements and call by reference, we pass addresses of array
elements.

Solved Example
Design a program to read five numbers in array variable and find out whether individual number
are even or odd.
Solution :
# include <stdio.h>
# include <conio.h>
//Function declaration
void check (int n);
void main()
{
int num[5]={4,2,7,9,52};
clrscr();
printf(“Example of passing individual element of array to function\n”);
for(int j=0;j<5;j++)
{
// Passing individual array element to the function
check(num[j]);
}
}
void check (int n)
{
if(n % 2==0)
printf(“\n%d is even number”,n);
else
printf(“\n%d is odd number”,n);
}

Program Explanation
In the above program, every time only one element is being passed. This element is stored in
int variable n in function check and checked whether the number is odd or even.
After executing the statements of check() function first time, the program will flow to the
statement after the function call. Again same function is called with new value to the check()
function. This process will continue till the final value of for loop in the main() function.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 171


a. Design a program to find the sum using user defined functions.
Solution:
#include<stdio.h>
#include<conio.h>
void sum(int x, int y);
void main()
{
sum(12,230);
sum(94,63);
sum(851,39);
getch();
}
void sum(int x, int y)
{
printf(“%d “, x+y);
}

b. Design a program to find length of string using user defined functions.


Solution:
#include<stdio.h>
int FindLength(char str[]);
int main()
{
char str[100];
int length;
printf(“\nEnter the String : “);
gets(str);
length = FindLength(str);
printf(“\nLength of the String is : %d”, length);
return(0);
}
int FindLength(char str[])
{
int len = 0;
while (str[len] != ‘\0’)
len++;
return (len);
}
172 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
c. Write a C program to calculate factorial using recursion.
Solution:
#include<stdio.h>
int fact(int);
int main()
{
int num,f;
printf(“\nEnter a number: “);
scanf(“%d”,&num);
f=fact(num);
printf(“\nFactorial of %d is: %d”,num,f);
return 0;
}

int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

d. Write a C program to find factorial of number.


Solution:
#include <stdio.h>
#include <conio.h>
void main ()
{
int a;
long f,fact();
clrscr();
printf (“\n Enter a Number : “);
scanf (“%d”,&a);
f=fact(a);
printf (“\n The Factorial of %d is : %ld”,a,f);
getch();
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 173


long fact(int b)
{
int i;
long f=1;
for (i=1;i<=b;i++)
f=f*i;
return(f);
}

e. Write a C program to print fibonacci series.


Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long int i;
long int fibo(int n);
clrscr();
printf(“Enter the limit:\n”);
scanf(“%d”,&n);
i=fibo(n);
printf(“\nThe %dth Fibonacci number is %ld”,n,i);
getch();
}
long int fibo(int n)
{
int old_no,currnt_no,sum,i;
i=1;
old_no=0;
currnt_no=1;
while(i<=n)
{
sum=old_no+currnt_no;
old_no=currnt_no;
currnt_no=sum;
i++;
printf(“\n%d”,sum);
}
return(sum);
}

174 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


C Programming Storage Class
Every variable in C programming has two properties: type and storage class. Type refers to the
data type of variable whether it is character or integer or floating-point value etc. And storage
class determines how long it stays in existence.
There are 4 types of storage class:
a. Automatic
b. External
c. Static
d. Register

Automatic storage class


The keyword for automatic variable is auto. Variables declared inside the function body are
automatic by default. These variable are also known as local variables as they are local to the
function and doesn’t have meaning outside that function. The automatic variables are initialized
to garbage by default. Since, variable inside a function is automatic by default, keyword auto
are rarely used.

Solved Example
#include <stdio.h>
int main()
{
int a = 10,i;
printf(“%d “,++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf(“%d “,a); // 20 will be printed 3 times since it is the local value of a
}
}
printf(“%d “,a); // 11 will be printed since the scope of a = 20 is ended.
}

External Storage Class


Extern stands for external storage class. Extern storage class is used when we have global
functions or variables which are shared between two or more files. Keyword extern is used
to declaring a global variable or function in another file to provide the reference of variable or
function which have been already defined in the original file. The variables defined using an
extern keyword are called as global variables. These variables are accessible throughout the
program.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 175
Solved Example
int num = 75 ;
void display();
void main()
{
extern int num ;
printf(“nNum : %d”,num);
display();
}
void display()
{
extern int num ;
printf(“nNum : %d”,num);
}

Register Storage Class


The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program. It is similar to the auto storage class.
The variable is limited to the particular block. The only difference is that the variables declared
using register storage class are stored inside CPU registers instead of a memory. Register has
faster access than that of the main memory. The variables declared using register storage class
has no default value. These variables are often declared at the beginning of a program.

Solved Example
#include<stdio.h>
int main()
{
int num1,num2;
register int sum;
printf(“\nEnter the Number 1 : “);
scanf(“%d”,&num1);
printf(“\nEnter the Number 2 : “);
scanf(“%d”,&num2);
sum = num1 + num2;
printf(“\nSum of Numbers : %d”,sum);
return(0);
}

176 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Static Storage Class
The keyword static is used to define static type variable. The static variables are used within
function/ file as local static variables. They can also be used as a global variable.
a. Static local variable is a local variable that retains and stores its value between function calls
or block and remains visible only to the function or block in which it is defined.
b. Static global variables are global variables visible only to the file in which it is declared.

Solved Example
#include <stdio.h>
void next(void);
static int counter = 7;
main()
{
while(counter<10)
{
next();
counter++;
}
return 0;
}
void next( void )
{
static int iteration = 13;
iteration ++;
printf(“iteration=%d and counter= %d\n”, iteration, counter);
}

Storage Classes Storage Place Default Value Scope Lifetime


auto RAM Garbage Local Within the
Value function/block
extern RAM Zero Global Program runtime
static RAM Zero Local Program runtime
Register Register Garbage Local Within the
function/block

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 177


Concepts Review
Topic Key Concepts
Functions in C-Language Function is a collection of statements that performs a specific
task.
Library functions are a set of pre-defined functions whereas
user defined functions are the functions created by the user
at the time of writing a program.
User-defined function helps to divide a program to a number
of parts, which makes easy to understand a program.
Function reduces the size of a program because we can call
a function whenever we require it.
Function declaration includes function name, arguments and
their types and return type of data.
A process of passing value of variables is known as call by
value.
A process of passing addresses to a function is known as call
by reference.

a. What is a function? What are the two varieties of function in C language?


b. What are the advantages of functions?
c. Why do we need function in C program?
d. What is a function argument? How can it be passed in C program?
e. Difference between arguments passed by value and arguments passed by reference?
f. What is recursive function? Give an example of a C program to demonstrate recursive
function.

In the Lab
a. Write a program to declare a user defined function to input the principal, rate of interest
and the number of years, and find the simple interest.
b. Write a program to declare a user defined function to calculate the volume of a cube. The
program accepts the length, width and height.

178 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


c. Write a program to pass the value of n as constant number and print the sum of the first
n natural numbers using function procedure. (Hint: sum = n(n+1)/2)
d. Write a program to declare a user defined function to calculate area and circumference of
a circle.
e. Write a program using function to input the temperature in Fahrenheit and print its
centigrade equivalent using the formula-c=5/9*(F-32). Let the function re the temperature
in Fahrenheit as argument and return the converted temperature.
f. Write a program using function to input three numbers and print the highest one. The
function has to receive the three numbers as argument and return the highest one.
g. Write a program using function to input a number and print whether it is odd or even.
The number has to be sent to the function as argument whereas the function should
return “O” if it odd else it should return “E”.
h. Write a program using function to input number and print whether it is positive or negative
number. The function should receive the two numbers as call by value and the third
argument should be passed by reference. In this third argument within the function it
should be given value 0 if it is negative else it should be given value 1. This value has to be
used in the main() function to display whether the number is positive or negative.
i. Write a complete C program that invokes a function FIND () to find whether four integer
values a, b, c and d sent to it as argument satisfy the equation a3+b3+c3=d3 or not. The
function FIND() should return 100 if the above equation is satisfied otherwise it should
return 200.
j. Write a program using function to input marks in five subjects. Find average and award
grades as per the following guidelines:
90% and above A
89% to 80% B
79% to 70% C
69% to 60% D
59% to 50% E
Less than 50% is fail.
The function receives marks and returns grade.
k. Write a function procedure MIDDLE (A,B,C) to input three numbers and find the middle
number.
l. Write a function procedure TRI (x,y,z) to input three angles of a triangle and check whether
it is a right angled triangle or not.
m. Write a program to declare a user defined function TRI$ (A,B,C) to input three angles of
a triangle. The program should print whether the triangle is equilateral triangle.
n. Write a program to declare a user-defined function rev$ (w$) to reverse a given string.
o. Write a function procedure count! (s$) to count the number of words in an input string.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 179
Structure and Union in C-Language
A structure is a collection of variables under a single name. These variables can be of different
types, and each has a name which is used to select it from the structure. A structure is a
convenient way of grouping several pieces of related information together. A structure can be
defined as a new named type, thus extending the number of available types.
For example: You want to store the information about person about his/her name, citizenship
number and salary. You can create these information separately but, better approach will be
collection of these information under single name because all these information are related to
person.

Structure in C
In C language, structure is a collection of different types of data, which is stored under one
name. It is the most convenient way to keep related data under one roof.
struct keyword : struct keyword groups related variables in a single record.
Syntax:
struct structure_name
{
type variable name1;
type variable name2;
type variable name3;
…….
……..
……..
} structure variables;

Important Points for Structure


i. Structure is a collection of one or more variables, which are logically related. It forms a
template.
ii. Variables of structure are called elements of structure.
iii. Structure tag (structure name) is the identification for data structure.
iv. Structure does not declared any variable, it simply declares format of the structure.
v. Variables of structure can be declared at the time of declaration of structure as given
below :
struct information
{
char fname[20];
char sname[20];
char address[20];
char telephone[10];
}
info1,info2,info3;

180 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


In the above example, struct is keyword, which is used to declare structure, information is
tag-name (which is identification for data structure) char fname, char sname, char address,
char telephone are elements or member of structure. info1,info2,info3 are variables of
structure information.
vi. We can also declare variables of structure anywhere in the program using tag name.
For example :
struct information
{
char fname[20];
char lname[20];
char address[20];
char telephone[10];
};
struct information info1,info2,info3;

Solved Example
Design a program to create a structure info to supply first-name, surname, salary, address and
telephone number. Print the information on the screen.
Solution:
# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
// Structure declaration with different elements
struct info
{
char fname[20];
char sname[20];
float salary;
char address[20];
char telephone[10];
} v1; //structure variable

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 181


Solved Example
//To enter value to structure elements
printf(“Enter First Name\n”);
scanf(“%s”,v1.fname);
printf(“Enter Last Name\n”);
scanf(“%s”,v1.sname);
printf(“Enter Address\n”);
scanf(“%s”,v1.address);
printf(“Enter Salary\n”);
scanf(“%f”,v1.salary);
printf(“Enter Telephone\n”);
scanf(“%s”,v1.telephone);
clrscr();
\\ Printing data of structure elements
printf(“First Name is %s\n”,v1.fname);
printf(“Last Name is %s\n”,v1.sname);
printf(“Salary is %f\n”,v1.salary);
printf(“Address is\ %s\n”,v1.address);
printf(“Telephone is %s\n”,v1.telephone);
}

Program Explanation
In the above program, keyword struct declares structure to hold four different elements
under structure name info called structure tag. In the example, both the template and
variable declaration are combined. V1 is a variable declared for the different elements of
structure info. To assign values to the members of structure, we have used:-
scanf(“%s”,v1.fname);
scanf(“%s”,v1.fname);
scanf(“%s”,v1.sname);
scanf(“%s”,v1.address);
scanf(“%f”,v1.salary);
scanf(“%s”,v1.telephone);

Variable Member of structure


So, the link between member and variable can be made using dot operator (.).

182 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Accessing Structure Members
Structure members can be accessed and assigned values in a number of ways. Structure
members have no meaning individually without the structure. In order to assign a value to any
structure member, the member name must be linked with the structure variable using a dot .
operator also called period or member access operator.

Solved Example
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
{
struct Student s1;
/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, “Viraaj”);
/*
displaying the stored values
*/
printf(“Name of Student 1: %s\n”, s1.name);
printf(“Age of Student 1: %d\n”, s1.age);

return 0;
}
Program Output
Name of Student 1: Viraaj
Age of Student 1: 18

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 183


How to initialize data to structure elements
Like in simple and array variables, the programmer can also initialize structure elements when
they are declared.
struct info
{
char fname[20];
char sname[20];
float salary;
char address[20];
char telephone[10];
};
// Variable declaration with data initialization
struct info v1={“Anil”,”Gurung”,”KTM”,7008.78,”532454”};
struct info v2={“Mohan”,”Subba”,”KTM”,7890.80,”543222”};

Solved Example
# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
struct info
{
char fname[20];
char sname[20];
char address[20];
float salary;
char telephone[10];
};
//Variables declaration with data initialization
struct info v1={“Anil”,”Gurung”,”KTM”,7008.78,”532454”};
struct info v2={“Mohan”,”Subba”,”KTM”,7890.80,”543222”};
clrscr();

184 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
printf(“First Name is %s\n”,v1.fname);
printf(“Last Name is %s\n”,v1.sname);
printf(“Address is\ %s\n”,v1.address);
printf(“Sarary is %f\n”,v1.salary);
printf(“Telephone is %s\n\n”,v1.telephone);
printf(“First Name is %s\n”,v2.fname);
printf(“Last Name is %s\n”,v2.sname);
printf(“Address is\ %s\n”,v2.address);
printf(“Sarary is %f\n”,v2.salary);
printf(“Telephone is %s\n\n”,v2.telephone);
}

Program Output
struct info v1={“Anil”,”Gurung”,”KTM”,7008.78,”532454”};
struct info v2={“Mohan”,”Subba”,”KTM”,7890.80,”543222”};
First Name is Anil
Last Name is Gurung
Address is KTM
Salary is 7008.78
Telephone is 532454
First Name is Mohan
Last Name is Subba
Address is KTM
Salary is 7890.80
Telephone is 543222

a. Write a program to input roll no, name, address of any five students in structure and display
the records properly.
b. Write a program to create a structure to store name, roll number and marks for five subjects.
Find out the total and percentage. Display the information in tabular form.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 185
Memory Consumption of Structure
Like in array, structure also occupies continuous memory location.

Solved Example
# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
struct info
{
char fname[10];
char sname[10];
char address[10];
float salary;
char telephone[10];
};
struct info v1={“Anil”,”Gurung”,”KTM”,7008.78,”532454”};
clrscr();
printf(“First Name is %s \tAddress =%u\n”,v1.fname,&v1.fname);
printf(“Last Name is %s \tAddress =%u\n”,v1.sname,&v1.sname);
printf(“Address is %s \t\tAddress =%u\n”,v1.address,&v1.address);
printf(“Sarary is %f \tAddress =%u\n”,v1.salary,&v1.salary);
printf(“Telephone is %s \tAddress=%u\n”,v1.telephone,&v1.telephone);
}

Program Output
First Name is Anil Address =65482
Last Name is Gurung Address =65492
Address is KTM Address =65502
Sarary is 7008.779785 Address =65512
Telephone is 532454 Address =65516

186 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Nested Structure in C
C provides us the feature of nesting one structure within another structure by using which,
complex data types are created. For example, we may need to store the address of an entity
employee in a structure. The attribute address may also have the subparts as street number,
city, state, and pin code. Hence, to store the address of the employee, we need to store the
address of the employee into a separate structure and nest the structure address into the
structure employee. Consider the following program.

Solved Example
# include <stdio.h>
# include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf(“Enter employee information?\n”);
scanf(“%s %s %d %s”,emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf(“Printing the employee information....\n”);
printf(“name: %s\nCity: %s\nPincode: %d\nPhone: %s”,emp.name,emp.add.
city,emp.add.pin,emp.add.phone);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 187


Structure and Array
To store number of elements of similar type, we need to declare structure variables for the
required number of times. Suppose, you want to store first name, last name, address, salary
and telephone of 50 persons, then you need to declare structure variables 50 times, which is
inconvenient. A better way to solve this problem is array of structure. The following program
illustrates this.

Solved Example
# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
struct info
{
char fname[10];
char sname[10];
char address[10];
float salary;
char telephone[10];
};
struct info v1[5]={“Anil”,”Gurung”,”KTM”,7008.78,”532454”,
“Bimal”,”Subba”,”KTM”,8009.45,”454545”,
“Sunil”,”Rai”,”KTM”,8999.88,”676767”,
“Munish”,”Gurung”,”KTM”,7878.78,”565656”,
“Hemant”,”Gupta”,”KTM”,8888.90,”454545”
};
clrscr();
for(int i=0;i<5;i++)
{
printf(“First Name is %s\n”,v1[i].fname);
printf(“Last Name is %s \n”,v1[i].sname);
printf(“Address is %s \n”,v1[i].address);
printf(“Sarary is %f \n”,v1[i].salary);
printf(“Telephone is %s \n\n”,v1[i].telephone);
}
}

188 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
The above program makes it clear that array of structure stores data as it store with simple
array. In the above program, struct v1[5] declares 5 variables and initialized elements as
given below:

Elements of Structure Data

V1[0].fname Anil

V1[0].sname Pradhan

V1[0].address KTM
V1[0].salary 20000

V1[0].telephone 4266333

V1[1].fname Bobby

V1[1].sname Shrestha

: :

: :

Solved Example
Design a program in C, to store name, address, salary, telephone using array of structure and
supply a name to check whether that supplied name is in the list or not.
Solution :
# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
struct info
{
char fname[10];
char sname[10];
char address[10];
float salary;
char telephone[10];
};

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 189


Solved Example
// to initialized structure
struct info v1[5]={“ANIL”,”Gurung”,”KTM”,7008.78,”532454”,
“BIMAL”,”Subba”,”KTM”,8009.45,”454545”,
“SUNIL”,”Rai”,”KTM”,8999.88,”676767”,
“MUNISH”,”Gurung”,”KTM”,7878.78,”565656”,
“HEMANT”,”Gupta”,”KTM”,8888.90,”454545”
};
clrscr();
char ssname[10];
int c;
printf(“Enter name to be searched\n”);
scanf(“%s”,ssname);
strupr(ssname); //to convert into uppercase
for(int i=0;i<5;i++)
{
c=strcmp(v1[i].fname,ssname);
if (c==0)
{
printf(“First Name is %s\n”,v1[i].fname);
printf(“Last Name is %s \n”,v1[i].sname);
printf(“Address is %s \n”,v1[i].address);
printf(“Sarary is %f \n”,v1[i].salary);
printf(“Telephone is %s \n\n”,v1[i].telephone);
goto last;
}
}
printf(“Name is not in list”);
last:
}

190 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Passing Structure to Function
Just like other variables, a structure can also be passed to a function. We may pass the structure
members into the function or pass the structure variable at once. Consider the following
example to pass the structure variable employee to a function display() which is used to display
the details of an employee.

Solved Example
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void display(struct employee);
void main ()
{
struct employee emp;
printf(“Enter employee information?\n”);
scanf(“%s %s %d %s”,emp.name,emp.add.city, &emp.add.pin, emp.add.
phone);
display(emp);
}
void display(struct employee emp)
{
printf(“Printing the details....\n”);
printf(“%s %s %d %s”,emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 191


Union in C
A union is a special data type available in C that enables you to store different data types in the
same memory location. You can define a union with many members, but only one member
can contain a value at any given time. Unions provide an efficient way of using the same
memory location for multi-purpose.

Defining a Union
To define a union, you must use the union statement in very similar was as you did while
defining structure. The union statement defines a new data type, with more than one member
for your program.
The format of the union statement is as follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the union’s definition, before
the final semicolon, you can specify one or more union variables but it is optional. Here is the
way you would define a union type named Data which has the three members i, f, and str:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of data type can store an integer, a floating-point number, or a string of
characters. This means that a single variable ie. same memory location can be used to store
multiple types of data. You can use any built-in or user defined data types inside a union based
on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in above example Data type will occupy 20 bytes of memory space
because this is the maximum space which can be occupied by character string.
Following is the example which will display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
192 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( “Memory size occupied by data : %d\n”, sizeof(data));
return 0;
}

When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member
access operator is coded as a period between the union variable name and the union member
that we wish to access. You would use union keyword to define variables of union type.

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, “C Programming”);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 193


printf( “data.i : %d\n”, data.i);
printf( “data.f : %f\n”, data.f);
printf( “data.str : %s\n”, data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result:
data.i 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Differences between Structure and Union


Structure Union
To define a structure, struct keyword is used. To define a union, the union keyword is used.
All members can be initialized at once. One member can be initialized at once.
struct structure_name { union union_name {
//member definition; //member definition;
} structure_variable; } union_variable;
Total memory size required is equal to Total memory size required is equal to the
the sum of the size of memory of all the memory size required by the largest data
members in the structure. member in the union.
Each member has a unique memory space. All the members have the same memory
space.
All the members can be accessed at the One member whose value recently stored
same time. in the memory location can be accessed at
a time.
Altering a value will not affect other Altering a value will also alter the value of
members. other members
Used when programmers need to store Used when type conversions are needed.
distinct values for all the members in a
distinct memory location.

a. Write a program to read and display student data using union.


b. Write a program to find average marks of N students each having M subjects in a class.
(Illustrate the concept of Array and Structure)

194 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


a. Design a C program to using a structure representing a length.
Solution :
# include <conio.h>
# include <stdio.h>
# include <ctype.h>
# define INCHES_PER_FOOT 12
# define FEET_PER_YARD 3
struct Length
{
unsigned int yards;
unsigned int feet;
unsigned int inches;
};
struct length add (struct Length first, struct Length second);
void show (struct Length length);
void main ( )
{
char answer = “n”
struct Length length;
struct Length total = { 0, 0, 0 }
int i=0;
length.yards=9;
length.feet=10;
length.inches=1;
total=add(total, length);
show(total);
printf(“\n”);
getch( );
}
struct Length add (struct Length first, struct Length second)

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 195


{
unsigned long inches=0;
struct Length sum;
inches=first.inches + second.inches + INCHES_PER_FOOT * (first.feet + second.
feet+FEET_PER_YARD * (first.yards + second.yards));
sum.inches = inches%INCHES_PER_FOOT;
sum.feet=inches/INCHES_PER_FOOT;
sum.yards=sum.feet/FEET_PER_YARD;
return sum;
}
void show (struct Length length)
{
printf ((“%d yards %d feet %d inches”, length.yards,length.feet, length.inches);
}

b. Write a C Program to Store Information(name, roll and marks) of a Student Using Structure.
Solution :
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s;
printf(“Enter information of students:\n\n”);
printf(“Enter name: “);
scanf(“%s”,s.name);
printf(“Enter roll number: “);
scanf(“%d”,&s.roll);
printf(“Enter marks: “);
scanf(“%f”,&s.marks);
printf(“\nDisplaying Information\n”);

196 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


printf(“Name: %s\n”,s.name);
printf(“Roll: %d\n”,s.roll);
printf(“Marks: %.2f\n”,s.marks);
return 0;
}

c. Write a C program to Add Two Complex Numbers by Passing Structure to a Function.


Solution:
#include <stdio.h>
typedef struct complex{
float real;
float imag;
}complex;
complex add(complex n1,complex n2);
int main(){
complex n1,n2,temp;
printf(“For 1st complex number \n”);
printf(“Enter real and imaginary respectively:\n”);
scanf(“%f%f”,&n1.real,&n1.imag);
printf(“\nFor 2nd complex number \n”);
printf(“Enter real and imaginary respectively:\n”);
scanf(“%f%f”,&n2.real,&n2.imag);
temp=add(n1,n2);
printf(“Sum=%.1f+%.1fi”,temp.real,temp.imag);
return 0;
}
complex add(complex n1,complex n2){
complex temp;
temp.real=n1.real+n2.real;
temp.imag=n1.imag+n2.imag;
return(temp);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 197


Concepts Review
Topic Key Concepts
Structure and Union in Structure is a collection of different types of data, which is
C-program referenced under one name.
Structure does not declare any variable, it simply declares
format of the structure.
Variables of structure can be declared at the time of
declaration of structure or anywhere in the program using
tag name.
Structure can be initialized at the time of declaration of
variable.
Structure also occupies continuous memory location.
A union is a special data type available in C that enables you
to store different data types in the same memory location.
The union statement defines a new data type, with more
than one member for your program.
To access any member of a union, we use the member
access operator (.).

a. What is a structure? How do you initialize data to structure elements? Illustrate your
answer with simple example.
b. Differentiate between structure and union with syntax.
c. Differentiate between array and structure.
d. What is a union in C program? How do you define a union in C program?

In the Lab
a. Write a program to create a structure to store name, address and salary of five persons.
Print the information with the structure elements.
b. Write a program to create a structure to store name, roll number and marks for five
subjects. Find out the total and percentage. Display the information in tabular form.
c. Define a structure to store name , department and salary for 20 employees. Supply the
name of an employee to display the information on the screen.

198 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


d. Write a program to create an array of structure to supply name, address and telephone
number for 10 persons. Print the information in a tabular form.
e. Write a C program to read and write the library data by using structure in C language
(illustrate the concept of accessing the value of structure variable).
f. Write a C program to read and write the student data by using structure. (Illustrate the
concept of accessing the value of structure variable).
g. Write a C program to find average marks of three subjects of N students in a class by using
array of structure (illustrate the concept of array of structure).
h. Write a C program to find average marks of N student each having M subjects in a class
(illustrate the concept of arrays within the structure).
i. Write a C program to read and display student grade by using structure with function
(illustrate the concept of passing structure to function).
j. Write a program to input Roll No, name and address of any 5 students in structure and
display the records properly.
k. Write a C program to store roll number, name, address and phone number of 10 students
by using union and display the record, see what happen on display.
l. Write a program to input roll number, name and age of different students and sort the
record in ascending order on the basis of age.
m. Write a program to input names and addresses of any 50 persons and sort the records in
ascending order on the basis of names.
n. Write a C program to read 20 patients id, name, disease and sort them on the basis of
disease.
o. Write a program to input name of the months and monthly income and expenditure of an
office during last year and display the records properly. Also calculate the total and average
income and expenditure of the office in last year.
p. Write a program to input the names and age of any 100 students and count how many
students are in the age group between 15 to 20.
q. Write a program to input the names and districts.
r. Write a program to input the names, address and age of different persons in a village and
display the records who are eligible to cast vote. {note: the persons who are 18 years or
above are eligible to case vote.}
s. Write a program to input name, district and phone no. of the students in a college and
display the records of those students who are from ‘Chitwan’ district.
t. Write a program to input roll no, name and address of different students and display the
records of those students whose first name begins from the letters ‘S’.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 199


Pointers in C-Language
Pointers are an extremely powerful programming tool. A pointer is a variable whose value is
the address of another variable, i.e., direct address of the memory location. Like any variable
or constant, you must declare a pointer before using it to store any variable address. The
pointer variable might be belonging to any of the data type such as int, float, char, double,
short etc. It is used to allocate memory dynamically i.e. at run time. It is also used to access the
memory and manipulate the address.
Major advantages of pointers are: (i) It allows management of structures which are allocated
memory dynamically. (ii) It allows passing of arrays and strings to functions more efficiently. (iii)
It makes possible to pass address of structure instead of entire structure to the functions. (iv) It
makes possible to return more than one value from the function.
aaa3 fff4

fff4 50

p (pointer) number (normal variable)


How to know the address of a variable?
To know the address of a variable, we have to use the special operator called unary operator
(address operator) that is &. Unary operator (&) returns the address of a variable.
For example:
int a=10; // declaration and initialization of integer variable a
int *p; // declaration of pointer variable p
p=&a; // & (address operator) returns address of a integer variable a

How to get the value of an address?


After storing the address of location of a variable to a pointer variable, the value of that variable
can be accessed by using special indirection operator called unary operator (* asterisks).

Declaration of Pointer variable


To declare pointer variable, we can write as follows:
Syntax:
data-type *pointer variable;
Examples:
int *p; // p is a pointer variable to point address of a integer value.
float *p; // p is a pointer variable to point address of a float point value.
char *p; // p is a pointer variable to point address of a char value.

200 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Initialization of pointer

Solved Example
int *p;
int a=10;
p=&a; //p stores an address of variable a.
# include <stdio.h>
# include <conio.h>
void main()
{
clrscr();
int a;
int *p;

Solved Example
a=50;
p=&a;
printf(“\nAddress of a =%u”,&a);
printf(“\nAddress of a =%u”,p);
printf(“\nAddress of p =%u”,&p);
printf(“\nValue of a =%d”,a);
printf(“\nValue of a =%d”,*p);
}

Program Explanation
Address of a =65524
Address of a =65524
Address of p =65522
Value of a = 50
Value of p = 50

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 201


Uses of Pointer
a. int *p;
*p is declared as pointer variable which would point to address of int type of value.
b. p=&a;
p is initialized with the address of int variable a which is 65524
c. printf(“\nAddress of a =%u”,&a);
&a (“address of” operator) is printing the address of int variable a.
%u is used to print address in unsigned integer.
d. printf(“\nAddress of a =%u”,p);
p is a pointer variable also prints the address of int variable a.
e. printf(“\nAddress of p =%u”,&p);
&p prints the address of pointer variable p.

Pointer Expression and Assignment


Like other variables, pointer variables can be used in expressions. For example, if p1 and p2
are properly declared and initialized pointers, then the following statements are valid:
y=*p1 * *p2;
sum=sum + *p1;
We can perform arithmetic operations to pointer variables using arithmetic operators. We can
add an integer or subtract an integer using a pointer pointing to that integer variable. In addition
to arithmetic operations, pointers can also be compared using the relational operators. The
expressions such as p1>p2, p1==p2, and p1!=p2 are allowed.

Solved Example
# include <stdio.h>
# include <conio.h>
void main()
{
clrscr();
int a;
int *p;
a=50;
p=&a;
printf(“\nBefore changing the value of a =%u”,*p);
*p=*p+15;
printf(“\nAfter changing the value of a =%u”,*p);
}

202 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
In the above program, pointer variable p is storing address of int variable a. It is indirectly
pointing to its value. So, expression *p = *p+15; will change the value of variable a.

Solved Example
# include <stdio.h>
# include <conio.h>
void main()
{
clrscr();
int a;
int *p;
a=50;
p=&a;
printf(“\nBefore changing the value of p =%u”,*p);

*p - =5; //Example of shorthand operator


//Value of Pointer variable *p minus 5
printf(“\nAfter changing the value of p =%u”,*p);
}

Solved Example
# include <stdio.h>
# include <conio.h>
void main()
{
clrscr();
int a;
int *p,*p1;
a=50;
p=&a;
p1=&a;
printf(“\nP is pointing the value of a =%u”,*p);
printf(“\nP1 is pointing the value of a =%u”,*p1);
int t=*p**p1; //Multiplication of pointers
printf(“\nAfter Multiplication of Values of pointers =%u”,t);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 203


Program Explanation
In the above program, pointer variables p1 and p2 are pointing value of variables a and b.
First two printf() functions prints value of variable a through pointer variables p1 and p2.
int t=*p**p1; it will multiply the values of p1 and p2 and store in int variable t. So, last
printf() will print the value of t.

Program Output
P is pointing the value of a =50
P1 is pointing the value of a =50
After Multiplication Value of t =2500
Pointers with Array
When we declare an array, array elements are stored in continuous memory location. So,
when the pointer is increased, it always points to next location of similar data type. The
following example will illustrate this:

Solved Example
# include <stdio.h>
# include <conio.h>
void main()
{
clrscr();
int a[]={2,5,44,3,1};
int *p;
p=&a[0];
for(int i=0;i<5;i++)
{
printf(“\nAddress = %u Value = %d”,p,*p);
*p++;
}
}

a. Write a program to add two values by using a pointer.


b. Write a program to swap two values by using a pointer.
c. Write a program to assign value to char pointer.

204 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Pointer with Character Array
As in integer array, in character array also we get base address of a string by mentioning
character variable to pointer variable. To get other elements of an array, we can increase the
value of pointer. When pointer is increased, it points to the immediate location of its type.
Suppose, the base address of character type is 65524, when it is increased it points to 65525,
because char data type occupies one byte for each character. This process continues till
pointer variable does not point to the null character (\0).

Solved Example
# include <stdio.h>
# include <conio.h>
void main()
{
clrscr();
char *p;
char a[]=”school”; // string assigned to array variable a[]
p=a; // It stores base address to pointer variable p
while(*p != ‘\0’)
{
//To print address and value of pointer
printf(“\nAddress = %u Value = %d”,&*p,*p);
*p++;
}
}

Program Output
Address = 65512 Value = s
Address = 65513 Value = c
Address = 65514 Value = h
Address = 65515 Value = o
Address = 65516 Value = o
Address = 65517 Value = l

Passing Array of Numbers to Function


As we have done earlier, when we call a function with a numeric array, address of the first
element of an array is passed to the pointer variable of the called function. Other elements of
an array can be accessed using the pointer variable. So, the parameter declaration must be
pointer type.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 205


Passing Array of Numbers to Function
As we have done earlier, when we call a function with a numeric array, address of the first
element of an array is passed to the pointer variable of the called function. Other elements of
an array can be accessed using the pointer variable. So, the parameter declaration must be
pointer type.

Solved Example
Design a program to pass an array elements (10 different numbers) to a called function
smallest() and print the smallest number.
Solution :
# include <stdio.h>
# include <conio.h>
void display (int *,int);
void main()
{
int num[]={4,2,99,67,45,46,1,9,52,87};
clrscr();
printf(“Example of passing array to function\n”);
display(num,9);
}
void display (int *n, int j)
{
int i;
int g=*n;
for(i=0;i<=j;i++)
{
if(*n<g)
g=*n;
n++;
}
printf(“Smallest number = %d”,g);
}

Program Explanation
When the function greatest is called, an address of the first element of array is passed and
stored in pointer variable *n and value of the same pointer variable is increase to access the
other elements of an array.

206 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by value and
call by reference.
Call by value in C
a. In call by value method, the value of the actual parameters is copied into the formal
parameters.
b. In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
c. In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
d. The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.

Solved Example
#include<stdio.h>
void change(int num) {
printf(“Before adding value inside function num=%d \n”,num);
num=num+100;
printf(“After adding value inside function num=%d \n”, num);
}
int main() {
int x=100;
printf(“Before function call x=%d \n”, x);
change(x);//passing value in function
printf(“After function call x=%d \n”, x);
return 0;
}

Program Explanation
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 207


Call by reference in C
a. In call by reference, the address of the variable is passed into the function call as the actual
parameter.
b. The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
c. In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets stored at the same
address.

Solved Example
#include<stdio.h>
void change(int *num) {
printf(“Before adding value inside function num=%d \n”,*num);
(*num) += 100;
printf(“After adding value inside function num=%d \n”, *num);
}
int main() {
int x=100;
printf(“Before function call x=%d \n”, x);
change(&x);//passing reference in function
printf(“After function call x=%d \n”, x);
return 0;
}

Program Explanation
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

208 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


a. Design a C program to add two numbers using pointers.
Solution :
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf(“Enter two integers to add\n”);
scanf(“%d%d”, &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf(“Sum of the numbers = %d\n”, sum);
return 0;
}

b. Design a C program to find factorial of a number using pointers.


Solution :
#include<stdio.h>
void findFactorial(int,int *);
int main()
{
int i,factorial,num;
printf(“Enter a number: “);
scanf(“%d”,&num);
findFactorial(num,&factorial);
printf(“Factorial of %d is: %d”,num,*factorial);
return 0;
}
void findFactorial(int num,int *factorial)
{
int i;
*factorial =1;
for(i=1;i<=num;i++)
*factorial=*factorial*i;
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 209


c. Design a C program to reverse a string in c using pointers.
Solution :
#include<stdio.h>
int main(){
char str[50];
char rev[50];
char *sptr = str;
char *rptr = rev;
int i=-1;
printf(“Enter any string : “);
scanf(“%s”,str);
while(*sptr)
{
sptr++;
i++;
}
while(i>=0)
{
sptr--;
*rptr = *sptr;
rptr++;
--i;
*rptr=’\0’;
printf(“Reverse of string is : %s”,rev);
return 0;
}
Sample Output:
Enter any string : pointer
Reverse of string is : retniop

210 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concepts Review
Topic Key Concepts
Pointers in C-program Pointer is a variable that holds an address of location of
another variable.
The operator & returns memory address of a variable
The operator * returns value of a variable pointed by a
pointer variable.
The pointer variable must pointed to the correct type of
data.
Value of a pointer can be manipulated.
Pointer is used to access the elements of an array.

a. Define pointer with example.


b. What is the use of indirection and address of operators?
c. Discuss the relation between the pointer and array with suitable.
d. Explain the meaning of each of the following declarations:
int *p;, int *p[10];, int (*p)[10];, int *p(void); and int *p(char*a);

In the Lab
a. Write a C program to assign value to a char pointer.
b. Write a C program to swap function: exchange the values by pointers.
c. Write a C program to find sum of N numbers by using pointer.
d. Write a C program to print the strings having three cities and their addresses using array
of pointer to the string concept.
e. Write a C program to add two tables of integers using functions and pointers.
f. Write a C program to find the sum of two numbers using pointer.
g. Write a C program to calculate the simple interest using pointer.
h. Write a C program to find the location of characters of any city and find its length (no. of
character in a string) by using pointer.
i. Write a C program to find the multiplication of two matrices using pointers.
j. Write a C program to sort a list of strings using pointers.
k. Write a C program to reverse the string using pointer.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 211


File Handling in C-Language
In the previous chapters, we have used printf(), scanf(), getc(), putc() etc. for input/output
operations. These functions are console oriented input/output functions. These functions
cannot write/read the data on the data file. This approach has some limitations:
i. It is difficult to handle large amount of data.
ii. Data stored for one program is not possible to be shared by other programs.
iii. All the data supplied from the keyboard will be lost, when computer is switched off.
To overcome this approach, we will discuss the handling of data file or disk input/output
operation. Data file is a collection of related data, which is stored on disk and can be used at
the time of requirement of data by the program.
In C, large numbers of standard library function are available to perform the input/output
operation on data file. C supports two types of Input/Output operation. They are:
i. High level file Input/Output operation
ii. Low level file Input/Output operation

Sequential and Random Access Files


Sequential Access to a data file means that the computer system reads or writes information to
the file sequentially, starting from the beginning of the file and proceeding step by step.
On the other hand, Random Access to a file means that the computer system can read or
write information anywhere in the data file. This type of operation is also called “Direct Access”
because the computer system knows where the data is stored (using Indexing) and hence goes
“directly” and reads the data.

Steps that are involved to maintained a data file


i. Opening a file
ii. Reading/Writing from/on data file
iii. Closing a data file

Opening a file
Before reading data from a file or writing data to a file, we must open a file. Opening a file
creates link between the program and operating system, where we have to mention data file-
name and mode of operation (reading or writing). The link between program and operating
system is controlled by a structure called FILE. So, it is necessary to declare FILE before
opening the data file.
Syntax:
FILE *fp;
Fp=fopen(“filename”,”mode”);
Where,
FILE is a structure which contains information about the file being used such as file size, location
etc.
fp is a pointer variable which contains the address of structure FILE.
Mode defines purpose of opening the data file.
212 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
The following modes in which file can be opened:
Mode Purpose
r Reading from file
w Writing to file
a Appending new contents at the end of file
r+ Reading and writing new contents
w+ Writing new contents and reading existing contents
a+ Reading existing contents and appending new contents

Closing a file
After opening a file, we can do reading or writing operation. After reading or writing operation,
we must close a file. This is done by using function fclose().
Syntax:
fclose(pointer variable);

Reading a character from a data file


Function getc() :
Purpose :
getc() function reads a character from a file which is opened in read
mode.
Syntax : char <variable>;
<variable>=getc(file-pointer);

Writing a character to a data file


Function putc() :
Purpose :
putc() function writes a character to a data file which is opened with
write mode.
Syntax : putc(character, file_pointer);
Example : #include <stdio.h>
main()
{
FILE *fp;
fp = fopen(“file1.txt”, “w”);//opening file
fputc(‘a’,fp);//writing single character into file
fclose(fp);//closing file
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 213


Solved Example
Design a program to read string from the keyboard and write on the data file. Display the
contents of data file on the screen.
Solution :
# include <stdio.h>
# include <conio.h>
void main()
{
char n;
int i=0;
clrscr();
printf(“Enter String and Press Enter Key\n”);
//file pointer declaration
FILE *fpt;
//file chara.dat open in write mode
fpt=fopen(“chara.dat”,”w”);
while((n=getchar())!=’\n’)
{
//to write character in opened data file
putc(n,fpt);
}
fclose(fpt);
//file chara.dat open in read mode
fpt=fopen(“chara.dat”,”r”);
char ch1;
//to read data of file opened file
printf(“String of data file \n”);
while((ch1=getc(fpt))!=EOF)
{
printf(“%c”,ch1);
}
fclose(fpt);
}

214 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
The above program allows user to give string from the keyboard. Function getchar() reads
a character typed from the keyboard and function putc() writes on the data file chara.dat
character wise. String is terminated when user press enter key from the keyboard. Again
file chara.dat is opened in read mode. Function getc() reads all the characters (one by
one) of data file until pointer reached to EOF and prints on the monitor (EOF a constant
indicating that end-of-file has been reached on a file).

Solved Example
Design a program to store string to the data file and display the same contents on the monitor
reading from the data file.
Solution :
# include <stdio.h>
# include <conio.h>
void main()
{
//to declare and initialized character array
char n[]=”KATHMANDU IS THE CAPITAL OF NEPAL”;
int i=0;
clrscr();
//file pointer declaration
FILE *filept;
//file new.dat open in write mode
filept=fopen(“new1.dat”,”w”);
while(n[i]!=’\0’)
{
//to write character in opened data file
putc(n[i],filept);
i++;
}
fclose(filept);
//file new.dat open in read mode
filept=fopen(“new1.dat”,”r”);
char ch1;
//to read data of opened file

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 215


Continued...
printf(“Contents of data file\n”);
while((ch1=getc(filept))!=EOF)
{
printf(“%c”,ch1);
}
fclose(filept);
}

Program Explanation
In the above program, string is stored in an array variable n[ ]. All the characters of string
is written on the opened data file new.dat. The putc() function writes one character at a
time. Again the file is opened in a read mode and displays the contents of data file new.
dat on the screen. The getc() function reads one character at a time. The file pointer
advances one character forward on the execution of getc() or putc().

Function : getw()
Purpose : getw() function reads integer value from the open file.
Syntax : int <variable>;
<variable>=getw(filepointer);

Function : putw()
Purpose : putw() function writes integer value to the open file.
Syntax : putw(integer,filepointer);

Solved Example
Design a program to supply three integers from the keyboard, store them in data file. Read the
numbers from the data file and find the sum.
Solution :
# include <stdio.h>
# include <conio.h>
void main()
{
int n[3];
int i=0;

216 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Continued...
clrscr();
//file pointer declaration
FILE *fpt;
//file new2.dat open in write mode
fpt=fopen(“c:\\new2.dat”,”w”);
//To supply three different numbers and to write on data file
while(i<3)
{
printf(“Enter Integer Value”);
scanf(“%d”,&n[i]);
//to write numbers in opened data file
putw(n[i],fpt);
i++;
}
fclose(fpt);
//file new.dat open in read mode
fpt=fopen(“c:\\new2.dat”,”r”);
int j=0,val,sum=0;
//to read data of file opened file
while(j<3)
{
val=getw(fpt);
printf(“Number= %4d\n”,val);
sum=sum+val;
j=j+1;
}
fclose(fpt);
printf(“Sum =%d”,sum);
}

Handle mixed formatted data


Function : fprintf()
Purpose : fprintf() function is used to write formatted data to the open
datafile.
Syntax : fprintf(file_pointer,”control string”, argument list);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 217


Function : fscanf()
Purpose : fscanf() function is used to read the formatted data from the
datafile.
Syntax : fscanf (file_pointer,”control string”, argument list);

Solved Example
Design a program to supply name, address, telephone and to store them in data file.
Solution :
# include <stdio.h>
# include <conio.h>
# include <ctype.h>
void main()
{
char name[20];
char addr[20];
char tele[10];
//file pointer declaration
FILE *fpt;
//file new3.dat open in append mode
fpt=fopen(“info.dat”,”a”);
//To supply three different numbers and to write on data file
char ch=’Y’;
clrscr();
printf(“\Enter data on the same line, separate data by space\n”);
while(ch==’Y’)
{
printf(“\nEnter Name Address Telephone \n”);
scanf(“%s %s %s”,name,addr,tele);
fprintf(fpt,”%s %s %s\n”,name,addr,tele);
printf(“\nWants to continue Y/N”);
ch=toupper(getche());

218 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Continued...
//to write numbers in opened data file
//printf(“%s%s%d\n”,name,addr,tele);
fflush(stdin);// flush buffer related with keyboard
}
fclose(fpt);
}
Program Explanation
The above program is opened in an append mode where data can be added after the last
record. The user can supply name, address and telephone through the keyboard. The
fprintf() function writes data on the data file. The number of data can be given according
to the user’s choice.

Solved Example
Design a program to read name, address and telephone. Display them on the monitor.
Solution :
# include <stdio.h>
# include <conio.h>
# include <ctype.h>
void main()
{
char name[20];
char addr[20];
char tele[10];
//file pointer declaration
FILE *fpt;
//file new3.dat open in write mode
fpt=fopen(“info.dat”,”r”);
//To supply three different numbers and to write on data file
clrscr();
printf(“NAME\t\tADDRESS\t\tTELEPHONE\n”);
while(fscanf(fpt,”%s %s %s”,name,addr,&tele)!=EOF)
//to display data on the monitor
printf(“\n%s\t\t%s\t\t%s”,name,addr,tele);
fclose(fpt);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 219


Trouble in opening a file
When we try to open a file in read mode with fopen() function, it returns file pointer. When
file is failed to open due to some reason, function returns null pointer. Here is an example of
checking opening error:

Solved Example
Design a program to open a file in read mode and print the error message if file is not open.
Solution :
# include <stdio.h>
# include <conio.h>
//File pointer declared
FILE *fpt;
fpt=fopen(“chara.dat”,”r”);
//To check whether file is opened or not
if(fpt==NULL)
{
printf(“File Not Found”);
}
char ch1;
//to read data of file opened file
while((ch1=getc(fpt))!=EOF)
{
printf(“%c”,ch1);
}
fclose(fpt);
}

Program Explanation
In the above example, if file chara.dat is not opened, then file returns null pointer. If it
returns null pointer, it displays message “File Not Found”, otherwise it reads the data of
chara.dat and prints on the monitor.

a. Write a program to create a data file named Tele.dat, which allows storing first-name, last-
name, address, and telephone. Program should allow user to enter records according to his or
her choice.

220 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Structure and Data file
In C, we can also use data type structure to write and read different types of data. We know,
that structure is a collection of different types of data, which is referenced under one name.
The fwrite() and fread() functions are used to write and read data respectively through data
type structure.
fwrite() function : This function writes number of items of data structure to the output file
pointed by file pointer.
Syntax :
fwrite(&v,sizeof(v),numv,fileptn);
Comments :
first argument &v indicates address of structure
second argument sizeof(v) indicates size of structure in bytes
third argument numv indicates number of structure wants to write
last argument fileptn indicates pointer to the output file.

fread() function : This function reads number of items of data structure from the output file
pointed by file pointer.
Syntax :
fread(&v,sizeof(v),numv,fileptn);

Solved Example
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <ctype.h>
void main()
{
FILE *fpt;
struct info
{
char fname[10];
char sname[10];
char street[10];
char city[10];
int sal;
};

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 221


Continued...
struct info v;
clrscr();
char choice=’Y’;
fpt=fopen(“infor.dat”,”w”);
while(choice==’Y’)

{
printf(“\nEnter First Name\n”);
scanf(“%s”,v.fname);
printf(“Enter Last Name \n”);
scanf(“%s”,v.sname);
printf(“Enter Street Name \n”);
scanf(“%s”,v.street);
printf(“Enter City \n”);
scanf(“%s”,v.city);
printf(“Enter Salary \n”);
scanf(“%d”,v.sal);
fwrite(&v,sizeof(v),1,fpt);
printf(“\nWants to add any more Y/N”);
fflush(stdin);
choice=toupper(getche());
}
fclose(fpt);
fpt=fopen(“infor.dat”,”r”);
clrscr();
printf(“Name\tSurname\tStreet\tCity\tSalary\n”);
while(fread(&v,sizeof(v),1,fpt)==1)
{
printf(“\n%s\t%s\t%s\t%s\t%d\n”,v.fname,v.sname,v.street,v.city,v.sal);
}
fclose(fpt);
}

222 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
In the above program, fwrite() and fread() are used in place of printf() and scanf(). The
statement fwrite(&v,sizeof(v),1,fpt); writes the structure to output file infor.dat. In the
statement, first argument &v writes address of structure, second argument sizeof(v)
writes the size of v, third argument 1 write one structure at a time and the last argument
fpt (File Pointer) is pointer to the file, where it writes the structure.
In the reading section, fread() function reads the data from the disk and store in structure
variable v (format for fread() is similar to fwrite() function). In fread() function third
argument is “1” which reads one record at a time. In condition, we have written while(fr
ead(&v,sizeof(v),1,fpt)==1), when it reads the record, it returns one otherwise it returns
0 and terminates the while loop.
Use of +w mode in file handling
In file handling, normally we will open a file in “r” (reading mode), “w” (writing mode) and “a”
(append mode). In “r” mode, we can read but can not write, in “w” mode we can only write
but cannot read the data and in “a” mode we can only add the records after the end of last
record but cannot read, but most of the compiler supports other modes like w+, r+ and a+.
The use of “w+” mode is shown by the sample program.

Solved Example
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <ctype.h>
void main()
{
FILE *fpt;
struct info
{
char fname[10];
char sname[10];
};
struct info v;
clrscr();

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 223


Continued...
char choice=’Y’;
fpt=fopen(“infor.dat”,”a+”);
while(choice==’Y’)
{
printf(“\nEnter First Name\n”);
scanf(“%s”,v.fname);
printf(“Enter Last Name \n”);
scanf(“%s”,v.sname);
fwrite(&v,sizeof(v),1,fpt);
printf(“\nWants to add any more Y/N”);
fflush(stdin);
choice=toupper(getche());
}
clrscr();
printf(“Name\t\tSurname\n”);
//To place the file pointer at the beginning
rewind(fpt);
while(fread(&v,sizeof(v),1,fpt)==1)
{
printf(“\n%s\t\t%s\n”,v.fname,v.sname);
}
fclose(fpt);
}

a. A data file “INFO.INF” has numerous records in it with name, address and telephone numbers
in each record. Write a program to scan all the records from that file and display only the
records with address “Kathmandu”.

224 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Program Explanation
In the above program, we have opened data file info.dat in “w+” mode, which allows to
write on the data file and read from the data file, So, it is not necessary to open a same
file twice as we have done in the previous programs.
Another new function we have used in this program is rewind(fpt) which places the file
pointer fpt to the beginning of the data file.
Deleting a data file
Command : remove
Purpose : Removes a data file from the disk drive.
Syntax : remove(“filename”);
For example : remove(“a:\info.dat”);
- Removes info.dat file from the A: drive.

Renaming a data file


Command : rename()
Purpose : Change a filename from old filename to new filename.
Syntax : rename(“old filename”,”new filename”);

Solved Example
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <ctype.h>
void main()
{
FILE *fpt;
FILE *tfpt;
struct info
{
char fname[10];
char sname[10];
char street[10];
char city[10];
int sal;

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 225


Continued...
};
struct info v;
clrscr();
// Files opened
fpt=fopen(“info.dat”,”r”);
tfpt=fopen(“temp.dat”,”w”);
char empname[20];
printf(“\nEnter Name to be deleted”);
scanf(“%s”,&empname);
while(fread(&v,sizeof(v),1,fpt)==1)
{
if(strcmp(empname,v.fname)!=0)
fwrite(&v,sizeof(v),1,tfpt);
}
fclose(fpt);
fclose(tfpt);
remove (“info.dat”);
rename (“temp.dat”,”info.dat”);
}

Program Explanation
In the above program, two files are opened at the same time. First is info.dat, which
contains some records, and second is temp.dat where program stores records
temporarily. User can supply first name of a person to delete record. While statement
reads all the records one by one and strcmp() function compares empname and v.fname.
If names are matched, it returns numeric value 0 then record will not be written on the
temp.dat otherwise it is written on the temp.dat. This process will continue upto the last
record. After closing two open files, remove() function removes info.dat and rename()
function change the filename temp.dat to info.dat.

a. A data file result.dat contains the name and marks secured by students in three subjects.
Assuming that mark for each subject is 32, write a C program to count the number of passed
students.

226 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Solved Example
Design a program to open a data file, which contains some records. Enter a name to modify
the record.
Solution :
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <ctype.h>
void main()
{
FILE *fpt;
FILE *tfpt;
struct info
{
char fname[10];
char sname[10];
char street[10];
char city[10];
int sal;
};
struct info v;
clrscr();
// files opened
fpt=fopen(“info.dat”,”r”);
tfpt=fopen(“temp.dat”,”w”);
// To print records of data file
printf(“Name\tSurname\tStreet\tCity\tSalary\n”);
while(fread(&v,sizeof(v),1,fpt)==1)
{
printf(“\n%s\t%s\t%s\t%s\t%d\n”,v.fname,v.sname,v.street,v.city,v.sal);
}
rewind(fpt);
char empname[20];
printf(“\nEnter First-Name to Modify”);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 227


Solved Example
scanf(“%s”,&empname);
char ch=’Y’;
while(fread(&v,sizeof(v),1,fpt)==1)
{
if(strcmp(empname,v.fname)!=0)
fwrite(&v,sizeof(v),1,tfpt);
else
{
clrscr();
printf(“Name\tSurname\tStreet\tCity\tSalary\n”);
printf(“\n%s\t%s\t%s\t%s\t%d\n”,v.fname,v.sname,v.street,v.city,v.sal);
printf(“Are You Sure To Modify Y/N”);
ch=toupper(getche());
if(ch==’N’) goto down;
printf(“\nEnter FName\tLName\tStreet\tCity\tSalary\n”);
scanf(“%s %s %s %s %d”,v.fname,v.sname,v.street,v.city,v.sal);
down:
fwrite(&v,sizeof(v),1,tfpt);
}
}
fclose(fpt);
fclose(tfpt);
remove (“info.dat”);
rename (“temp.dat”,”info.dat”);
}

a. A data file “ADDRESS.txt” contains name, post and salary of employees. Write a program to
update the salary of every employee by 25%.

228 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


a. Write to a text file using fprintf().
Solution :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen(“C:\\program.txt”,”w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num: “);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
return 0;
}

b. Write a program to read from a text file using fscanf().


Solution :
#include <stdio.h>
#include <stdlib.h>
int main() {
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.txt”,”r”)) == NULL)
{
printf(“Error! opening file”);
exit(1);
}
fscanf(fptr,”%d”, &num);
printf(“Value of n=%d”, num);
fclose(fptr);
return 0;
}
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 229
c. Write a C program to copy data from one file to another file.
Solution :
#include<stdio.h>
int main()
{
FILE *p,*q;
char file1[20],file2[20];
char ch;
printf(“\nEnter the source file name to be copied:”);
gets(file1);
p=fopen(file1,”r”);
if(p==NULL){
printf(“cannot open %s”,file1);
exit(0);
}
printf(“\nEnter the destination file name:”);
gets(file2);
q=fopen(file2,”w”);
if(q==NULL)
{
printf(“cannot open %s”,file2);
exit(0);
}
while((ch=getc(p))!=EOF)
putc(ch,q);
printf(“\nCOMPLETED”);
fclose(p);
fclose(q);
return 0;
}

d. Write a C program to read name and marks of n number of students from user and store them in a
file. If the file previously exits, add the information of n students.
Solution :
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf(“Enter number of students: “);
scanf(“%d”, &num);

230 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


FILE *fptr;
fptr = (fopen(“C:\\student.txt”, “a”));
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
for(i = 0; i < num; ++i)
{
printf(“For student%d\nEnter name: “, i+1);
scanf(“%s”, name);
printf(“Enter marks: “);
scanf(“%d”, &marks);
fprintf(fptr,”\nName: %s \nMarks=%d \n”, name, marks);
}
fclose(fptr);
return 0;
}

e. Write a C program to write all the members of an array of structures to a file using fwrite(). Read the
array from the file and display on the screen.
Solution:
#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main()
{
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen(“file.txt”,”wb”);
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf(“Enter name: “);
gets(stud1[i].name);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 231


printf(“Enter height: “);
scanf(“%d”, &stud1[i].height);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);
fptr = fopen(“file.txt”, “rb”);
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf(“Name: %s\nHeight: %d”, stud2[i].name, stud2[i].height);
}
fclose(fptr);
}

f. Write a program which produces its own source code as its output.
Solution :
#include<stdio.h>
int main(){
FILE *p,*q;
char file1[20],file2[20];
char ch;
printf(“\nEnter the source file name to be copied:”);
gets(file1);
p=fopen(file1,”r”);
if(p==NULL)
{
printf(“cannot open %s”,file1);
exit(0);
}
printf(“\nEnter the destination file name:”);
gets(file2);
q=fopen(file2,”w”);
if(q==NULL)
{
printf(“cannot open %s”,file2);
exit(0);
}

232 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concepts Review
Topic Key Concepts
File Handling in C-program A file is a collection of related records.
A record is a collection of related fields.
Field is a single data item of record. Such as First-name or
Last-name or Address, etc.
File is a structure which contains information about the file
being used such as file size, location, etc.
Data file can be opened in different modes, like read, write
or append, etc.
After reading or writing operation on opened file, we must
close a file.
When we try to open a file in read mode with fopen()
function, it returns file pointer. When a file fails to open due
to some reason, function returns null pointer.
The rewind() function places the file pointer to the beginning
of the data file.

a. What is a data file? What are the two types of input/ouput operation?
b. How do you open a data file in file handling?
c. What is the function and syntax of the following statement?
i. getc() ii. putc()
d. What is the difference between sequential access file and random access file?
e. What is the use of +w mode in file handling?

In the Lab
a. Write a program to store different integer numbers on the data file unsorted.dat. Read
the same numbers from the data file unsorted.dat and arrange the numbers in ascending
order, store them in another data file sorted.dat. Display the sorted data on the monitor
also.
b. Write a program to create a data file named Tele.dat, which allows storing first-name, last-
name, address, and telephone. Program should allow user to enter records according to
his or her choice.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 233
c. Write a program to open a data file named Tele.dat. Display the information of a person
asking first-name or last-name.
d. Write a program to open a data file named Tele.dat. Delete a record of a person asking
his or her name.
e. Write a program to ask name, location, contact number and number of staff of a school
and store them in a data file “info.dat”.
f. Write a program to create a data file “student.dat” to store name, roll, address and DOB
of a student.
g. Write a program to create a data file “record.dat” to store name, ID number, address and
contact number.
h. Write a program in C to create a data file “book.txt” which ask the Book’s Title, Author’s
name, Edition date, price and copies of books. Program should ask the user’s choice for
more records.
i. Write a program to display all the records from “bank.dat” where data are name, ID
number, address and contact number.
j. A data file “test.txt” contains name and marks secured in three subjects. Write a program
to count the students who has secured more than 70%.
k. Write a program to display all the records from “sal.dat” for the employees whose salary
is more than 5000 and increase their salary by 20%.
l. Write a program to ask students’ name, class and marks secured in three subjects. Store
the data in a data file “RESULT.DAT” along with the total marks. Make a provision to ask
the user to enter another record.
m. Write a program which reads records from the file “RESULT.DAT” having the fields name,
and marks of three different subjects and display only those records whose percentage is
greater than 60 and less than 80. Also count the total number of records present in that
data file.
n. Write a program to display all records from a data file info.dat that contains the fields
employee’s name, post, department and salary. Also count the total number of records
whose salary is more than 5000.
o. A data file “INFO.INF” has numerous records in it with name, address and telephone
numbers in each record. Write a program to scan all the records from that file and display
only the records with address “Kathmandu”.
p. A data file result.dat contains the name and marks secured by students in three subjects.
Assuming that mark for each subject is 32, write a C program to count the number of
passed students.
q. A data file “ADDRESS.INF” contains name, post and salary of employees. Write a program
to update the salary of every employee by 25%.

234 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Chapter
Object
Oriented
5 Programming

Concept
With the rapidly changing world, and the highly competitive and versatile nature of
industry, the operations are becoming more and more complex. In view of the
increasing complexity of software systems, the software industry and software engineer
continuously look for the new approaches to software design and development.
The increased complexity had become the chief problem with computer programs
in traditional languages. Large programs, because of this complexity, are more prone
to errors, and software errors can be expensive and even life-threatening. The most
adopted and popular programming approach, structured programming approach,
failed to show the desired results in terms of bug-free, easy to maintain, and reusable
programs. The latest programming approach, Object-Oriented Programming (OOP),
offers a new and powerful way to cope with this complexity. Its goal is clearer, more
reliable and more easily maintained programs.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 235


Programming Paradigms
Paradigm is a method to solve some problems or do some tasks. Programming paradigm is
an approach to solve a problem using some programming language. Paradigms are important
because they define a programming language and how it works. There are lots for programming
language that are known but all of them need to follow some strategy when they are
implemented and this methodology/strategy is paradigms. Apart from varieties of programming
language there are lots of paradigms to fulfil each and every demand. Programming paradigms
are of three types. They are procedural, structural and object oriented.

Procedural Programming
Procedural programming can also be referred to as imperative programming. It is a programming
paradigm based upon the concept of procedure calls, in which statements are structured into
procedures (also known as subroutines or functions). They are a list of instructions to tell the
computer what to do step by step, Procedural programming languages are known as top-
down languages. Most of the early programming languages are all procedural. Examples of
Fortran C and Cobol.
The paradigm is:
Decide which procedures you want.
Use the best algorithm you can find.

Advantages of Procedural Programming


a. Procedural Programming is excellent for general-purpose programming.
b. The coded simplicity along with ease of implementation of compilers and interpreters.
c. A large variety of books and online course material available on tested algorithms, making
it easier to learn.
d. The source code is portable.
e. The code can be reused in different parts of the program, without the need to copy it.
f. The program flow can be tracked easily as it has a top-down approach.

Disadvantages of Procedural Programming


a. The program code is harder to write when procedural programming is employed.
b. The procedural code is often not reusable, which may pose the need to recreate the
code if is needed to use in another application.
c. Difficult to relate with real-world objects.
d. The importance is given to the operation rather than the data, which might pose issues in
some data-sensitive cases.
e. The data is exposed to the whole program, making it not so much security friendly.

236 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Structured Programming
Structured programming (sometimes known as modular programming) is a programming
paradigm that facilitates the creation of programs with readable code and reusable components.
Structured programming encourages dividing an application program into a hierarchy of
modules or autonomous elements, which may, in turn, contain other such elements. Within
each element, code may be further structured using blocks of related logic designed to improve
readability and maintainability. The languages that support Structured programming approach
are: C, C++, Java and C#.

Advantages of Structured Programming


a. It is easy to understand.
b. It consists statement of English vocabulary.
c. It needs less time to write code.
d. It is easier to maintain.
e. It can be debugged easily.
f. Most of the high-level programming languages support this paradigm
g. It is machine independent, which means the structured programming written in one
computer can be run on any other computer.

Disadvantages of Structured Programming


a. It is a machine-independent so we need a translator to convert it into machine language.
b. The program depends upon changeable factors like data-types. Therefore, it needs to be
updated with the need on the go.

Object Oriented Programming (OOP)


Object Oriented Programming (OOP) is an approach to standardize the programs by creating
partitioned memory area for both data and function. It has been developed to increase the
programmer’s productivity and also to overcome the weaknesses of traditional approach of
programming. OOP does not allow data to flow freely from function to function and procedure
to procedure. In this system, the complete problem is broken into number of entities called
objects. These objects are created and maintained along with a set of related data. The data
is so used and maintained that they cannot be changed or edited from another function or
object. The data of an object can be object can access the function of another object. Different
object oriented programming languages are C++, java, small talk, simula-67 and Eiffel.
The paradigm is:
Decide which classes and objects are needed;
Provide a full set of operations for each class

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 237


Features of OOP
Some key features of the Object Oriented Programming are:
a. Emphasis on data rather than procedure.
b. Programs are divided into entities known as objects.
c. Data Structures are designed such that they characterize objects.
d. Functions that operate on data of an object are tied together in data structures.
e. Data is hidden and cannot be accessed by external functions.
f. Objects communicate with each other through functions.
g. New data and functions can be easily added whenever necessary.
h. Follows bottom up design in program design.

Advantages of OOP
The advantages of Object Oriented Programming are:
a. The programmes written with OOP are really easy to understand.
b. Since everything is treated as objects, so we can model a real-world concept using OOP.
c. OOP approach offers the reusability of classes. We can reuse the classes that are already
created without writing them again and again.
d. Since the parallel development of classes is possible in OOP concept, It results in the quick
development of the complete programmes.
e. Programmes written in OOP technique are marginally easier to test, manage as well as
maintain.
f. It is a secured development technique since data is hidden and can’t be accessed by
external functions.

Disadvantages of OOP
The disadvantages of Object Oriented Programming are:
a. Sometimes, the relation among the classes become artificial in nature.
b. The programmer should have a proper planning before designing a program using OOP
approach.
c. Since everything is treated as objects in OOP, the programmers need proper skill such as
design skills, programming skills, thinking in terms of objects etc.
d. The size of programmes developed with OOP is larger than the procedural approach.
e. Object-oriented programs are typically slower than procedure-based programs, as they
typically require more instructions to be executed.
238 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
Basic Elements of OOP
The basic elements of object oriented programming are Object, Class, Data abstraction, Data
encapsulation, Inheritance, Polymorphism and Overloading.

Object
Objects are the basic identifiable runtime entities in object-oriented programming. Objects
may represent a real-world entity like a person, a car, a place, a house etc. For instance, we
can say ‘car’ is an object which has some special characteristics like the ‘number of gears’,
‘colour’ etc. and it also holds some functions like ‘braking’, ‘accelerating’ and so on. When we
compare a software object with real world object, the characteristics and behaviour of real
world objects are referred to as data members and member functions of software objects
respectively. So, an object represents an entity that can store data and has its interface through
functions.

Class
A class is a structure of making a user-defined data type which holds the entire set of data of an
object. So, a class is basically a blueprint or a template of a set of objects which shares some
common properties and behaviours. We can also say that a class is a collection of similar types
objects.
Once a class is created, we can create any number of objects belonging to that class. Actually,
a class doesn’t specify any data, it determines the properties or methods that may contain in
an object of that class. Classes normally act like a built-in data type, but they are actually a user-
defined data types.
For example, ‘Dog’ is a class which holds properties like ‘dog name’, ‘age of the dog’, ‘weight
of the dog’ etc. Now, if we have two dogs named ‘Tommy’ and ‘Jenna’, then they will have
their own properties like name, age and weight; which may be different for both the dog but
they are similar in types. So, the two dogs ‘Tommy’ and ‘Jenna’ will be called as objects of
the class ‘Dog’. Here the class ‘Dog’ is representing the common properties of both the two
objects named as ‘Tommy’ and ‘Jenna’.
Objects

TOMMY
Class

DOG

JENNA

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 239


Data abstraction
Data abstraction is a concept which hides the background details and represents only the
needed information to the outside world. It is the simplification process of real-world concept
into its absolutely necessary component.
For example, you are riding a bike, You only know the essential methods to ride a bike like
accelerating, braking, how to change the gears, using the clutch, etc. but while riding you don’t
need the internal details of the bike like gearbox, fuel-injection or carburetor, workings of the
motor, engine blocks, etc. You just use the accelerator and your bike starts moving, You don’t
need to know the details of what happening inside to ride the bike. This is called abstraction
as you only know the essential parts to ride a bike without including the background process
or explanation.

Data encapsulation
Data encapsulation is one of the most important concepts of object oriented programming. It
is a technique which combines both data members and functions, operates on that data in a
single unit known as a class. This technique basically prevents the access to the data directly.
The only way to access the data is provided by the functions.
If you want to read a data in an object, you have to call the member function in the object. The
function will read the data and return the data back to you. So, you have no access to the data
directly. Since data is hidden, it is secured from accidental alteration.
For example, consider a big company which may have different departments like production,
marketing, sales, account, etc. Each department has its own manager to maintain its data. If the
production manager wants to know the sales data of last month, the sales department would
not be allowed to himself go through the sales department data files. So, he will have to write
a letter to the sales department requesting the data required.
Then sales manager will go through the sales data files and sends a reply with asked information.
Which implies that data is accessed currently and has no chance of data leak to the outside of
that department. This is a real-life example concept of data encapsulation.

Inheritance
Inheritance is also an important characteristic of OOP. It is basically a method which provides a
way that capabilities and properties from one class to come into another class. This technique
provides code reusability to the programmers. We can form a new class from an existing class,
where the existing class contains some properties or methods that also exist in the new class.
Here the new class is called as the derived class and the existing class i.e. the class from which
the new class is derived is called as the base class.
For instance, ‘vehicle’ is a class with some properties and methods. The ‘car’ and ‘bus’ is also
two classes which have some properties and methods that already exist in the class ‘vehicle’.
So, both the classes ‘car’ and ‘bus’ can inherit some of its properties from the class ‘vehicle’.
So, here the class ‘vehicle’ is a base class and the classes ‘bus’ and ‘car’ are the derived classes
of ‘vehicle’.
240 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
Polymorphism
Polymorphism is the ability for a message or data to be processed in more than one form. It
supports the capability of an object of a class to behave differently in response to a message
or action.
For a real-life example, consider yourself. At the same time, you may have some different
characteristics like a student, a guitarist or a football player. This is called polymorphism, since
you have some different forms or characteristics with respect to a different action or situation.

Overloading
Overloading is the capability of a single function to perform different task depending on the
situation. When an existing function or operator is to be operated on new data type, it is called
as overloaded. Overloading allows creating different methods with the same name which
differ from each other in the type of the input and the output of the function. It can be used
with both functions and members.

Applications of using OOP


Main application areas of OOP are:
a. User interface design and Real Time Systems
b. Simulation and Modeling
c. Object oriented databases
d. AI, Expert System, Neural Networks and parallel programming
e. Decision support and office automation system

Difference between structured programming and object oriented programming


Structured Programming Object Oriented Programming
Structured programming is designed which Object oriented programming is designed
focuses on process/ logical structure and which focuses on data.
then data required for that process.
Structured programming follows top-down Object oriented programming follows bottom-
approach. up approach.
Programs are divided into small self Programs are divided into a number of entities
contained functions. called objects.
Structured programming is less secure as Object oriented programming is more secure
there is no way of data hiding. as having data hiding feature.
Data is open and can be freely accessed by Data is hidden inside the object and cannot be
all the programs. accessed by external functions.
Examples of structured programming are Examples of Objected Oriented Programming
C, Pascal and QBasic are C++, Java and VB.net

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 241


Concepts Review
Topic Key Concepts
Object Oriented Programming Object Oriented Programming (OOP) is an approach to
standardize the programs by creating partitioned memory
area for both data and function.
Objects are the basic identifiable runtime entities in object-
oriented programming.
A class is a structure of making a user-defined data type
which holds the entire set of data of an object.
Data abstraction is a concept which hides the background
details and represents only the needed information to the
outside world.
Data encapsulation is a technique which combines both
data members and functions, operates on that data in a
single unit known as a class.
Inheritance is basically a method which provides a way that
capabilities and properties from one class to come into
another class.
Polymorphism is the ability for a message or data to be
processed in more than one form.

Section 1.1 (Very Short Questions)


a. What is Object Oriented Programming?
b. What do you understand by the term “data abstraction”?
c. What are the features of OOP?
d. Name any two object oriented programming.
e. What is an object?

Section 1.2 (Short Questions)


a. What are the advantages and disadvantages of OOP?
b. What do you understand by the term “data abstraction”? Explain with an example.
c. What is the difference between an object and class?
d. In what ways are encapsulation and data abstraction inter-related?
e. What are the applications of using OOP?

242 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Section 1.3 (Long Questions)
a. What is object oriented programming? How is it different from the procedure oriented
programming?
b. What are the elements of OOP?
c. What are the differences between structured programming and object oriented
programming?
d. Polymorphism and inheritance are important concept of OOP. What do you understand
by these two terms.
e. Which OOP principle implements function overloading?
f. What is an object? Give five examples of real world objects.
g. How are objects explained in terms of software?
h. Class and objects are inter-related. Explain.
i. A class is also referred to as “object factory”. Comment.
j. Why is an object called an instance of a class?
k. Explain “inheritance” with a suitable example.

Mention five attributes (data values) and appropriate methods which you can
expect from these classes.
a. Class Employee
b. Class Bank
c. Class Teacher
d. Class School
e. Class Book
f. Class Park
g. Class Medicine
h. Class Telephone
i. Class Computer
j. Class Camera

Teaching Manual
While teaching this chapter, the key concepts that need to be emphasized upon include:
a. Basic concepts of Object Oriented Programming (OOP), OOP terminology and features
and applications of OOP.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 243


Software
Chapter
Process
6 Model

Concept
Software development is the process programmers use to build computer programs. The
process, also known as the Software Development Life Cycle (SDLC), includes several
phases that provide a method for building products that meet technical specifications and
user requirements.
The SDLC provides an international standard that software companies can use to build
and improve their computer programs. It offers a defined structure for development
teams to follow in the design, creation and maintenance of high-quality software. The
aim of the IT software development process is to build effective products within a
defined budget and timeline.

244 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


System Analyst
System Analyst is an individual in charge of designing, modifying, or analyzing various systems
to ensure compatibility and user effectiveness. A system analyst uses computers and related
systems to design new IT solutions, modify, enhance or adapt existing systems and integrate new
features or improvements, all with the aim of improving business efficiency and productivity.
They must possess a high level of technical expertise and clear insights into current business
practices. Depending on the employer, clients may be internal, e.g. departments within the
same organization, or external.

Attributes of a Good System Analyst


The system analyst is a person with unique skills-common sense, a structured framework and
a disciplined approach to solving problems are a part of the analysis. Therefore the analyst
requires a combination of skills, experience, personality and common sense. The fact that a
system is designed for a specific user also means that the analyst must have interpersonal skills.
The different interpersonal skills that a system analyst should have are as follows:
a. Communication skills - System analyst should have the ability to work with all levels of
managerial positions of the organization.
b. Creativity - The analyst should be creative to help the users to model ideas
into real plans and developing candidate systems to match user
requirements.
c. Understanding - System analyst should have the ability to identify problems
and assess their solution, grasping of company goals and
objectives, show sensitivity to the impact of the system on
people at work and understanding their problems.
d. Teaching and selling ideas - System analyst should have the skill to educate other
people in the use of computer systems and selling ideas and
promoting innovations in problem solving using computers.
e. Problem solving - System analyst should have the skill of problem solving,
developing alternative solutions, scheduling, overcome
constraints, coordinating team efforts and managing costs
and accounts.
f. Dynamic interface - System analyst should be a perfect blend of both technical
and non-technical skills in functional specifications and
general design. He should also have a questioning attitude
and inquiring mind.
g. Computer knowledge - System analyst should have the knowledge of basics of
computers and business functions.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 245


Role of a Good System Analyst
1. Assists current or potential application users in identifying and describing problems or
opportunities that might be addressed either:
a) by implementing a new (automated or manual) system, or
b) by changing an existing application system.
2. Investigates such problems and opportunities to determine the feasibility of a system
solution and to identify the general kinds of system solution that appear appropriate.
3. Analyzes users’ business requirements in detail and, where appropriate, prepares
functional specifications for a proposed new (or changed) system.
4. Assists and guides prospective users of a proposed new or changed system in:
a) quantifying the benefits of having the system (or the penalties for not having it), and
b) assessing the impact of the system on their organization and on the operation of their
business.
5. Obtains rough estimates of the cost of operating and maintaining a proposed new or
changed system, assuming use of appropriate technology, tools, and methods.
6. Assists the project manager in identifying the skills and resources needed to implement a
new system or to modify an existing system, and in preparing rough estimates of:
a) the cost of developing or changing the system,
b) the duration of a project to do so.
7. Designs and develops users’ manuals and corresponding training programs for a system
being developed.
8. Assists the sponsoring users in:
a) analyzing the costs, benefits, risks, and return-on-investment of the proposed new
system,
b) understanding the exact nature of the proposed system,
c) deciding whether to proceed with the implementation.
9. Prepares, in consultation with users, implementers, and operations representatives, the
acceptance (or parallel) test plan for any new or changed system.
10. Assists the users in preparing for the installation and start-up of any new system being
implemented.

a. What is a Software development ?


b. Who is System Analyst? List the attributes of a good system analyst.
c. Explain the role of a good system analyst.

246 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


System Engineers
Software engineers are computer science professionals who use knowledge of engineering
principles and programming languages to build software products, develop computer games,
and run network control systems. A software engineer’s responsibilities may also include:
a. Working with users to determine their software needs
b. Designing, developing and testing a system or application according to the users’
specifications
c. Drawing diagrams and models that help developers create the appropriate code for the
system or application
d. Documenting the system or application in detail to help those responsible for future
maintenance
e. Maintaining the system or application with updates and fixes as necessary
f. Recommending software upgrades for existing systems or applications
g. Collaborating with developers and other engineers to create software
The attributes that smart engineers ought to posses are as follows:
a. Exposure to systematic techniques, i.e., familiarity with package engineering principles.
b. Smart technical data of the project areas (Domain knowledge).
c. Smart programming talents.
d. Smart communication skills. These skills comprise of oral, written, and interpersonal skills.
e. High motivation.
f. Sound data of fundamentals of applied science.
g. Intelligence.
h. Ability to figure in a very team.

System Development Life Cycle


SDLC is a process followed for a software project, within a software organization. It consists
of a detailed plan describing how to develop, maintain, replace and alter or enhance specific
software. The life cycle defines a methodology for improving the quality of software and the
overall development process. The SDLC aims to produce a high quality software that meets
or exceeds customer expectations, reaches completion within times and cost estimates. SDLC
is important because it breaks down the entire life cycle of software development and makes it
easier to evaluate each part of software development and also makes it easier for programmers
to work concurrently on each phase. It is also called as software development process.
An SDLC has three primary business objectives:
a. Ensure the delivery of high quality systems.
b. Provide strong management controls.
c. Maximize productivity.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 247


Importance and Necessity of System Development Life Cycle
The System Development Life Cycle helps alleviate the complexity of developing a system
information system from scratch, within a framework of structured phases that help shape
the project and manage it easily. It helps transform an idea project into a functional and fully
operational system. It also encompasses activities such as process and procedure development,
change in management, user experience, policy development, impact, and conformity to
security regulations. Another important reason for leveraging a system development life cycle
is to plan ahead of time and analyze the structured phases and goals of a specific software
system project.

System Development Model


There are various software development life cycle models defined and designed which are
followed during software development process. These models are also referred as “Software
Development Process Models”. Each process model follows a series of steps unique to its
type, in order to ensure success in process of software development.
Some of the most important and popular SDLC models followed in the industry are:
a. Waterfall Model b. Iterative Model c. Spiral Model

Waterfall Model
The waterfall model was first process model to be introduced. It is also referred to as a
linear-sequential life cycle model. It is very simple to understand and use. In a waterfall model,
each phase must be completed before the next phase can begin and there is no overlapping
in the phases. Waterfall model is the earliest SDLC approach that was used for software
development. The waterfall model illustrates the software development process in a linear
sequential flow. This means that any phase in the development process begins only if the
previous phase is complete. The waterfall approach does not define the process to go back to
the previous phase to handle changes in requirement. Therefore, different projects may follow
different approaches to handle such situations.
The sequential phases in Waterfall model are:
Requirement Gathering and Analysis
All possible requirements of the system to be developed are captured in this phase and
documented in a requirement specification document.

System Design
The requirement specifications from first phase are studied in this phase and system design is
prepared. System Design helps in specifying hardware and system requirements and also helps
in defining overall system architecture.

248 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Implementation
With inputs from system design, the system is first developed in small programs called units,
which are integrated in the next phase. Each unit is developed and tested for its functionality
which is referred to as Unit Testing.

Integration and Testing


All the units developed in the implementation phase are integrated into a system after testing
of each unit. Post integration the entire system is tested for any faults and failures.

Deployment of system
Once the functional and non functional testing is done, the product is deployed in the customer
environment or released into the market.

Maintenance
There are some issues which come up in the client environment. To fix those issues patches
are released. Also to enhance the product some better versions are released. Maintenance is
done to deliver these changes in the customer environment.

All these phases are cascaded to each other in which progress is seen as flowing steadily
downwards (like a waterfall) through the phases. The next phase is started only after the
defined set of goals are achieved for previous phase and it is signed off, so the name “Waterfall
Model”. In this model, phases do not overlap.

Requirements analysis
and definition

System design

Implementation and
unit testing

Integration and system


testing

Operation and
maintenance
Advantages of Waterfall Model
The waterfall model is the oldest and most widely used model in the field of software
development. There are certain advantages of this model, which makes it, one of the most
widely used models as yet. Some of them are:

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 249


1. Being a linear model, it is very simple to implement.
2. The amount of resources required to implement this model are minimal.
3. Documentation is produced at every stage of the software’s development. This makes
understanding the product designing procedure, simpler.
4. After every major stage of software coding, testing is done to check the correct running
of the code.

Disadvantages of Waterfall Model


Some of the disadvantages of waterfall model are:
1. You cannot go back a step; if the design phase has gone wrong, things can get very
complicated in the implementation phase.
2. Often, the client is not very clear of what he exactly wants from the software. Any changes
that he mentions in between, may cause a lot of confusion.
3. Small changes or errors that arise in the completed software may cause a lot of problems.
4. Until the final stage of the development cycle is complete, a working model of the
software does not lie in the hands of the client. Thus, he is hardly in a position to inform
the developers, if what has been designed is exactly what he had asked for.

Spiral Model
The spiral model is a new approach towards Objectives Risk identification
software development, which is considered to be determining and resolving
an ideal option for projects in which complexity is
much higher and the costs involved are expected
to be greater. It can be defined as a model based
on SDLC (system development life cycle), which
integrates the characteristics of the waterfall model
and the prototyping model. The waterfall model is
a method of sequential and linear advancement of
a development through different stages, while the
Evaluation and Development and
prototyping model constitutes building and testing of planning testing
a required prototype.
The spiral model has four phases. A software project repeatedly passes through these phases
in iterations called spirals.
Identification
This phase starts with gathering the business requirements in the baseline spiral. In the
subsequent spirals as the product matures, identification of system requirements, subsystem
requirements and unit requirements are all done in this phase. This also includes understanding
the system requirements by continuous communication between the customer and the system
analyst. At the end of the spiral the product is deployed in the identified market.

250 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Design
Design phase starts with the conceptual design in the baseline spiral and involves architectural
design, logical design of modules, physical product design and final design in the subsequent
spirals.

Construct or Build
Construct phase refers to production of the actual software product at every spiral. In the
baseline spiral when the product is just thought of and the design is being developed a POC
(Proof of Concept) is developed in this phase to get customer feedback. Then in the subsequent
spirals with higher clarity on requirements and design details a working model of the software
called build is produced with a version number. These builds are sent to customer for feedback.

Evaluation and Risk Analysis


Risk Analysis includes identifying, estimating, and monitoring technical feasibility and management
risks, such as schedule slippage and cost overrun. After testing the build, at the end of first
iteration, the customer evaluates the software and provides feedback.

Advantages of Spiral Model


1. The spiral model is a flexible SDLC model which allows the development phases to be
determined and adjusted depending upon the project’s complexity.
2. Effective monitoring of the project development is possible as each phase as well as loop,
requires inputs and feedback from those associated with the project.
3. Risk management is an in-built feature of this model. The project is typically divided into
smaller pats and the risky ones are taken care of earlier in the development.
4. Changes to the design can be introduced at any stage of the development life cycle and
can be easily accommodated in the process.
5. Spiral model is most suited for the development of new, customized or high-risk projects.

Disadvantages of Spiral Model


1. The spiral model is an unnecessarily complicated design methodology especially for
projects in which the software requirement specifications are clear and definite. It is also
not feasible for many low-risk projects.
2. This model requires that the developers possess a high-level skill-set which is a necessity
for reviewing the prototype in each phase and loop of the development.
3. More number of documents and files need to be generated (for every intermediate stage)
as compared to other models.
4. Due to client feedback and subsequent customization and modifications carried out in
the various stages of development, reusing the prototypes in future projects becomes
difficult.
5. Since this model involves loops or stages, the cost of implementation is high.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 251


Prototyping Model
The Prototyping Model is a system development method (SDM) in which a prototype (an early
approximation of a final system or product) is built, tested, and then reworked as necessary
until an acceptable prototype is finally achieved from which the complete system or product
can now be developed. This model works best in scenarios where not all of the project
requirements are known in detail ahead of time. It is an iterative, trial-and-error process that
takes place between the developers and the users.
Following is the stepwise approach to design a software prototype:

Basic Requirement Identification


This step involves understanding the very basic product requirements especially in terms
of user interface. The more intricate details of the internal design and external aspects like
performance and security can be ignored at this stage.

Developing the initial Prototype


The initial prototype is developed in this stage, where the very basic requirements are show-
cased and user interfaces are provided. These features may not exactly work in the same
manner internally in the actual software developed and the work around are used to give the
same look and feel to the customer in the prototype developed.

Review of the Prototype


The prototype developed is then presented to the customer and the other important
stakeholders in the project. The feedback is collected in an organized manner and used for
further enhancements in the product under development.

Revise and enhance the Prototype


The feedback and the review comments are discussed during this stage and some negotiations
happen with the customer based on factors like, time and budget constraints and technical
feasibility of actual implementation. The changes accepted are again incorporated in the new
prototype developed and the cycle repeats until customer expectations are met.

Identify Problems Initial Requirements Develop Prototype

e
totyp
Pro
rking
Wo
New Requirements

Problems
Implement and Use Revise and Enhance
Prototype Prototype
Next Version

252 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Advantages of Prototype Model
1. Users are actively involved in the development.
2. Since in this methodology a working model of the system is provided, the users get a
better understanding of the system being developed.
3. Errors can be detected much earlier.
4. Quicker user feedback is available leading to better solutions.
5. Missing functionality can be identified easily.

Disadvantages of Prototype Model


1. Leads to implementing and then repairing way of building systems.
2. Increase the complexity of the system as scope of the system may expand beyond original
plans.
3. Incomplete application may cause application not to be used as the full system.
4. Incomplete or inadequate problem analysis.

SDLC A process followed for a software project, within a software


organization.
Waterfall Model A linear, sequential approach to the software development
life cycle (SDLC) that is popular in software engineering and
product development.
Spiral Model A risk-driven software development process model.

a. What is SDLC? What are the three primary business objectives?


b. Explain the different models of system development.
c. What is spiral model? List any three advantages of spiral model.
d. What is prototype model? List any three advantages of prototype model.

System Development Phases


The System Development Life Cycle (SDLC) is a series of various steps that a project team
works through in order to conceptualize, analyze, design, construct and implement a new
information technology system. Any system development process, in general, is understood
to have the following phases.
System Investigation System Analysis System Design Coding
Testing Implementation Maintenance
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 253
System Investigation
Preliminary investigation is the first step in the system development project. The preliminary
investigation is a way of handling the user’s request to change, improve or enhance or existing
system. The objective is to determine whether the request is valid and feasible before any
recommendation is made to do nothing, improve or modify the existing system, or build
altogether a new one. It is not a design study, nor does it include the collection of details to
completely describe the business system. The following objectives should be accomplished,
while working on the preliminary investigation system investigation includes the following two
sub-stages.
a. Problem definition
b. Feasibility study

Problem Definition
Problem definition is the most frequently bypassed step in the entire system development
process. So the first responsibility of a system analyst is to prepare a written statement of the
objectives and scope of the problem. Based on interviews with the user, the analyst writes
a brief description of his/her understanding of the problem, and reviews it with both groups,
ideally in a joint user/information analyst meeting people respond to written statements. They
ask for clarification and they correct obvious errors or misunderstandings.
In other words, proper understanding and definition of the problem is essential to discover the
cause of the problem and to plan a directed investigation by asking questions like what is being
done? Why? Is there any underlying reason different from the one the user identifies? Here are
some possible definitions of problems.
a. The existing system has a poor response time, i.e. it is slow.
b. It is unable to handle the workload.
c. The problem of cost, i.e. the existing system is not economical.
d. The problem of accuracy and reliability.
e. The requisite information is not produced by the existing system.
f. The problem of security.
Similarly, a system analyst should provide a rough estimate of the cost involved for the system
development. This is again a very important question that too often is not asked until it is quite
late in the system development process.

Feasibility Study
In case the system proposal is acceptable to the management, the next phase is to examine the
feasibility of the system. The feasibility study is basically the test of the proposed system in the
light of its workability, meeting user’s requirements, effective use of resources and of course,
the cost effectiveness. These are categorized as technical, operational, economic, schedule

254 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


and social feasibility. The main goal of feasibility study is not to solve the problem but to
achieve the scope. In the process of feasibility study, the cost and benefits are estimated with
greater accuracy to find the Return on Investment (ROI). This also defines the resources
needed to complete the detailed investigation. The result is a feasibility report submitted to the
management. This may be accepted or accepted with modifications or rejected.

Organizational feasibility
The extent to which a proposed information system supports the objective of the organizations
strategic plan for information systems determines the organizational feasibility of the system
project. The information system must be taken as a sub-set of the whole organization.

Economic feasibility
In this study, cost and returns are evaluated to know whether returns justify the investment
in the system project. The economic question raised by analysts during the preliminary
investigation are for the purpose of estimating the following:
a. The cost of conducting a full system investigation.
b. The cost of hardware and software for the class of application being considered.
c. The benefits in the form of reduced costs, improved customer service, improved resource
utilization or fewer costly errors.

Technical feasibility
Whether reliable hardware and software, capable the meetings the needs of the proposed
system can be acquired or developed by the organization in the required time is a major
concern of the technical feasibility. In other words, technical feasibility includes question like:
a. Does the necessary technology exist to do what is suggested and can it be acquired?
b. Does the proposed equipment have the technical capacity to hold the data required to
use the new system?
c. Will the proposed system provide adequate responses, regardless of the number of
locations and users?
d. Can the system be expanded?
e. Is there any technical surety of accuracy, reliability, ease of access and data security?

Operational feasibility
The willingness and ability of the management, employees, customers, suppliers, etc., to
support a proposed system come under operational feasibility. In other words, the rest of
operational feasibility asks if the system will work when it is developed and installed. Are there
major barriers to implementation? The following questions are asked in operational feasibility.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 255


a. Is there sufficient support from the management? From employees? From customers?
From suppliers?
b. Are current business methods acceptable to the users?
c. Have the users been involved in the planning and development of the system project?
Operational feasibility would pass, the test if the system is developed as per rules, regulations,
laws, organizational culture, union agreements, etc., and above all with the active involvement
of the users.

System Analysis
Systems analysis is a process of collecting factual data, understand the processes involved,
identifying problems and recommending feasible suggestions for improving the system
functioning. This involves studying the business processes, gathering operational data,
understand the information flow, finding out bottlenecks and evolving solutions for overcoming
the weaknesses of the system so as to achieve the organizational goals. System Analysis also
includes subdividing of complex process involving the entire system, identification of data store
and manual processes.
System analysis involves a detailed study of:
a. The information needs of the organization and its users.
b. Existing information systems (their activities, resources and products).
c. The expected information system (in terms of capabilities of IS required to meet the
information needs of users).
It is more of a thinking process and involves the creative skills of the system analyst. It attempts
to give birth to a new efficient system that satisfies the current needs of the user and has scope
for future growth within the organizational constraints. The result of this process is a logical
system design. System analysis is an iterative process that continues until a preferred and
acceptable solution emerges.

System Design
Based on the user requirements and the detailed analysis of a new system, the new system
must be designed. This is the phase of system designing. It is the most crucial phase in the
development of a system. System analysis describes WHAT a system should do to meet the
information needs of users. System design specifies HOW the system will accomplish this
objective. The term design refers to the technical specification that will be implied in constructing
the system. Input, output, databases, forms, codification schemes and processing specifications
are drawn up in detail. In the design stage, the programming language and the hardware and
software platform in which the new system will run are also decided. Data structure, control
process, equipment source, workload and limitation of the system, Interface, documentation,
training, procedures of using the system, taking backups and staffing requirement are decided
at this stage.

256 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


There are several tools and techniques used for describing the system design of the system.
These tools and techniques are: Flowchart, Data Flow diagram (DFD), Data Dictionary,
Structured English, Decision Table and Decision Tree.

Coding
The system design needs to be implemented to make it a workable system. This demands
the coding of design into computer language, i.e., programming language. This is also called
the programming phase in which the programmer converts the program specifications into
computer instructions, which we refer to as programs. It is an important stage where the
defined procedures are transformed into control specifications by the help of a computer
language. The programs coordinate the data movements and control the entire process in a
system. A well written code reduces the testing and maintenance effort. It is generally felt that
the programs must be modular in nature. This helps in fast development, maintenance and
future changes, if required. Programming tools like compilers, interpreters and language like
c, c++, and java etc., are used for coding .with respect to the type of application. The right
programming language should be chosen.

Testing
Before actually implementing the new system into operations, a test run of the system is done
removing all the bugs, if any. It is an important phase of a successful system. After codifying the
whole programs of the system, a test plan should be developed and run on a given set of test
data. The output of the test run should match the expected results. Sometimes, system testing
is considered as a part of implementation process.
The two types of systems testing are:
White Box Testing : In this testing, a programmer can test cases that guarantee
that every individual part in a program has been exercised at
least once, all logical decisions on their true and false sides are
executed, all loops are executed properly or not and internal
data structures to ensure their validity are exercised. In other
words, white box testing is a method of testing software that
is based on knowledge of how the software is intended to
function. White box testing is also called as structural testing or
glass-box testing.
Black Box Testing : Black box testing focuses on how the software functions without
references to how it is designed. The primary concern is
whether the program works or not, how it is constructed. Black
box testing is also known as functional testing. A programmer
attempts to find errors in the following categories:
a. Incorrect or missing functions
b. Interface errors

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 257


c. Errors in data structures or external database access
d. Performance errors
e. Initialization and termination errors.

Implementation
Implementation is the stage of a project during which theory is turned into practice. The
major steps involved in this phase are: Acquisition and Installation of Hardware and Software,
Conversion, User Training and Documentation
The hardware and the relevant software required for running the system must be made
fully operational before implementation. The conversion is also one of the most critical and
expensive activities in the system development life cycle. The data from the old system needs
to be converted to operate in the new format of the new system. The database needs to be
setup with security and recovery procedures fully defined.
During this phase, all the programs of the system are loaded onto the user’s computer.
After loading the system, training of the user starts. Main topics of such type of training are:
a. How to execute the package?
b. How to enter the data?
c. How to process the data (processing details)?
d. How to take out the reports?
After the users are trained about the computerized system, working has to shift from manual
to computerized working.

Maintenance
Maintenance is necessary to eliminate errors in the system during its working life and to tune
the system to any variations in its working environments. It must meet the scope of any future
enhancement, future functionality and any other added functional features to cope up with the
latest future needs. It has been seen that there are always some errors found in the systems
that must be noted and corrected. It also means the review of the system from time to time.
The review of the system is done for:
a. Knowing the full capabilities of the system
b. Knowing the required changes or the additional requirements
c. Studying the performance
If a major change to a system is needed, a new project may have to be set up to carry out the
change. The new project will then proceed through all the above life cycle phases.

a. List out the different phases of SDLC. Explain each of them.


b. What is feasibility study? Explain the different levels of feasibility study.
c. Explain the differences between white box testing and black box testing.

258 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concept of Requirements Gathering
Requirements gathering is a crucial part of any project, large or small. It is essential to
understanding and fulfilling the needs of the customers. The process of requirement gathering
include identifying and documenting the necessary requirements of customers, users,
stakeholders etc. related to the project. This knowledge will be used to develop solutions in
the form of products, services, software etc.
The following are some of the well-known requirements gathering techniques:
Brainstorming
Brainstorming is used in requirement gathering to get as many ideas as possible from group
of people. Generally used to identify possible solutions to problems, and clarify details of
opportunities.

Document Analysis
Reviewing the documentation of an existing system can help when creating AS–IS process
document, as well as driving gap analysis for scooping of migration projects. In an ideal world,
we would even be reviewing the requirements that drove creation of the existing system – a
starting point for documenting current requirements. Nuggets of information are often buried
in existing documents that help us ask questions as part of validating requirement completeness.

Focus Group
A focus group is a gathering of people who are representatives of the users or customers of a
product to get feedback. The feedback can be gathered about needs/opportunities/ problems
to identify requirements, or can be gathered to validate and refine already elicited requirements.
This form of market research is distinct from brainstorming in that it is a managed process with
specific participants.

Interface analysis
Interfaces for a software product can be human or machine. Integration with external systems
and devices is just another interface. User centric design approaches are very effective at
making sure that we create usable software. Interface analysis – reviewing the touch points
with other external systems is important to make sure we don’t overlook requirements that
aren’t immediately visible to users.

Interview
Interviews of stakeholders and users are critical to creating the great software. Without
understanding the goals and expectations of the users and stakeholders, we are very unlikely
to satisfy them. We also have to recognize the perspective of each interviewee, so that, we
can properly weigh and address their inputs. Listening is the skill that helps a great analyst to
get more value from an interview than an average analyst.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 259


Observation
By observing users, an analyst can identify a process flow, steps, pain points and opportunities
for improvement. Observations can be passive or active (asking questions while observing).
Passive observation is better for getting feedback on a prototype (to refine requirements),
where active observation is more effective at getting an understanding of an existing business
process. Either approach can be used.

Prototyping
Prototyping is a relatively modern technique for gathering requirements. In this approach,
you gather preliminary requirements that you use to build an initial version of the solution - a
prototype. You show this to the client, who then gives you additional requirements. You change
the application and cycle around with the client again. This repetitive process continues until
the product meets the critical mass of business needs or for an agreed number of iterations.

Requirement Workshops
Workshops can be very effective for gathering requirements. More structured than a
brainstorming session, involved parties collaborate to document requirements. One way to
capture the collaboration is with creation of domain-model artifacts (like static diagrams, activity
diagrams). A workshop will be more effective with two analysts than with one.

Reverse Engineering
When a migration project does not have access to sufficient documentation of the existing
system, reverse engineering will identify what the system does. It will not identify what the
system should do, and will not identify when the system does the wrong thing.

Survey/Questionnaire
When collecting information from many people – too many to interview with budget and time
constraints – a survey or questionnaire can be used. The survey can force users to select from
choices, rate something (“Agree Strongly, agree…”), or have open ended questions allowing
free-form responses. Survey design is hard – questions can bias the respondents.

a. Explain the requirements gathering techniques.


b. What is a focus group?
c. What is prototyping?
d. What is reverse engineering?

260 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concept of System Design Tools
Software analysis and design includes all activities, which help the transformation of requirement
specification into implementation. Requirement specifications specify all functional and non-
functional expectations from the software. These requirement specifications come in the
shape of human readable and understandable documents, to which a computer has nothing
to do. Software analysis and design is the intermediate stage, which helps human-readable
requirements to be transformed into actual code. The main tools which are used for the
purpose are given below: DFD, Context Diagram, E-R Diagram, System Flow Chart, Decision
Table, Decision Tree, Use Case and UML.

Data Flow Diagram (DFD)


Data Flow Diagram (DFD) is a graphical representation of the logical flow of data. It illustrates
how data is processed by a system in terms of inputs and outputs. As its name indicates its
focus is on the flow of information, where data comes from, where it goes and how it gets
stored. It is also known as a bubble chart. Its aim is to clarify the system requirements and
identify major transformation that will become programs in system design. It decomposes the
requirement specifications down to the lowest level of details.

Defining DFD Components


DFDs consist of four basic components that illustrate how data flows in a system: entity,
process, data store and data flow.

Entity Process Data Store


Data Flow

Entity
An entity is the source or destination of data. The source in a DFD represents these entities
that are outside the context of the system. Entities either provide data to the system (referred
to as a source) or receive data from it (referred to as a sink). Entities are often represented as
rectangles (a diagonal line across the right-hand corner means that this entity is represented
somewhere else in the DFD). Entities are also referred to as agents, terminators, or source/
sink.

Process
The process is the manipulation or work that transforms data, performing computations,
making decisions (logic flow), or directing data flows based on business rules. In other words,
a process receives input and generates some output. Processes can be drawn as circles or a
segmented rectangle on a DFD, and include a process name and process number.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 261
Data Store
A data store is where a process stores data between processes for later retrieval by that same
process or another one. Files and tables are considered data stores. Data stores are usually
drawn as a rectangle with the right-hand side missing and labeled by the name of the data
storage area it represents.

Data Flow
Data flow is the movement of data between the entity, the process, and the data store. Data
flow portrays the interface between the components of the DFD. The flow of data in a DFD
is named to reflect the nature of the data used (these names should also be unique within a
specific DFD). Data flow is represented by an arrow, where the arrow is annotated with the
data name.

DFD rules and tips


a. Each process should have at least one input and an output.
b. Each data store should have at least one data flow in and one data flow out.
c. Data stored in a system must go through a process.
d. All processes in a DFD go to another process or a data store.

Levels of DFD
The different levels of DFD are:

Context Diagram
A context diagram is a data flow diagram that only shows the top level, otherwise known as
Level 0. At this level, there is only one visible process node that represents the functions of a
complete system in regards to how it interacts with external entities.
Some of the benefits of a Context Diagram are:
a. Shows the overview of the boundaries of a system
b. No technical knowledge is required to understand with the simple notation
c. Simple to draw, amend and elaborate as its limited notation

Online Shopping System


Delivery
Order

Customers

262 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


First Level DFD
First Level DFD is a data flow diagram that represents a system’s major processes, data flows
and data stores at a high level of details. In 1-level DFD, context diagram is decomposed into
multiple bubbles/processes. Level 1 DFD’s also identifies data stores that are used by the
major processes. It is further refinement of the context diagram.

Accounts
Finance
Verfication

Order
Customer Date
Processing Stores
Verify Issue Item

Process Order

Sales
Delivery
Order

Customers
Entity-Relationship Diagram
An entity-relationship diagram (ERD) is a data modeling technique that graphically illustrates
an information system’s entities and the relationships between those entities. An ERD is
a conceptual and representational model of data used to represent the entity framework
infrastructure.
There are five main components of an ERD. They are as follows:
a. An entity is any singular, identifiable and separate object. It refers to individuals, organizations,
systems, bits of data or even distinct system components that are considered significant in
and of themselves. Entities are represented by rectangles.
b. Actions, which are represented by diamond shapes, show how two entities share
information in the database.
c. An attribute is a property or descriptor of an entity, for example, Customer Name is an
attribute of the entity Customer. Each attribute will eventually be represented by one or
more entity attributes in the physical database structure. Attributes are represented by
ovals.
d. Connecting lines, solid lines that connect attributes to show the relationships of entities in
the diagram.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 263
e. Cardinality specifies how many instances of an entity relate to one instance of another
entity. Ordinality is also closely linked to cardinality. While cardinality specifies the
occurrences of a relationship, ordinality describes the relationship as either mandatory or
optional. In other words, cardinality specifies the maximum number of relationships and
ordinality specifies the absolute minimum number of relationships.

Id
m
ss

ds
Na
Cu
dre

e
sto

m
Goo
me
Ad

Na
rs
Id

Customers Purchases Customers


.
r

- no
e
nd

Ra

Qua hase
Ge

tact

ntity
e

c
Con

Pur
An ERD for ‘Customer’ and ‘Goods’ entity

a. What is DFD? What are the four basic components of DFD?


b. Draw first level DFD for order processing.
c. What are the five main components of ERD? Draw ERD diagram for customer and goods
entity.
Algorithm
An algorithm is the central concept of computing. It is a set of well-defined rules for solving
a problem in a finite number of times. An algorithm consists of stepwise list of instructions.
The programmer writes it on the paper using any simple language. It generally takes some
input, carries out a number of effective steps in a finite amount of time, and produces some
output.
Some of the main characteristics of algorithm are:
a. Each step of the algorithm should be simple.
b. The logic of each step should be clear.
c. It should be effective.
d. An algorithm must come to an end after a finite number of steps.
e. Every step of the algorithm must be accurate and precise. At the same time, it must have
the time limit for execution.
f. The output must be logically correct.

264 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Flowchart
Flowchart is a diagrammatic representation that shows the logical flow of a program. It uses
predefined symbols to represent the logic, data and processing steps of a program. It is
designed before the program is written to ensure that the instructions are accurate and logically
integrated. Flowcharts verify and integrate elements of a program prior to writing the program.
The system designer and programmer uses two types of flowcharts. They are:
a. System flowchart
b. Program flowchart

System Flowchart
System flowchart plays a vital role in system analysis. It is a diagram that shows the overview
of the data flow and sequence of operations in a system. It illustrates graphically the elements,
characteristics of a system, expresses its structure and relationship in terms of flowchart
symbols. These symbols describe the sequence of major processing operation, both manual
and computer, data flow and the files to be used in processing and the flow of processing
control. It allows the system analyst to conveniently experiment with alternative data flow
plan during the system design stage. It also provides graphic records to serve as guides during
implementation of a modified or newly designed business system.

Program Flowchart
Program flowchart is a detailed diagram showing how individual processing steps will be
performed within the computer to convert input data into the desired result. It is a process of
breaking down the design specifications into the specific input and output, text manipulation
and calculation, logic and comparison, storage and retrieval to satisfy the different users. It
helps the programmer in developing the program logic and to serve as documentation for
future reference for a completed program.

Flowchart Symbols
A flowchart consists of simple geometrical symbols for different functions. Some of the basic
flowchart symbols are given below:
Symbol Purpose
Terminal box The oval shaped terminal box is used to indicate the start and
the end of a flowchart.

Input/Output Box The parallelogram shaped input/output box, as the name


suggests, is used to show the input and output related steps in
a flowchart.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 265


Symbol Purpose
Processing Box The rectangular shaped processing box is used to show the
processing step (calculations, data manipulation, etc.) in a
flowchart.

Flow Lines The arrows that are used to connect the various geometrical
symbols in flowchart are called flow lines. The direction of the
arrow shows the order in which the computer will execute
the instructions to solve the problem.

Decision Box The diamond shaped decision box is used to show the steps
involving comparison and decision making steps. The outcome
of any decision can be either true or false. It has one entry and
two exit points which are for true and false. (Observe that one
arrow goes into the decision box, and two arrows come out
of it to indicate two alternate actions to be performed based
on the outcome of the decision making).

Connector The connectors indicate the continuation of the flow on


another page, where a corresponding symbol (containing the
same letter) is located.

Pseudocode
Pseudocode is a detailed readable description of what a computer program or algorithm must
do. It is expressed in a formally-styled natural language rather than in a programming language.
It is sometimes used as a detailed step in the process of developing a program. It allows
designers or lead programmers to express the design in great detail and provides programmers
a detailed template for the next step of writing code in a specific programming language. It uses
a combination of English words, mathematical notations and a set of capitalized keywords,
such as BEGIN, END, READ, PRINT, IF, ELSE, ELSEIF, ENDIF, WHILE, DO and ENDWHILE.

Solved Example
To calculate area of a triangle
BEGIN
PRINT “Enter base and height”
READ b, h
A = 1/2 * b * h
PRINT “The area of a triangle is: “, A
STOP

266 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Decision Table
A decision table is used to represent conditional logic by creating a list of tasks depicting business
level rules. Decision tables can be used when there is a consistent number of conditions that
must be evaluated and assigned a specific set of actions to be used when the conditions are
finally met.
The purpose of a decision table is to structure logic by generating rules derived from the data
entered in the table itself. A decision table lists causes (business rule condition) and effects
(business rule action and expected results), which are represented through the use of a matrix
where each column represents a unique combination.
In constructing a decision table, the following rules are observed.
a. A decision should be given a name to be written at the top left of the table.
b. The logic should be independent of the sequence in which the condition rules were
written, but the actions take place in the order in which the events occur.
c. Consistent and standardised language should be used.
d. Duplication of terms should be avoided to the maximum extent.
An example of decision tree to show the calculation of discount policy in a departmental store as
follows:
a. If the customer is ‘Regular’ and purchase amount>=1000, then 10% discount.
b. If the customer is ‘Regular’ and purchase amount<1000, then 5% discount.
c. If the customer is not ‘Regular’ and purchase amount>=1000, then 5% discount.
d. If the customer is not ‘Regular’ and purchase amount<1000, then no (0%) discount.

Process Name Rate

Is Customer Regular ? Y Y N N
Conditions
Is Purchase amount>=1000 Y N Y N

10% discount X - - -

Actions 5% discount - X X -

No discount - - - X
Decision Tree
A decision tree is a graphical representation of specific decision situations that are used when
complex branching occurs in a structured decision process. A decision tree is a predictive
model based on a branching series of Boolean tests that use specific facts to make more
generalized conclusions. The main components of a decision tree involve decision points
represented by nodes, actions and specific choices from a decision point. Each rule within a
decision tree is represented by tracing a series of paths from root to node to the next node
and so on until an action is reached.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 267
The main components of a decision tree involve decision points represented by nodes, actions
and specific choices from a decision point. Each rule within a decision tree is represented
by tracing a series of paths from root to node to the next node and so on until an action is
reached.

Yes Calculate 10% discount


Is Purchase
Amount
>=1000 No
Yes Calculate 5% discount
Is Customer
Regular
No Yes Calculate 5% discount
Is Purchase
Amount
>=1000 No
Calculate No discount

a. What is a flowchart? Explain the two types of flowchart.


b. Write short note on decision table.

CASE Tools
CASE stands for Computer Aided Software Engineering which is software that supports one or
more software engineering activities within a software development process, and is gradually
becoming popular for the development of software as they are improving in the capabilities
and functionality and are proving to be beneficial for the development of quality software.
CASE tools are the software engineering tools that permit collaborative software development
and maintenance. Almost all the phases of the software development life cycle are supported
by them such as analysis; design, etc., including umbrella activities such as project management,
configuration management, etc.
CASE tools may support the following development steps for developing data base application:
a. Creation of data flow and entity models
b. Establishing a relationship between requirements and models
c. Development of top-level design
d. Development of functional and process description
e. Development of test cases.

268 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Unified Modeling Language (UML)
Unified Modeling Language (UML) is a standardized modeling language enabling developers
to specify, visualize, construct and document artifacts of a software system. Thus, UML makes
these artifacts scalable, secure and robust in execution. UML is an important aspect involved
in object-oriented software development. It uses graphic notation to create visual models
of software systems. UML is a common language for business analysts, software architects
and developers used to describe, specify, design, and document existing or new business
processes, structure and behavior of artifacts of software systems. UML includes a collection
of elements such as:
a. Programming Language Statements
b. Actors: specify a role played by a user or any other system interacting with the subject.
c. Activities: These are tasks, which must take place in order to fulfill an operation contract.
d. They are represented in activity diagrams.
e. Business Process: includes a collection of tasks producing a specific service for customers
and is visualized with a flowchart as a sequence of activities.
f. Logical and Reusable Software Components.

Use case diagrams


Use case diagrams are usually referred to as behavior diagrams used to describe a set of actions
(use cases) that some system or systems (subject) should or can perform in collaboration
with one or more external users of the system (actors). Each use case should provide some
observable and valuable result to the actors or other stakeholders of the system.

Order Food

Service person
Customer
Prepare Bill

Pay Bill Bill Offices


A use case diagram contains four components.
a. The boundary, which defines the system of interest in relation to the world around it.
b. The actors, usually individuals involved with the system defined according to their roles.
c. The use cases, which are the specific roles played by the actors within and around the
system.
d. The relationships between and among the actors and the use cases.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 269
Documentation
Once the new system is fully developed, a considerable amount of documentation needs to
be produced a) for the end user, and b) for people who may need to modify or develop the
system further at some later stage. Documentation is the information that describes the product
to its users. It consists of the product technical manuals and online information (including online
versions of the technical manuals and help facility descriptions). It is carried out at every state
as a part of SDLC. The different tools used in documentation are flowchart, in line comments,
data flow diagram, entity relation diagram and class/object diagrams.
Documentation is needed because of the following reasons:
a. The presence of documentation helps keep track of all aspects of an application and it
improves on the quality of a software product.
b. Successful documentation makes information easily accessible, provide a limited number
of user entry points, help new users learn quickly, simplify the product and help cut
support costs.
c. Documentation is needed for IT infrastructure management and maintenance.
d. Documentation is needed for migration to a new software platform.

The two types of documentation are:


Internal Documentation
Internal documentation is written in a program as comments. It is the comments and remarks
made by the programmer in the form of line comments. It is very useful for program modification
and maintenance of the system. Internal documentation is created within the programming
department and shows the design and implementation of the project (flow charts, UML
diagrams, design documents, etc.). Some of the examples of internal documents are:
a. System Requirements Specification (SRS) is a document or set of documentation that
describes the features and behaviour of a system or software application. It includes a
variety of elements that attempts to define the intended functionality required by the
customer to satisfy their different users.
b. Software Design Report consists of logical as well as physical design report. It consists of
different tools and techniques to solve a problem.

External Documentation
External documentation is a documentation used for operation module of the system. It is
written in a place where people who need to use the software can read about how to use
the software. It is created by the user and Programmer/System Analyst. It contains the detail
description in terms of manuals, guide and help files.

a. What is UML? Draw use case diagram of any system.


b. What is documentation? Explain the two types of documentation.

270 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Software and Quality
Software quality is defined as a field of study and practice that describes the desirable attributes
of software products. Software quality is a software which is reasonably bug or defect free, is
delivered in time and within the specified budget, meets the requirements and/or expectations,
and is maintainable. In the software engineering context, software quality reflects both functional
quality as well as structural quality.
Key aspects that conclude software quality include,
Good design It is always important to have a good and aesthetic design to
please users
Reliability Be it any software it should be able to perform the
functionality impeccably without issues
Durability In this context, durability means the ability of the software to
work without any issue for a long period of time.
Consistency Software should be able to perform consistently over
platform and devices
Value for money Customer and companies who make app should feel that
the money spent on app has not fone to waste.
Portability A software device is said to be portable, if it can be freely
made to work in various operating system environments, in
multiple machines, with other software products, etc.
Usability A software product has better usability if various categories
of users can easily invoke the functions of the product.
Reusability A software product has excellent reusability if different
modules of the product can quickly be reused to develop
new products.
Correctness A software product is correct if various requirements
as specified in the SRS document have been correctly
implemented.
Maintainability Bugs associated with any software should be able to capture
and fix quickly and news tasks and enhancement must be
added without any trouble

a. What is software quality?


b. What are the key aspects of software quality? Explain.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 271


Concepts Review
Topic Key Concepts
System Analyst and Software System Analyst is an individual in charge of designing,
Engineers modifying, or analyzing various systems to ensure
compatibility and user effectiveness.
System analyst should have the knowledge of basics of
computers and business functions.
Software engineers are computer science professionals who
use knowledge of engineering principles and programming
languages to build software products, develop computer
games, and run network control systems.
System Development Life SDLC is a process followed for a software project, within a
Cycle software organization.
The waterfall model illustrates the software development
process in a linear sequential flow.
The spiral model can be defined as a model based on
SDLC (system development life cycle), which integrates the
characteristics of the waterfall model and the prototyping
model.
The prototyping model is a systems development method
(SDM) in which a prototype (an early approximation of a
final system or product) is built, tested, and then reworked
as necessary until an acceptable prototype is finally achieved
from which the complete system or product can now be
developed.
System Design Tools Data Flow Diagram (DFD) is a graphical representation of
the logical flow of data.
An entity-relationship diagram (ERD) is a data modeling
technique that graphically illustrates an information system’s
entities and the relationships between those entities.
An algorithm is a set of well-defined rules for solving a
problem in a finite number of times.
Flowchart is a diagrammatic representation that shows the
logical flow of a program.
UML is a standardized modeling language enabling
developers to specify, visualize, construct and document
artifacts of a software system.

272 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Section 1.1 (Very Short Questions)
a. What is a system analyst?
b. What is a system engineer?
c. What is system development life cycle?
d. What is a waterfall model?
e. What is system development life cycle?

Section 1.2 (Short Questions)


a. State the attributes of a good system analyst.
b. What are the roles of a good system analyst?
c. What are the responsibilities of system engineer?
d. List the attributes of system engineer.
e. What is a spiral model? What are the advantages and disadvantages of spiral model?

Section 1.3 (Long Questions)


a. What is system development life cycle? What are the most important models of SDLC?
Explain in brief.
b. What is feasibility study? Why feasibility study is important in system analysis phase?
c. What are the different tools used in system design? Describe each of them with an
example.
d. What is Data Flow Diagram? What are the defining DFD components? Explain them.
e. What is Entity-Relationship Data Model? Give an ER-diagram for a database showing
fatherhood, motherhood and spouse relationship among men and women.
f. What are the documentation techniques? Explain any two of them.
g. Explain the different phases of System Development Life Cycle (SDLC)?
h. Explain the two types of system testing.
Make a case study to computerize the library system of your college. You
can ask the librarian for details of their requirements for the new information
system.

Teaching Manual
While teaching this chapter, the key concepts that need to be emphasized upon include:
a. Definition of information system, components of information system, types of information
system, different types of SDLC model and system development phases.
b. Concept of system design tools, Entity-Relationship diagram and different types of CASE
tools.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 273
Recent
Chapter
Trends in
7 Technology

Concept
The modern world is more reliant on computers and the internet than ever before.
Whether it is for businesses, colleges, the government, or many other organizations,
access to the internet is vital to the operation of most organizations. Various emerging
technologies, the recent developments and convergences in various fields of technology,
hold possible future impacts. Emerging technologies cover various cutting-edge
developments in the emergence and convergence of technology, including transportation,
information technology, biotechnology, robotics and applied mechanics, and material
science. Their status and possible effects involve controversy over the degree of social
impact or the viability of the technologies. Though, these represent new and significant
developments within a field; converging technologies represent previously distinct fields
which are in some way moving towards stronger inter-connection and similar goals.

274 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Artificial Intelligence
Artificial Intelligence is a branch of computer science that aims to create intelligent machines.
It has become an essential part of the technology industry. The term was coined in 1956 by
John McCarthy at the Massachusetts Institute of Technology. Some of the activities computers
with artificial intelligence are designed for include:
a. Speech recognition
b. Learning
c. Planning
d. Problem solving

Artificial Intelligence A branch of computer science that aims to create intelligent


machines.

Components of Artificial Intelligence


Search in Artificial Intelligence
Search plays a major role in solving many Artificial Intelligence (AI) problems. Search is a
universal problem-solving mechanism in AI. In many problems, sequence of steps required
to solve is not known in advance but must be determined by systematic trial-and-error
exploration of alternatives. The problems that are addressed by AI search algorithms fall into
three general classes: single-agent path-finding problems, two-players games, and constraint-
satisfaction problems.

Pattern Recognition
Pattern recognition is the research area that studies the operation and design of systems that
recognize patterns in data. It encloses subdisciplines like discriminant analysis, feature extraction,
error estimation, cluster analysis (together sometimes called statistical pattern recognition),
grammatical inference and parsing (sometimes called syntactical pattern recognition). Important
application areas are image analysis, character recognition, speech analysis, man and machine
diagnostics, person identification and industrial inspection.

Logic Generate
Logic has played an important role in the development of Artificial Intelligence (AI). In turn,
thinking about applications in AI has led to the development of many new and interesting
logical systems. Logic is useful for:
a. Reasoning about combinatorial circuits
b. Reasoning about databases
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 275
c. Giving semantics to programming languages
d. Formally specifying software and hardware systems - model-checking and theorem-
proving can be used to show that the system meets the specification or that the system
has certain properties.

Machine Learning
To solve problems, computers require intelligence. Learning is central to intelligence. As
intelligence requires knowledge, it is necessary for the computers to acquire knowledge.
Machine learning serves this purpose. Machine learning refers to a system capable of acquiring
and integrating the knowledge automatically. The capability of the systems to learn from
experience, training, analytical observation, and other means, results in a system that can
continuously self-improve and thereby exhibit efficiency and effectiveness. A machine learning
system usually starts with some knowledge and a corresponding knowledge organization so
that it can interpret, analyze, and test the knowledge acquired.

Heuristic search
AI involves teaching computers to ‘think’ and ‘learn’ using algorithms. The idea of heuristic
methods in AI is based on cognitive science or the study of how humans think. Indeed,
humans use heuristics all the time to make decisions and solve problems. Likewise, heuristic
algorithms are often used in AI to get a computer to find an approximate solution instead
of an exact solution. Heuristic search is an AI search technique that employs heuristic for its
moves. Heuristic is a rule of thumb that probably leads to a solution. Heuristics play a major
role in search strategies because of exponential nature of the most problems. Heuristics help
to reduce the number of alternatives from an exponential number to a polynomial number.

Genetic Algorithm
Genetic algorithms are based on biological evolution. Genetic algorithms can be used to solve
a wide variety of problems. Given a problem a genetic algorithm generates a set of possible
solutions and evaluates each in order to decide which solutions are fit for reproduction. If a
particular solution is more fit then it will have more chances to generate new solutions. Finally
we can find a real solution. Genetic algorithms are so powerful that they can exhibit more
efficiency if programmed perfectly. Applications include learning robot behaviour, molecular
structure optimization, and electronic circuit design.

Uses of Artificial Intelligence


The use of machines which are programmed to think and act with some level of human
intelligence is known as artificial intelligence. This has already started to affect our daily life in
ways that we could not even have begun to contemplate only a hundred years ago. Our lives
have been changed beyond measure by robotics and AI and this technology is used in a wide
array of day to day services.

276 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Natural Language Programs or NLP
Communicating with computers via a natural language (e.g. English) instead of an artificial
language (e.g. Fortran) is the goal of natural language systems. A natural language program
interprets the parts of speech and the meaning of a sentence and then translates the sentence
into application commands in the computers own language that it can understand and process.
The three elements in a NLP system are:
Parser - It figures out how a sentence is put together with nouns, verbs and
other fragments and divides the sentence into different parts of speech
forming a parse tree.
Semantic Analyzer - It uses a built in dictionary to interpret the meanings of words in a
sentence. Parsing and dictionary lookup are concurrent procedures
and are carried on side by side.
Code generator - The code generator translates the user’s sentence to machine
language codes acceptable to the computer.

Expert Systems
An expert system is a software package that amasses the knowledge and decision making
roles of the specialists in a particular field so that package users can call on this knowledge or
expertise in making their own decisions. An expert system comprises of two components:
A knowledge base - This is the most important component of an expert system since it
holds the experts’ problem solving knowledge. It is a file of judgemental
rules applicable to a specified set of problem; the rules are obtained
from human experts. The rules are written in the following structure:
IF condition
THEN consequence with a specified probability of being correct.
An inference engine - It is the most active component of an expert system which comprises
of linguistic and reasoning mechanism that can probe the knowledge
base to reach conclusions and recommend solution to specific
problem.

Game playing
Game Playing is an important domain of artificial intelligence. Games do not require much
knowledge; the only knowledge we need to provide is the rules, legal moves and the conditions
of winning or losing the game. Both players try to win the game. So, both of them try to make
the best move possible at each turn. We need another search procedures that improve:
a. Generate procedure so that only good moves are generated.
b. Test procedure so that the best move can be explored first.
The most common search technique in game playing is Minimax search procedure. It is depth-
first depth-limited search procedure. It is used for games like chess and tic-tac-toe.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 277


Speech Recognition
Speech recognition is a computer technology that enables a device to recognize and understand
spoken words, by digitizing the sound and matching its pattern against the stored patterns.
Their major applications are in assisting technology for helping people in working around their
disabilities. Speech recognition applications include voice user interfaces such as voice dialling,
call routing, appliance control, search, simple data entry, preparation of structured documents,
speech-to-text processing, and aircraft.

Ethical Aspect of AI
Debates about the social impact of creating intelligent machines has occupied many organizations
and individuals over the past decades. Since many of the early science fiction speculations and
predictions from the late 19th century through to the 1960’s have already become reality there
is no reason to assume that robots and intelligent machines will not happen. We are already
living in that era’s future, experiencing a golden age of technology, with no end, or limit, in
sight.
The moral and ethical implications of artificial intelligences are obvious and there are three
sides to the argument. While one party argues that there are already too many of us living in
poverty without work and there is little or no reason to create mechanical laborers (that can
think independently). And that we certainly should not create machines that can argue with us
about such issues.
a. A robot may not injure a human being, or, through inaction, allow a human being to come
to harm.
b. A robot must obey the orders given it by human beings except where such orders would
conflict with the first law.
c. A robot must protect its own existence as long as such protection does not conflict with
the first or second law.

Robotics
Robotics is a branch of engineering that involves the conception,
design, manufacture, and operation of robots. This field overlaps
with electronics, computer science, artificial intelligence,
mechatronics, nanotechnology and bioengineering.
Science-fiction author Isaac Asimov is often given credit for being
the first person to use the term robotics in a short story composed
in the 1940s. In the story, Asimov suggested three principles to
guide the behaviour of robots and smart machines. Asimov’s
Three Laws of Robotics are:
a. Robots must never harm human beings.
b. Robots must follow instructions from humans without violating rule 1.
c. Robots must protect themselves without violating the other rules.

278 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Advantages of Robotics
a. Robots can work in environments harmful to human operators.
b. Business can achieve Return on Investment (ROI) quickly and in less time period due to
high productivity.
c.  Productivity is higher, since they do not need holidays.
d. In certain situations, robots can help in saving huge amount of labour costs.
e. Robots can perform routine and repetitive tasks easily. This will free up human resources
to perform more value addition jobs. This way both robots and humans can work together
for the development of an organization effectively and efficiently. The robots which work
in collaboration with humans are known as cobots.

Disadvantages of Robotics
a. If the robots are not well maintained, it will malfunction, this may be disastrous during
manufacturing or production processes.
b. Operational costs are higher due to power costs and grease costs.
c. Highly skilled man power is needed to implement and maintain robots. This is provided
by robotics company. This will increase the initial and operational costs of the companies
which use robots in their operations.
d. The robots are very costly and are available in different prices as per applications of use.

Cloud Computing
Individuals and businesses are increasingly turning to
providers of software and computing services that are
accessed entirely on the Internet. This delivery model
of software and services is called cloud computing. With
cloud computing, all you need is a computer with a web
browser in order to get your work done since all of the
software and the documents you need to access are
stored online.
Could computing got its name because the Internet has always been identified with a cloud
in technology documentation. Cloud computing places the processing and storage operations
of the Information Processing cycle at an online service provider’s server and/ or data center
rather than using the hardware and software on your won PC mobile device. In some cases
you can use up to 5 GB of cloud storage for free (with an option to play a fee for more storage
space).
The delivery of software applications using the Internet is referred to as software-as-a service
(SaaS).

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 279


Characteristics of Cloud Computing
The major characteristics of cloud computing are:
a. The user can access the data of the cloud or upload the data to the cloud from anywhere
just with the help of a device and an internet connection.
b. Cloud computing analyzes the storage usage and allows the user to buy extra cloud
storage if needed for a very small amount.
c. Cloud computing monitors, controls and report the usage of data.
d. Cloud computing is economical and most of the time some space is allotted for free.
e. Cloud computing helps the user to continuously monitor the server uptime, capabilities,
and allotted network storage.

Advantages of Cloud Computing


The advantages of cloud computing are:
a. Cloud computing provides service to the companies at the lowest rates.
b. The cloud computing platform is very reliable as the data stored is secured.
c. The data stored in one location can be accessed from different remote places in cloud
computing.
d. Cloud computing helps you to access the latest and applications any time without spending
your time and money on installations.
e. Employees who are working on the premises or at the remote locations can easily access
all the could services.
f. Cloud computing platform helps employees who are located in different geographies to
collaborate in a highly convenient and secure manner.

Disadvantages of Cloud Computing


The disadvantages of cloud computing are:
a. Cloud computing needs Internet connectivity, otherwise you won’t be able to access the
cloud.
b. Storing data in the cloud may pose serious challenges of information theft since in the
cloud every data of a company is online.
c. Downtime is considered as one of the biggest potential downsides of using cloud
computing.
d. Cloud computing companies sometimes fail to provide proper support to the customers.
e. Cloud computing is an economical option, but if you consider the installation of the
software, it can be costly. Installation can lead to some costly feature which can be non-
beneficial in the future.

280 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Big Data
Big data is a combination of structured, semistructured and
unstructured data collected by organizations that can be
mined for information and used in machine learning projects,
predictive modeling and other advanced analytics applications.
Big data is often characterized by the 3Vs: the large volume
of data in many environments, the wide variety of data types
stored in big data systems and the velocity at which the data is
generated, collected and processed.
Some of the examples of Big Data are:
a. The New York Stock Exchange generates about one terabyte of new trade data per day.
b. A single Jet engine can generate 10+terabytes of data in 30 minutes of flight time. With
many thousand flights per day, generation of data reaches up to many Petabytes.

Basic Principle of Big Data


Some of the basic principles of big data are:
a. It refers to a massive amount of data that keeps on growing exponentially with time.
b. It is so voluminous that it cannot be processed or analyzed using conventional data
processing techniques.
c. It includes data mining, data storage, data analysis, data sharing, and data visualization.
d. The term is an all-comprehensive one including data, data frameworks, along with the
tools and techniques used to process and analyze the data.

Benefits of Big Data


Some of the benefits of Big Data are:
a. Big data analysis derives innovative solutions. Big data analysis helps in understanding and
targeting customers. It helps in optimizing business processes.
b. It helps in improving science and research.
c. It improves health care and public health with availability of record of patients.
d. It helps in financial trading, sports, polling, security/law enforcement, etc.
e. Any one can access vast information via surveys and deliver an aswer of any query.
f. Real-time forecasting and monitoring of business as well as the market.
g. Identify crucial points hidden within large datasets to influence business decisions.
h. Promptly mitigate risks by optimizing complex decisions for unforeseen events and
potential threats.
i. Identify issues in systems and business processes in real-time.
j. Unlock the true potential of data-driven marketing.
Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 281
e-Business
e-Business is a short form for “electronic business”. e-Business (electronic business) is the
conduct of business processes on the Internet. These electronic business processes include
buying and selling products, supplies and services, servicing customers, processing payments,
managing production control, collaborating with business partners, sharing information, running
automated employee services and recruiting.

Features of e-Business
Some of the features of e-Business are as follows :
a. It is easy to set up.
b. There are no geographical boundaries.
c. Much cheaper than traditional business
d. There are flexible business hours
e. Marketing strategies cost less

Advantages of e-Business
The internet and the emergence of e-business has provided entrepreneurs with many new
advantages and opportunities. The internet has created a business environment in which time
and distance are less important, people have access to more information to help them make
decisions and consumers have better access to a broader range of products and services.
a. A significant benefit for entrepreneurs is that the initial investment for starting up an
e-business is generally lower than the costs associated with starting an equivalent business
using a traditional model.
b. e-Business allows for conversations to happen quickly. Faster decision-making saves time,
and time is money in business. E-business allows people to communicate in several ways
that facilitate understanding.
c. The increases in technology and falling prices also provide online businesses with a steady
stream of new customers as more people move online to shop for products and services.
Cost and access is becoming less of a barrier for consumers and people are becoming
increasingly comfortable with making purchasers online.
d. e-Business makes it easier, faster and cheaper for businesses to communicate with their
suppliers and their customers. Using email and online ordering systems, communication
and transactions can occur almost instantly between organisations situated anywhere in
the world.
e. The internet is accessible twenty-four hours a day, seven days a week. This means that
buyers and sellers can conduct transactions at any time, as opposed to the regular trading
hours of traditional business models. The internet can also make it easier and more cost
effective for business managers to track and analyse the buying patterns of their customers,
and in turn tailor the business to better suit their needs and expectations.

282 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


e-Commerce
e-Commerce or Electronic Commerce means buying and selling of goods, products, or
services over the internet. e-Commerce is also known as electronic commerce or Internet
commerce. These services provided online over the Internet network. Transaction of money,
funds, and data are also considered as e-Commerce. Online stores like Amazon, Flipkart,
Shopify, Myntra, Ebay, Quikr, Olx are examples of E-commerce websites.

Types of e-Commerce system


There are four types of e-Commerce systems. They are B2B, B2C, C2C and C2B. All
these four types of e-commerce that are used today are classified based on the nature of the
transaction.

B2B (Business-to-Business)
B2B e-commerce can be simply defined as the commerce between companies. In Business-
to-Business type of electronic commerce system, companies do business with each other.
For say, a manufacturer selling a product to a wholesaler, a wholesaler selling a product to the
retailer. Here manufacturer, wholesaler and retailer all are doing their separate businesses.

B2C (Business-to-Consumer)
B2C model works as its name suggest. In this model, the company sells their products, goods
or services directly to the consumer online. Here the customer can view products on the
website that they want to buy and can order it. After receiving the order details, the company
will process the order and then send the products directly to the customer. For example,
Amazonand Flipkart are this type of e-commerce business model which we are using in our
daily life.

C2C (Consumer-to-Consumer)
Here a consumer sells products, goods or services to other consumers using the Internet or
the web technologies. The C2C business model helps us to sell our assets or properties like
a car, house, bike, electronics etc via online to other consumers. OLX, Quickr etc are C2C
business model.

C2B (Consumer-to-Business)
A consumer to the business model is a type of commerce where a consumer or end user
provides a product or service to an organization. It is the reverse model of the B2C or
business to consumer model, where businesses produce products and services for consumer
consumption.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 283


Advantages of e-Commerce
a. Electronic commerce provides the sellers with a global reach. They remove the barrier
of place (geography). Now sellers and buyers can meet in the virtual world, without the
hindrance of location.
b. Electronic commerce will substantially lower the transaction cost. It eliminates many fixed
costs of maintaining brick and mortar shops. This allows the companies to enjoy a much
higher margin of profit.
c. It provides quick delivery of goods with very little effort on part of the customer. Customer
complaints are also addressed quickly. It also saves time, energy and effort for both the
consumers and the company.
d. One other great advantage is the convenience it offers. A customer can shop 24×7. The
website is functional at all times, it does not have working hours like a shop.
e. Electronic commerce also allows the customer and the business to be in touch directly,
without any intermediaries. This allows for quick communication and transactions. It also
gives a valuable personal touch.

Disadvantages of e-Commerce
a. The start-up costs of the e-commerce portal are very high. The setup of the hardware
and the software, the training cost of employees, the constant maintenance and upkeep
are all quite expensive.
b. The e-commerce industry has a high risk of failure.
c. At times, e-Commerce can feel impersonal. So it lacks the warmth of an interpersonal
relationship which is important for many brands and products. This lack of a personal
touch can be a disadvantage for many types of services and products like interior designing
or the jewelry business.
d. Security is another area of concern. Credit card theft and identity theft remain big concerns
with the customers.

Differences between e-Business and e-Commerce


e-Business e-Commerce
Running business using the internet is Trading of merchandise, over the internet is
known as E-business. known as E-commerce.
It includes monetary as well as provides It includes transactions which are related to
services to the customers, communication money only.
with employees, client, discussion about
company, issues, etc.
To run the business over the internet It just requires a website that can represent the
successfully, it requires a website, Customer business.
relationship management and enterprise
resource planning.
284 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center
e-Government
“e-Government” refers to the use of information and communication technologies by
government agencies to transform relations with citizens, business and other arms of the
government. It involves information technology enabled initiatives that are used for improving:
a. The interaction between government and citizens or government and businesses-e-
services,
b. The internal government operations,
c. E-administration and
d. External interactions-e-society.
It is a kind of ‘window of opportunity’ facilitating a much faster convenient, transparent and
dynamic interaction between the government and the people. It integrates people, processes,
information and technology in the service of achieving goverance objectives. E-government
can serve a variety of different ends: better delivery of government services to citizens,
improved interactions with business and industry and citizen empowerment through access
to information.

Advantages of e-Government
E-Governance has the following advantages:
a. E-Governance greatly simplifies the process of information accumulation for citizens and
businesses.
b. E-Governance empowers people to gather information regarding any department of
government and get involved in the process of decision making.
c. E-Governance strengthens the very fabric of democracy by ensuring greater citizen
participation at all levels of governance
d. E-Governance leads to automation of services, ensuring that information regarding every
work of public welfare is easily available to all citizens, eliminating corruption.

Goals of e-Government
The Working Group on E-Government in the Developing World has identified broad categories
of goals commonly pursued for E-government. E-government is a means to accomplish these
broader social goals, goals that move beyond mere efficiency of government processes to that
of overall reform and development. The goals of E-Government are explained below:

Creating a better business environment


The rapid development of modern information and communications technologies (ICTs) are
having far-reaching effects on all aspects of modern life, including government. The use of
ICT in government and the establishment of an e-government infrastructure help create a
business-friendly environment by streamlining the interaction and improving the interface
between government and business.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 285


By cutting out redundancies in procedures and emphasizing immediate and efficient delivery of
services, e-government creates the conditions that attract investors/ investment.

Improving the productivity


E-government increases government staff productivity, reduces overhead from fewer offices
and less paper management and improves capacity for planning management by government.

Strengthening good governance and broadening public participation


Promoting transparency and accountability in government through the proliferation of ICT in
management and operations also opens opportunities for citizens to be more actively involved
in the policy- and decision-making processes of government. E-government can advance the
fight against corruption. E-government also facilitates the swift delivery of complete information.
The broad dissemination of information helps empower citizens and facilitates informed
decision-making.

Efficiency gains
E-Government provides benefits to the citizen and to public administration at a number of levels.
At its most basic, E-government can harness modern technology to enable departments achieve
efficiency improvements in the processing of large volumes of data and other administrative
operations. Significant savings can be obtained in data collection and transmission as well as in
the provision of information to the whole community.

Improving the quality of life for disadvantaged communities


ICT makes it possible for government to reach marginalized groups/communities and improve
their quality of life. This means empowering them through their participation in the political
process, as well as delivering much-needed public goods and services. Ultimately, the goal of
e-government is to enhance the interaction between three main actors in society-government,
citizens and business-in order to stimulate political, social and economic progress in the country.

Types of e-Government services


The four types of e-government services are Government-to-Citizen (G2C), Government-to-
Business (G2B), Government-to-Employee (G2E), and Government-to-Government (G2G).

Government-to-Citizen (G2C)
Government-to-Citizen (G2C) is the online non-commercial interaction between local and
central Government and private individuals. It includes information dissemination to the public,
basic citizen services such as license renewals, ordering of birth/death/marriage certificates and
filing of income taxes, as well as citizen assistance for such basic services as education, health
care, hospital information and libraries. It makes public services and information accessible to
all. For example Government sectors become visibly open to the public domain via a Web
Portal. One such web portal is Government Gateway.

286 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Government-to-Business (G2B)
Government-to-Business (G2B) is the online non-commercial interaction between local and
central government and the commercial business sector. It includes dissemination of policies,
memos, rules and regulations. Business services offered include obtaining current business
information, downloading application forms, renewing licenses, registering businesses,
obtaining permits, payment of taxes and an online government-supplier exchange for the
purchase of goods and services by government.

Government-to-Employee (G2E)
Government-to-Employee (G2E) is the online non-commercial interaction between
government organization and the government employees. It includes provision of human
resources training and development that improve the bureaucracy’s day-to-day functions and
dealings with citizens.

Government-to-Government (G2G)
Government-to-Government (G2G) is the online non-commercial interaction between
Government organisations, departments, and the authorities and other Government
organisations, departments, and authorities. G2G services take place at two levels: at the local
or domestic level and at the international level. G2G services are transactions between the
central/national and local governments, and between department-level and attached agencies
and bureaus. At the same time, G2G services are transactions between governments, and can
be used as an instrument of international relations and diplomacy.

e-Medicine
e-Medicine refers to the use of communications and information technologies for the delivery
of clinical care. It enhances or speeds up health care services by accessing linking clinics or
physicians’ offices to central hospitals. This process is helpful to treat patient situated at remote
region. This process can include transmitting all the diagnostic documents including X-Ray,
prescription, images of examination and other documents to another site. e-Medicine is a rapidly
developing application of clinical medicine where medical information is transferred through
interactive audiovisual media for the purpose of consulting and sometimes remote medical
procedures or examinations. e-Medicine may use satellite technology, videoconferencing
equipment or real time medical procedures to conduct medical operation by sitting in distinct
geographical regions.

Advantages of e-Medicine for the Patient


a. Improved diagnosis and treatment
b. Significantly fewer errors found within personal health records
c. Faster care and decision making responses from assigned medical professionals

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 287


Advantages of e-Medicine for the Medical Practice
From the viewpoint of doctors and health practitioners, there are numerous other advantages
of implementing electronic medical records:
a. The ability to quickly transfer patient data from one department to the next is a huge asset
b. The space saving benefit of a digital records environment
c. The ability to ultimately increase the number of patients served per day for enhanced
patient workflow and increased productivity
d. Improved results management and patient care with a reduction in errors within your
medical practice
e. Reduced operational costs such as transcription services and overtime labour expenses
f. Customizable and scalable electronic medical records that can grow with your practice
g. Advanced e-prescribing and clinical documentation capabilities
h. An improved bottom line of the health-care practice, enhanced through the ability to
more accurately and efficiently process patient billing.

Virutal Reality
Virtual Reality is a technology that allows people to enter and interact with three dimensional
computer graphics world. The user wears a headset that contains two screens-one in front of
each eye. The brain combines the screen images to create a three-dimensional (3D) scene.
The headset plays stereo sounds-one into each ear-which the brain combines for a surround-
sound effect. In addition, many systems make use of gloves, shoes and even whole suits
with sensors to detect the user’s movement. The computer analyzes these movements and
changes the images and sounds to fit. So the user seems to move through a virtual landscape,
and can grasp virtual objects.
Virtual Reality can be applied in many areas:
a. It can be used in medical studies to enable students to know the human body structure.
b. It can be used in scientific research laboratories so that scientist can easily research on a
specific topic.
c. It can be used in entertainment like in games and movies to make the gaming experience
more real and to allow individual to experience adventures under extreme conditions.
d. It can be used in driving schools as it give a real look of roads and traffic.
e. It can be used in military training for the soldiers to get familiar with different areas in the
battlefield.
Some of the advantages of Virtual Reality are:
a. Virtual Reality creates a realistic world.
b. Virtual Reality enables user to explore places.
c. The user can experiment with an artificial environment through Virtual Reality.
d. Virtual Reality make the education more easily and comfort.

288 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Mobile Computing
Mobile computing is a technology that allows transmission
of data, voice and video any time and any where over the
wireless network infrastructure.
The main concept involves:
Mobile communication Mobile communication is the use of technology that allows
us to communicate with others in different locations without
the use of any physical connection (wires or cables). Mobile
communication makes our life easier, and it saves time and
effort.
Mobile hardware Mobile hardware are mobile devices that receive or access the
service of mobility.
Mobile software Mobile software is a program that runs on the mobile hardware.
It deals with the characteristics and requirements of mobile
applications.
Some of the important features of mobile computing are:
a. Portability The ability to move a device within a learning environment or to
different environments with ease.
b. Social interactive The ability to share data and collaboration between users.
c. Context sensitivity The ability to gather and respond to real or simulated data unique to
a current location, environment, or time.
d. Connectivity The ability to be digitally connected for the purpose of communication
of data in any environment.
e. Individual The ability to use the technology to provide movable platform on
difficult activities and lesson customization for individual learners.

Advantages of Mobile Communication


There are following advantages of mobile communication:
Flexibility Mobile communication enables the people to communicate with
each other regardless of location. There is no need to be in an office
or some telephone booth in order to pass and receive messages.
Cost effectiveness In mobile communication, there is no need of any physical
infrastructure (wires or cables) or maintenance practice. Hence, the
cost is reduced.
Enhanced Productivity Users can work efficiently and effectively from whichever location
they find comfortable. This in turn enhances their productivity level.
Ease of Research Mobile communication has made it easier for field officers and
researchers to collect and feed data from wherever they are without
making unnecessary trips to and from the office to the field.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 289


Constant connectivity Constant connectivity ensures that people can respond to
emergencies relatively quickly. For example, a wireless device like
mobile can ensure you a constant connectivity though you move
from place to place or while you travel, whereas a wired landline
can’t.

Internet of Things (IoT)


The “Internet of Things” (IoT) is becoming an increasingly
growing topic of conversation both in the workplace and
outside of it. The Internet of Things (IoT) describes the
network of physical objects-“things”-that are embedded
with sensors, software, and other technologies for the
purpose of connecting and exchanging data with other
devices and systems over the internet. These devices range from ordinary household objects
to sophisticated industrial tools. A thing, in the Internet of Things, can be a person with a heart
monitor implant, a farm animal with a biochip transponder, an automobile that has built-in
sensors to alert the driver when tire pressure is low-or any other natural or man-made object
that can be assigned an IP address and provided with the ability to transfer data over a network.
The most important features of IoT are:
a. IoT integrating the various models to improve the user experience as well.
b. IoT makes things smart and enhances life through the use of data.
c. The sensor devices used in IoT technologies detect and measure any change in the
environment and report on their status. IoT technology brings passive networks to active
networks. Without sensors, there could not hold an effective or true IoT environment.
d. IoT makes the connected technology, product, or services to active engagement between
each other.
e. The primary activity of Internet of Things is to collect data from its environment, this is
achieved with the dynamic changes that take place around the devices.
Some of the common benefits of IoT enable businesses are to:
a. monitor their overall business processes;
b. improve the customer experience (CX);
c. save time and money;
d. enhance employee productivity;
e. integrate and adapt business models;

a. What is e-Commerce? Explain its role to enhance the digital economy.


b. What are the key challenges of implementing e-Governance in developing countries?
c. What is Virtual Reality? List the advantages of Virtual Reality.

290 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Concepts Review
Topic Key Concepts
Information System An information system is a set of interrelated components
that collect (or retrieve), process, store, and distribute
information to support decision making and control in an
organization.
Procedures are rules or guidelines for people to follow
when using software, hardware and data.
Hardware is the physical equipment used for input,
processing and output work in an information system.
Software is a set of instructions that cause a computer to
perform one or more tasks.
System Development Life SDLC is a process followed for a software project, within a
Cycle software organization.
The waterfall model illustrates the software development
process in a linear sequential flow.
The spiral model can be defined as a model based on
SDLC (system development life cycle), which integrates the
characteristics of the waterfall model and the prototyping
model.
The prototyping model is a systems development method
(SDM) in which a prototype (an early approximation of a
final system or product) is built, tested, and then reworked
as necessary until an acceptable prototype is finally achieved
from which the complete system or product can now be
developed.
System Design Tools Data Flow Diagram (DFD) is a graphical representation of
the logical flow of data.
An entity-relationship diagram (ERD) is a data modeling
technique that graphically illustrates an information system’s
entities and the relationships between those entities.
An algorithm is a set of well-defined rules for solving a
problem in a finite number of times.
Flowchart is a diagrammatic representation that shows the
logical flow of a program.
UML is a standardized modeling language enabling
developers to specify, visualize, construct and document
artifacts of a software system.

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 291


Section 1.1 Very Short Questions
a. What is Artificial Intelligence? Who coined this term?
b. What is Robotics?
c. What is big data?
d. What is e-Business?
e. What is virtual reality?

Section 1.2 Short Questions


a. What is cloud computing? State the characteristics of cloud computing.
b. List the advantages and disadvantages of cloud computing.
c. What is big data? What are the benefits of big data?
d. What is e-Business? List the advantages of e-Business.
e. What are the features of e-Business?
f. What are the advantages and disadvantages of robotics?

Section 1.3 Long Questions


a. Explain the components of Artificial Intelligence.
b. What is expert system? Explain the two components of expert system.
c. Explain the ethical aspect of AI.
d. What is e-Commerce? Explain the types of e-Commerce system.
e. List the advantages and disadvantages of e-Commerce.
f. Differentiate between e-Business and e-Commerce.
g. What is e-Government? Explain the goals of e-Government.
h. Explain the four types of e-Government services.
i. What is mobile computing? List the important features of mobile computing.
Search on the Internet and find information on the recent computing
technology.

Teaching Manual
While teaching this chapter, the key concepts that need to be emphasized upon include:
a. Definition of Artificial Intelligence, components of Artificial Intelligence, uses of Artificial
Intelligence, definition of Robotics, advantages of Robotics, disadvantages of Robotics
b. Explanation of Cloud Computing, Big Data, e-Commerce, Virtual Reality and IoT.

292 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


Project Work
Project Synopsis
Synopsis format may vary as per the project and university. Each university has a different format
for synopsis. It is nothing but a document containing project specifications and requirements in
a formatted manner. As per the syllabus of NEB, each student must submit project based on
C-language.

Project Development using C programming


Following points will be useful to manage your project
1) Be very clear about the idea of your project, modifying your project at a later time can be
a trouble for you.
2) Always create a back up of your source code, you start your project by writing some
portion and it works fine but at a later point of time you need to modify it so you modified
the original one and you find it’s not working and now you want your original one back
but it is not possible if you have saved your file or you can undo if it works. So you should
keep a backup of every source file.
3) To easily manage keep your project source code in different files.
4) Do not use too many global variables as global variables are shared by many functions
so they get modified causing a lot of trouble when you’re not getting the result what you
desire although your logic is correct.
5) Use const keyword as much as you can, it will help you to protect your variables from
being modified when undesired.
6) Ensure that every function is performing the task for what it is made. You can test your
function separately by using it in a program which is not a part of your project.
7) Every function should have a description about what is to be done by a function and
description of arguments being passed to it. You can use comments for this purpose.
8) Write detailed comments in your source code. It will help quickly understand your source
code at a later time.
9) Initialize every variable at declaration time.
10) Use tab and blank spaces to make your code easily readable which will help in easy
understanding of code.

Project Report
A project report must contain the following topics:
1) Cover page 2) Acknowledgement 3) Table of Contents

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 293


Telecom Billing Management System in C with source code

This project can be a good reference for those student who are doing project in c. Architecture
of this project is very simple and easy to understand the code. Just file handling is used to store
the data and corresponding function are made to manipulate the data.
The tasks provide in this program are:
1. A : for adding new records.
2. L : for list of records.
3. M : for modifying records.
4. P : for payment.
5. S : for searching records.
6. D : for deleting records.
User are provide the above tasks. They can add records,modify and view records. Searching
and deleting facilities is also provided.
Here is the complete source code , copy and compile it in code
Solution:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<windows.h>
#include<stdlib.h>
struct subscriber
{
char phonenumber[20];
char name[50];
float amount;
}s;
void addrecords();
void listrecords();
void modifyrecords();
void deleterecords();
void searchrecords();
void payment();
char get;
int main()
{ int password;
int phonenumber;
char choice;
system(“cls”);

294 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


printf(“\**********************************************************************”);
printf(“\n\t\t---WELCOME TO THE TELECOM BILLING MANAGEMENT SYSTEM---”);
printf(“\n\t\t****************************************************************”);
Sleep(2000);
getch();
system(“cls”);
while (1)
{
system(“cls”);
printf(“\n enter\n A : for adding new records.\n L : for list of records”);
printf(“\n M : for modifying records.\n P : for payment”);
printf(“\n S : for searching records.”);
printf(“\n D : for deleting records.\n E : for exit\n”);
choice=getche();
choice=toupper(choice);
switch(choice)
{
case ‘P’:
payment();break;
case ‘A’:
addrecords();break;
case ‘L’:
listrecords();break;
case ‘M’:
modifyrecords();break;
case ‘S’:
searchrecords();break;
case ‘D’:
deleterecords();break;
case ‘E’:
system(“cls”);
printf(“\n\n\t\t\t\tTHANK YOU”);
printf(“\n\n\n\n\n:\n\tFOR USING OUR SERVICE”);
Sleep(2000);
exit(0);
break;
default:
system(“cls”);
printf(“Incorrect Input”);
printf(“\nAny key to continue”);

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 295


getch();
}
}
}
void addrecords()
{
FILE *f;
char test;
f=fopen(“c:/file.ojs”,”ab+”);
if(f==0)
{ f=fopen(“c:/file.ojs”,”wb+”);
system(“cls”);
printf(“please wait while we configure your computer”);
printf(“/npress any key to continue”);
getch();
}
while(1)
{
system(“cls”);
printf(“\n Enter phone number:”);
scanf(“%s”,&s.phonenumber);
printf(“\n Enter name:”);
fflush(stdin);
scanf(“%[^\n]”,&s.name);
printf(“\n Enter amount:”);
scanf(“%f”,&s.amount);
fwrite(&s,sizeof(s),1,f);
fflush(stdin);
system(“cls”);
printf(“1 record successfully added”);
printf(“\n Press esc key to exit, any other key to add other record:”);
test=getche();
if(test==27)
break;
}
fclose(f);
}
void listrecords()
{

296 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


FILE *f;
int i;
if((f=fopen(“c:/file.ojs”,”rb”))==NULL)
exit(0);
system(“cls”);
printf(“Phone Number\t\tUser Name\t\t\tAmount\n”);
for(i=0;i<79;i++)
printf(“-”);
while(fread(&s,sizeof(s),1,f)==1)
{
printf(“\n%-10s\t\t%-20s\t\tRs. %.2f /-”,s.phonenumber,s.name,s.amount);
}
printf(“\n”);
for(i=0;i<79;i++)
printf(“-”);
fclose(f);
getch();
}
void deleterecords()
{
FILE *f,*t;
int i=1;
char phonenumber[20];
if((t=fopen(“c:/temp.ojs”,”w+”))==NULL)
exit(0);
if((f=fopen(“c:/file.ojs”,”rb”))==NULL)
exit(0);
system(“cls”);
printf(“Enter the phone number to be deleted from the Database”);
fflush(stdin);
scanf(“%[^\n]”,phonenumber);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.phonenumber,phonenumber)==0)
{ i=0;
continue;
}
else
fwrite(&s,sizeof(s),1,t);
}

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 297


if(i==1)
{ system(“cls”);
printf(“Phone number \”%s\” not found”,phonenumber);
remove(“c:/file.ojs”);
rename(“c:/temp.ojs”,”c:/file.ojs”);
getch();
fclose(f);
fclose(t);
main();
}
remove(“c:/file.ojs”);
rename(“c:/temp.ojs”,”c:/file.ojs”);
system(“cls”);
printf(“The Number %s Successfully Deleted!!!!”,phonenumber);
fclose(f);
fclose(t);
getch();
}
void searchrecords()
{
FILE *f;
char phonenumber[20];
int flag=1;
f=fopen(“c:/file.ojs”,”rb+”);
if(f==0)
exit(0);
fflush(stdin);
system(“cls”);
printf(“Enter Phone Number to search in our database”);
scanf(“%s”, phonenumber);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.phonenumber,phonenumber)==0)
{ system(“cls”);
printf(“ Record Found “);
printf(“\n\nPhonenumber: %s\nName: %s\nAmount: Rs.%0.2f\n”,s.phonenumber,s.
name,s.amount);
flag=0;
break;
}

298 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


else if(flag==1)
{ system(“cls”);
printf(“Requested Phone Number Not found in our database”);
}
}
getch();
fclose(f);
{
}
void modifyrecords()
FILE *f;
char phonenumber[20];
long int size=sizeof(s);
if((f=fopen(“c:/file.ojs”,”rb+”))==NULL)
exit(0);
system(“cls”);
printf(“Enter phone number of the subscriber to modify:”);
scanf(“%[^\n]”,phonenumber);
fflush(stdin);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.phonenumber,phonenumber)==0)
{
system(“cls”);
printf(“\n Enter phone number:”);
scanf(“%s”,&s.phonenumber);
printf(“\n Enter name: “);
fflush(stdin);
scanf(“%[^\n]”,&s.name);
printf(“\n Enter amount: “);
scanf(“%f”,&s.amount);
fseek(f,-size,SEEK_CUR);
fwrite(&s,sizeof(s),1,f);
break;
}
}
fclose(f);
}
void payment()

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 299


{
FILE *f;
char phonenumber[20];
long int size=sizeof(s);
float amt;
int i;
if((f=fopen(“c:/file.ojs”,”rb+”))==NULL)
exit(0);
system(“cls”);
printf(“Enter phone number of the subscriber for payment”);
scanf(“%[^\n]”,phonenumber);
fflush(stdin);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.phonenumber,phonenumber)==0)
{
system(“cls”);
printf(“\n Phone No.: %s”,s.phonenumber);
printf(“\n Name: %s”,s.name);
printf(“\n Current amount: %f”,s.amount);
printf(“\n”);
for(i=0;i<79;i++)
printf(“-”);
printf(“\n\nEnter amount of payment :”);
fflush(stdin);
scanf(“ %f”,&amt);
s.amount=s.amount-amt;
fseek(f,-size,SEEK_CUR);
getch();
fwrite(&s,sizeof(s),1,f);
break;
}
}
system(“cls”);
printf(“THANK YOU %s FOR YOUR TIMELY PAYMENTS”,s.name);
fclose(f);
}

300 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


2065 (2008)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any two of the following questions. [2 x 20 = 40]
1. a. Write an algorithm and a flowchart for a program that checks whether the number entered
by user is exactly divisible by 5 but not by 11.
b. Write a program that reads three numbers and display the largest among them.
c. What is an operator? Explain different types of operators used in programming.
d. What is a program to read a four digit number and display it in reverse order?
2. a. Write a program to add two matrices.
b. Write differences between structure and union with syntax.
3. a. Write a program to enter name, roll, number and marks of 10 students and store
them in the file.
b. Write a program to enter ‘n’ number into one dimensional array and sort and display them
in ascending order.

Group – B
(Short Answer Questions)
Attempt any five questions. [5 x 7 = 35]
4. What is the local area network? Explain the different types of topologies with diagrams
5. Who is a system analyst? Explain the major role of system analyst.
6. What is normalization? Explain the normalization process with example.
7. Differentiate between Internet and Internet with suitable example.
8. Define the term polymorphism and inheritance with examples.
9. Differentiate between while and do while loop.
10. What is data security? How it can be implemented?
11. What is documentation? Explain the importance of documentation in program designing.
12. Write short notes on:
a. Cyber Law b. Feasibility study

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 301


2066 (2009)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any two of the following questions. [2 x 20 = 40]
1. a. Write an algorithm for a program that input cost of price (CP) and selling price (SP) ad
determine whether there is gain or loss. Convert this algorithm into program code.
b. Write a program to display the name of day on the basis of entered number 1 to 7. For
example, 1 for Sunday.
c. Write a program to input an integer number and checks whether it is prime or not.
d. Explain data types used in C-programming with examples.
2. a. Write a program to store name and mark of 20 students, Sort the data according with mark
in descending order and display them.
b. Write a program to find the sum of ‘n’ integer number using function.
3. a. Write a program to store std. on, name, and mark of ‘n’ students in a data file. Display the
records in appropriate format reading from the file.
b. Differentiate array and structure with examples.

Group – B
(Short Answer Questions)
Attempt any five questions. [5 x 7 = 35]
4. Define Network Architecture. Explain client-server and peer-networking.
5. Explain about the system designing methodologies.
6. Explain about OSI/ISO model of networking.
7. Define database and DBMS. Explain the advantage of Database system over flat-file system.
8. Explain about the importance of computer security in this knowledge based society.
9. What are the different program logic tools? Explain about the decision table and decision tree
with examples.
10. What are the advantages of distributed database system over centralized database system?
11. Explain about the different testing techniques during the system development.
12. Write short notes:
a. E-commerce b. Inheritance

302 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


2067 (2010)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any two of the following questions. [2 x 20 = 40]
1. a. What is looping? Write a program to print first 10 terms of the following series using for loop:
5, 9, 13, ............................
b. Write a recursive function to calculate the factorial of an integer number.
c. Write a program to display all prime numbers from 1 to 100.
d. What do you mean by string manipulation? Explain about ‘strcpy’ and ‘strcat’.
2. a. How do you declare an array? Write a program to arrange the elements of an array in ascending
order.
b. What are the different between library function and user defined function? Write a program
using user defined function to calculate y raise to power x.
3. a. Differentiate between array and structure with suitable example.
b. Write a program to delete and rename the data file using ‘remove’ and ‘rename’ command.


Group – B
(Short Answer Questions)
Attempt any five questions. [5 x 7 = 35]
4. What is system analyst? Explain the major roles of system analyst.
5. What is feasibility study? Explain the different levels of feasibility study.
6. What is network topology? Explain the different types of network topology with diagrams.

7. Write short notes on:
a. Data Security b. e-Commerce
8. What is normalization? Explain the normalization process with examples.
9. Explain the terms ‘Polymorphism’ and ‘Inheritance’.
10. What is Internet? What is the use of Internet in business?
11. What do you understand by the term “Data Integrity”? Why it is important thing to be considered
while designing a database? Explain.
12. Write short notes:
a. Co-axial cable b. Satellite

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 303


2068 (2011)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any two of the following questions. [2 x 20 = 40]
1. a. What is an operator? Explain different types of operators used in programming with example.
b. Define ‘Nested Loop’. Write a program to calculate and display the multiplication table using
nested loop.
c. Write a program to find out factorial of any number.
d. What do you mean by ‘ local’, ‘global’ and ‘static ‘ variables? Explain with examples
2. a. What is an array? Write down the similarities and difference of array with pointer.
b. Write a program to read salaries of 300 employees and count the number of employees getting
salary from 10,000 to 15000.
3. a. Write a program to sort an array of ‘n’ elements in descending order.
b. Write a program to enter ‘name’, roll-on’ and ‘marks; of 10 students and store them in a file.
Read and display the same from the file.

Group – B
(Short Answer Questions)
Attempt any five questions. [5 x 7 = 35]
4. What do you understand by the term data integrity? Why it is important in designing a
database?
5. Why is feasibility study? Explain different levels of feasibility study?
6. Why polymorphism and inheritance are important concepts of OOP? Explain.
7. Define program logic. Explain different types of program logic tools.
8. What is system analysis? What are the major objectives of system analysis? Explain.
9. Explain the benefits of centralized database.
10. What are the types of LAN topology? Explain with diagram.
11. What do you understand by AL? How it affects the modern society?
12. Write short notes on:
a. Data dictionary b. Cyber Law

304 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


2069 (2012)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.

Group – A
(Long Answer Questions)
Attempt any two of the following questions. [4 x 10 = 40]
1. What is looping? Describe ‘for’, ‘while’ and ‘do-while’ loops with appropriate example.
2. What is control statement? Write program which selects and prints largest among 3 numbers
using ‘if-else] statement with flow charts.
3. What is string? Explain any four string handling functions with example.
4. Write a program to add two matrices by supplying elements of matrices by the user.
5. Write a program which reads name, department and age from a file named ‘employee.dat’ and
display them on the monitor.

Group – B
(Short Answer Questions)
Attempt any five questions. [7 x 5 = 35]
6. Explain different stages of system development life cycle with clean figure.
7. What are the types of LAN topologies? Explain with diagrams.
8. What is database? List the major uses of database application software.
OR
Differentiate between array and structure.
9. What is E-R diagram? Explain the advantage or E-R diagram in system design.
10. Explain the database model with suitable examples.
11. What are the key challenges of implementing of e-government in development countries?

OR
What is AI? Describe the application of AI.
12. What is multimedia? What are the components of multimedia? List out.
13. Define computer crime and its various forms.
14. Write the advantages and disadvantages of OOP.
15. Write short notes on:
a. Coaxial Cable b. Satellite

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 305


2070 (2013)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any four questions. [4 x 10 = 40]
1. What is nested loop? Write a program to display the multiplication table of nth terms of given
numbers.
2. Describe any five “string handling functions” with examples.
3. Describe array, structure and pointer with examples.
4. Write a program which reads salary of 25 employee and count the number of employee who
are getting salary between 30, 000 and 40,000.
5. Describe fprintf and fscanf file handling functions. Write a program which writes “Welcome to
Nepal” in a file.

Group – B
(Short Answer Questions)
Attempt any seven questions. [7 x 5 = 35]
6. What is feasibility study? Explain different levels of feasibility study.
7. What is Hierarchical database model? List out the advantages and disadvantages of Hierarchical
database model.
8. What is Networking? List out the advantages and disadvantages of Networking.
9. Explain centralized and distributed database models.
10. Explain any tow transmission media with appropriate diagram.
11. Differentiate between “While” and “Do-While loop” with flowchart.
12. What is procedural oriented programming? Explain.
13. What is AI? Explain the application areas of AI.
14. What are the components of multimedia? Explain.
15. Write short notes on:
a. E-learning b. Data dictionary

306 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


2071 (2014)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any four questions. [4 x 10 = 40]
1. What is function? Write a program to generate factorial of given number using recursive function.
2. Describe any five “file handling functions” with examples.
3. What is looping? Describe ‘for loop’, ‘while loop’ and ‘do-while loop’ with appropriate examples.
4. Write a program which asks 100 numbers and sort them in ascending order.
5. Write a program to find greatest number among four numbers.
Group – B
(Short Answer Questions)
Attempt any seven questions. [7 x 5 = 35]
6. What is system analysis and design? Describe briefly.
7. What is database? List out the advantages of Database Management System
8. What is network topology? Describe any two network topologies with clear diagram.
9. Describe the centralized and distributed database systems.
10. Describe the ‘Coaxial cable’ and ‘Satellite’ with examples.
11. Describe the different data types which are used in C-programming.
12. What is OOP? List the advantages of OOP.
13. Describe the application areas of AI.
14. Describe the advantages of multimedia.
15. Write short notes on:
a. e-Commerce b. Normalization

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 307


2072 (2015)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any four questions. [4 x 10 = 40]
1. Write a program which find the sum, difference and product of 2 numbers using switch case
statement.
2. a. Differentiate between while and Do-while loop with appropriate example.
b. Write a program to display the following:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
3. Write a program which asks in nth terms of numbers and sort them in ascending order.
4. a. What is function? List out the advantages of functions.
b. Write a program to find the factorial of a given number.
5. a. Describe fscanf and fprintf function.
b. Write a program which asks name, age, roll-number of student and write it in a file student.
dat.

Group – B
(Short Answer Questions)
Attempt any seven questions. [7 x 5 = 35]
6. Describe SDLC with diagram.
7. Define DBMS. List out the objectives of DBMS.
8. What is relational database model? List the advantages and disadvantages of relational database
model.
9. Describe the terms ‘SQL’ and ‘DML’.
10. Define computer network and explain its uses.
11. Describe ‘simplex’, ‘half duplex’, and ‘full duplex’ with example.
12. Differentiate between array and structure with example.
13. What is E-governance? List out the objectives of E-governance.
14. Describe any five application of multimedia.
15. Write short notes on:
a. Computer crime b. Social impact of the ICT

308 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


2073 (2016)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any four questions. [4 x 10 = 40]
1. a. Describe the switch statement with example.
b. What are the differences between while and Do while loop? Explain with syntax.
2. Write a program to read five positive number using array and find out the smallest among them.
3. a. Describe the string manipulation function in C. Explain strcpy and Strcmp with example.
4. Describe the function in C. Write a program to find the sum of ‘n’ integer number using function
in C.
5. Differentiate between structure and union. Write a program to input the employee name and
post of five employee and display the records in proper format using structure.

Group – B
(Short Answer Questions)
Attempt any seven questions. [7 x 5 = 35]
6. What are the major activities in SDLC with based on waterfall model?
7. What id DBMS? Explain data integrity with suitable example.
8. Define DML and DDL with example.
9. Describe the Bus Star topology with suitable diagram.
10. Differentiate between guided and unguided networking media.
11. What is variables in programming? List out the different data types in C program.
12. Describe the different mode of the handling concept in C.
13. Describe the cyber crime in Nepal. What are protection method to the cybercrime?
14. What is multimedia? List out the component of multimedia.
15. Write short notes on:
a. DBMS b. Network protocols

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 309


2074 (2017)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any four questions. [4 x 10 = 40]
1. a. What is switch statement in C Program? Explain with example.
b. Explain FOR loop in C with example.
2. Describe the syntax of array. Write a program to sort ten integer number in ascending order.
3. What are the methods of function declaration and call in C? Write a program in find out given
number is odd or even using function.
4. What is string? Explain any four string function with example.
5. What is structure in C? Write a program to enter the 20 employee’s name, age, and salary using
structure and print them.
Group – B
(Short Answer Questions)
Attempt any seven questions. [7 x 5 = 35]
6. What are the soft development process phases in SDLC? Explain any one phase.
7. What are the role of DBA? Explain.
8. What are INF and 2NF normalization principle in Database? Explain.
9. Explain Unshielded Twisted Pair (UTP) cable and Coaxial cable.
10. Differentiate between LAN and WAN.
11. Explain the file handling concept on C.
12. List out the difference operator in C. Describe logical operator with example.
13. What are advantage and disadvantage of social media? List out.
14. What is cybercrime? How do you affected from cybercrime in your daily life?
15. Write short notes on:
a. Data Security b. Bluetooth

310 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center


2075 (2018)
Time:3 Hrs. Full Marks: 75
Pass Marks:27
Candidates are required to give their answers in their own words as far as practicable. The figure in the
margin indicate full marks.
Group – A
(Long Answer Questions)
Attempt any four questions. [4 x 10 = 40]
1. a. What is operator? Explain logical and relational with example.
b. Write a program to find out whether entered number is positive or negative number.
2. a. Write the importance of OOP.
b. Write a program to enter 5 integer numbers into an array and display.
3. What is function? Write a program to read the principle, time and rate. Find the simple interest
using function.
4. Write a program to store 50 records of students using fields std no, name and mark. Display the
name of student and mark.
5. Write the importance of normalization? Explain second and third normal form with example.

Group – B
(Short Answer Questions)
Attempt any seven questions. [7 x 5 = 35]
6. List out different stages of system development life cycle and explain any two stages of them.
7. Describe the major role and responsibility of system analyst in SDLC phase.
8. Explain the advantages of Database Management System.
9. What is E-R diagram? Write the meaning of graphical symbols used in E-R diagram.
10. What is transmission media? Explain any two different types of transmission media.
11. Explain the benefits of decentralized database models.
12. Distinguish between “for” and “while” loop.
13. Define the components of multimedia.
14. What is E-commerce? Point out the advantages of E-commerce.
15. Write short notes on:
a. Inheritance b. Application of AI

Approved by Curriculum Development Center Asia’s Start Up Computing - Book 12 311


Bibliography

1. See S. G. Nash, A History of Scientific Computing (1990)


2. A. Cohen, Introduction to Computer Theory (2d ed. 1996);
3. P. Norton, Peter Norton’s Introduction to Computers (2d ed. 1996);
4. A. W. Biermann, Great Ideas in Computer Science: A Gentle Introduction (2d ed. 1997);
5. R. L. Oakman, The Computer Triangle: Hardware, Software, People (2d ed. 1997);
6. R. Maran, Computers Simplified (4th ed. 1998);
7. A. S. Tanenbaum and J. R. Goodman. Structured Computer Organization (4th ed. 1998).
8. Greg Perry and Dean Miller, C Programming Absolute Beginner’s Guide
9. Brain W. Kernighan, C Programming Language
10. Griffiths David, Head First C: A Brain-Friendly Guide
11. “Sams Teach Yourself SQL in 10 Minutes” By Ben Forta
12. “Learning SQL” By Alan Beaulieu
13. “SQL: The Ultimate Beginners Guide: Learn SQL Today” By Steve Tale
14. “SQL: QuickStart Guide – The Simplified Beginner’s Guide To SQL” By Clydebank Technology
15. Mark Mayers, A Smarter Way to Learn JavaScript
16. Elizabeth Robinson, Head First JavaScript Programming: A Brain-Friendly Guide
17. Nicholas C. Zakas, The Principles of Object-Oriented JavaScript
18. C. J. Date, A. Kannan and S. Swamynathan, An Introduction to Database Systems, Pearson
Education, Eighth Edition, 2009.
19. Abraham Silberschatz, Henry F. Korth and S. Sudarshan, Database System Concepts, McGraw-
Hill Education (Asia), Fifth Edition, 2006.
20 Shio Kumar Singh, Database Systems Concepts, Designs and Application, Pearson Education,
Second Edition, 2011.
21. Peter Rob and Carlos Coronel, Database Systems Design, Implementation and Management,
Thomson Learning-Course Technology, Seventh Edition, 2007.
22. Patrick O’Neil and Elizabeth O’Neil, Database Principles, Programming and Performance,
Harcourt Asia Pte. Ltd., First Edition, 2001.
23. Atul Kahate, Introduction to Database Management Systems, Pearson

312 Asia’s Start Up Computing - Book 12 Approved by Curriculum Development Center

You might also like