A Textbook On Computer Science-Grade 12: Asia's
A Textbook On Computer Science-Grade 12: Asia's
Asia’s
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]
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
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
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.
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.
Fields
Employee Master Table
Emp No Dept No. Address
Records E01 D01 New Road
E02 D02 Prithivi Chowk
E03 D03 Surket Road
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.
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.
USER
Data File
USER
Data File
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:
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.
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.
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
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
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.
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
a. What is Database Management System? What are the advantages and disadvantages of
DBMS?
b. What are the objectives of Database Management System.
NCC
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
COURSE
STUDENT
Antony 1021 1
Bob 1022 1
Deeksha 1023 1
Rohan 1024 1
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
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)
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
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
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
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
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
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.
{ {
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.
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
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
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.
Example:
CREATE TABLE Customers
( CustID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
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;
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;
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 ;
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;
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;
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.
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);
Syntax:
UPDATE table_name
SET column_name1 = new-value1,
column_name2=new-value2, ...
[WHERE Clause]
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.
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.
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.
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.
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.
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).
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.
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)
Transmitter Receiver
Half Duplex (Both ways, but
only one way at a time)
Receiver Transmitter
Receiver Transmitter
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
Files
Files
Peer
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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).
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).
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.
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
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).
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.
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.
PC
PC
t Host
Interne
TCP/IP
Serve
r
Router
Internet
PC
It does not provide security for data. It provides more security for data.
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.
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.
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>
Solved Example
<html>
<body>
<script type = “text/javascript”>
<!--
document.write(“Hello World”)
//-->
</script>
<p>StartUp Computing</p> Output
</body> StartUp Computing
</html>
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>
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
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
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;
Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Object Data Type</title>
</head>
<body>
<script>
Solved Example
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>JavaScript Array Data Type</title>
</head>
<body>
<script>
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!”;
}
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!”
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”;
Solved Example
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Solved Example
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
<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:
Comparison Operators
The comparison operators supported by javascript are:
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
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>
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.
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>
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>
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>
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.
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>
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>
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.
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.
Solved Example
var person = {
firstName: “Raj”,
lastName : “Rai”,
id : 5566,
fullName : function() {
return this.firstName + “ “ + this.lastName;
}
};
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>
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.
Solved Example
<!DOCTYPE html>
<html>
<body>
<button onclick=”document.getElementById(‘demo’).innerHTML=Date()”>The
time is?</button>
<p id=”demo”></p>
</body>
</html>
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>
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>
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.
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
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”.
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.
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.
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.
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.
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 */ .
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>
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.
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>
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.
<?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 . “!”;
}
}
</body>
</html>
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:
<?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
=== 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
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.
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 )
);
NOTE : MySQL does not terminate a command until you give a semicolon (;) at the end of
SQL command.
Solved Example
<html>
<head>
<title>Creating MySQL Tables</title>
</head>
<body>
<?php
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>
Solved Example
<!DOCTYPE html>
<html>
<body>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
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());
}
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>
Solved Example
<?php
$dbhost = ‘localhost:3036’;
$dbuser = ‘root’;
$dbpass = ‘rootpassword’;
if(! $conn ) {
die(‘Could not connect: ‘ . mysql_error());
}
if(! $retval ) {
die(‘Could not get data: ‘ . mysql_error());
}
mysql_close($conn);
?>
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().
INFONET SERVICES
First Name
Last Name
E-mail Address
Address
City
State Postal Code Country
Please choose the most appropriate statement
Hiking
Mountain Biking
Camping
Rock Climbing
Off-Road 4WD
Cross-country Skiing
I learned about this site from
Print Ads
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.
Yes NO,Thanks!
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.
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.
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.
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!
}
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.
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
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.
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;
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
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.
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:
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.
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:
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.
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.
Program Output:
Value of a is 1.200000
Value of b is 2
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.
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.
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
…………………………………
…………………………………
}
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.
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
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”);
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
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);
}
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.
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.
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.
There is no argument passed to input() function But, the value of n is returned from input() to
main() function.
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.
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) );
}
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.
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}
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.
}
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);
}
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);
}
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.
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;
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
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);
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
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();
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
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);
}
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);
}
}
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];
};
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);
}
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
#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”);
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”);
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.
fff4 50
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
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);
}
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);
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);
}
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++;
}
}
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
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.
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
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
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.
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);
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
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;
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());
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);
}
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.
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;
};
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();
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”.
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;
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.
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%.
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);
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);
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);
}
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%.
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.
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 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
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.
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.
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.
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.
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
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:
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.
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.
e
totyp
Pro
rking
Wo
New Requirements
Problems
Implement and Use Revise and Enhance
Prototype Prototype
Next Version
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
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.
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.
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
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.
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.
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.
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.
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
Customers
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
- no
e
nd
Ra
Qua hase
Ge
tact
ntity
e
c
Con
Pur
An ERD for ‘Customer’ and ‘Goods’ entity
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.
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).
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
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.
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.
Order Food
Service person
Customer
Prepare Bill
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.
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.
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.
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.
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.
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).
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.
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.
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.
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:
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.
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.
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.
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.
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.
Project Report
A project report must contain the following topics:
1) Cover page 2) Acknowledgement 3) Table of Contents
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”);
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
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
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
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
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