New Gateway To Computer Science 10
New Gateway To Computer Science 10
New Gateway To Computer Science 10
NEW GATEWAY
TO
COMPUTER SCIENCE
10
Authors
Dinesh Adhikari
Dilendra Prasad Bhatta
Shekhar Poudel
Laxman Adhikari
© : Publisher
No part of this book may be reproduced or transmitted by means (electronic, photocopying,
recording or otherwise) without prior written permission from the publisher. Any breach of this
condition will entail legal action and prosecution.
Printed in Nepal
Preface
Preface
Along with the evolution of human beings new thoughts, area of knowledge and
technology also developed together. Among the eruptions, ICT (Information and
Communication Technology) is one which has unquestionably become important
part of human beings. A person is not better than a caged pigeon if s/he is far
from computer technology in this century. New Gateway to Computer Science is
a complete package which obviously supports a lot to the students as this is one
of the most useful textbook, so far available in the market.
This book is completely prepared considering the level of the students. This
text has various salient features like it focuses on child psychology, pictorial
descriptions, practical sections, let’s Review, sufficient exercise, etc.
Comments and constructive suggestions are highly welcomed from the readers
and professionals to update this text book.
Dinesh Adhikari
dinesh.nayaghare@gmail.com
Content
Lesson 4: E-Commerce.....................................................................................66
List of Abbreviations.........................................284-288
Introduction to
Technology Fundamentals
Unit
Learning Outcomes
Let’s Review
Data communication technologies deal with the means and methods of data
transfer from one location to another using wired or wireless transmission medium.
Telecommunication systems are a specialized system for communication.
Transmission is the channel or physical path through which message is carried from
the sender to the receiver.
The device that sends data to the destination or target is the sender.
Transmission mode means transferring of data between two devices. It is also known as
communication mode. The three modes of data transmission are simplex, half-duplex and
full duplex. They are explained below.
Transmission Mode
Simplex Mode
In a simplex communication mode, data
can transmit in one direction only. It One Direction
is suitable for connecting send-only
like keyboard or receive only like
monitor devices. In simplex mode, the
communication is unidirectional. The simplex mode can use the entire capacity of the
channel to send data in one direction. The best example of simplex mode is radio and
television broadcasting. In this mode, there is just one communication channel. So, we
can receive data on that channel but could not be able to transmit on the same channel.
The speed in which data can be transmitted from one device to another across a
communication channel is called data transmission rate. Data transmission rates are
measured in Kbps, Mbps, Gbps, etc.
The difference between the highest and the lowest frequencies on a transmission is called
bandwidth. Bandwidth of a communication system refers to its data transfer rate. The
data transfer capacity, or speed of transmission, of a digital communication system is
measured in bps (Bits Per Second). Based on the data transmission speed, there are three
basic categories of communication channels which we are going to discuss below.
Narrowband: Narrowband is used where data volume is relatively slow or fewer amounts
of data are to be transmitted. These utilize the channel frequency that is considered flat or
which will use a less number of frequency sets.
Wideband: Wideband channel has a medium capacity of data transmission rate. Wideband
channels can carry more information than narrowband channels, but they typically require
more power to do so.
Let’s Review
The speed in which data can be transmitted from one device to another across a
communication channel is called data transmission rate.
The difference between the highest and the lowest frequencies on a transmission
is called bandwidth.
There are three basic categories of communication channels. They are narrowband,
wideband and broadband.
The electric signals have limited bandwidth and cannot be used in long distance
communication.
An analog signal is a wave that continuously changes its information carrying
properties over time.
A digital signal is a wave that takes limited number of values at discrete intervals of
time.
Types of Transmission
Media
Twisted Pair Cable: It consists of two separately insulated conductor wires wounded
about each other. Generally, several such pairs are bundled together in a protective sheath.
They are the most widely used transmission media. There are two types of twisted pair
cable.
Unshielded Twisted Pair (UTP): This type of cable has the
ability to block interference and does not depend on a physical
shield. It is used for telephonic applications. It is easy to install
and it has high capacity. It is a cable with wires that are twisted
together to reduce noise and crosstalk.
Let’s Review
Transmission media is a pathway that carries the information from the sender to
receiver.
Guided media is also called bounded media or wire media. In this communication
media, data travel through the wire instead of wave.
Unguided media is also called unbounded media or wireless media. In this
communication media, data travel through the air instead of cable.
Radio waves are a type of electromagnetic radiation used in communication
technologies, such as television, mobile phones and radios.
Shielded Twisted Pair cable consists of a special jacket to block external interference.
Microwave transmission refers to the technique of transmitting information over a
microwave link.
Computer Network
There are various hardware and software elements used to create a networking mechanism
which we are going to discuss below.
Hardware Elements
NIC (Network Interface Card)
A NIC is a device that helps the computer to communicate
with another device. It is also called network card. NIC is a
printed circuit board which connects one of the expansion
slots of a computer and provides a port for attaching a network
cable. There are two types of network interface cards namely
wireless and wired. The wireless NIC is used by the modern
laptops devices. Wireless NIC is a connection that is made using the antenna which
employs the radio wave technology. Like this, the wired NIC uses wire to transfer data
over the medium.
Connectors
A connector is a device that terminates a segment of cabling or
provides a point of entry for networking devices such as computers,
hubs, and routers. Connectors can be distinguished according to their
physical appearance, such as jacks and plugs (male connectors) or
sockets and ports (female connectors).
Hub
A Hub is a multiport central connectivity networking device that
splits the network connection into multiple devices. When the
computer requests for information from a computer, it sends
the request to the hub. Hub distributes this request to all the
interconnected computers. Hub is a device that connects cables
from computers and other devices such as printers in a local area network. Hubs are used
in start topology networks but they are often used with other configuration to make it easy
to add and remove computers without bringing down the network.
Router
MODEM
The MODEM stands for Modulation and Demodulation. It connects the computer to the
internet over the existing telephone line. A modem is not integrated with the computer
motherboard. It is a separate part on the PC slot found on the motherboard. Modem speed
is measured in bps , Kbps, Mbps, etc. which is the speed in which the modem can send
and receive data. The common use for modems is to both sending and receiving of the
digital information between personal computers.
Repeater
Gateway
A gateway is a node in a computer network.
It connects two networks having dissimilar
communication protocol. A gateway device provides communication to a remote network
or an independent system that is out of bounds for the host network nodes. Gateways serve
as the entry and exit point of a network; all data routed inward or outward must first pass
through and communicate with the gateway in order to use routing paths. Generally, a
router is configured to work as a gateway device in computer networks. For basic Internet
connections at home, the gateway is the Internet Service Provider that gives you access
to the entire Internet.
Bridge
A bridge is a type of computer network device
that provides interconnection with other bridge
networks using the same protocol. It reduces
the amount of traffic on a LAN by dividing it
into two segments. Bridge devices work at the
data link layer of the Open System Interconnect (OSI) model, connecting two different
networks together and providing communication between them. Bridges are similar to
repeaters and hubs in that they broadcast data to every node.
Software Elements
Network Operating System (NOS)
An operating system that enables a machine to participate in the network is called
networking operating system. Network operating systems are designed for client computers
Let’s Review
A gateway is a node in a computer network. It connects two networks
having dissimilar communication protocol.
A bridge is a type of computer network device that provides interconnection with
other bridge networks using the same protocol.
The set of rules and regulations that must be followed by the sender and the receiver
while communicating with each other over the network is called protocol.
A device driver is a software program that controls a particular type of hardware
device that is attached to the computer network.
TCP/IP, HTTP, FTP, SMTP, POP, IPX/SPX, Apple Talk and NetBEUI are the types of
network protocols.
Network Topology
Network topology refers to the layout of the network in which all the devices are
connected. The network topologies can be physical or logical. Physical topology refers
to the physical shape or design structure of a network including the nodes, devices
and cables. Logical topology refers to how data are transferred or exchanged between
computers within the network. Network topology also refers to the physical topology
where topology is the way in the cables and devices that connect the computers in the
network. The commonly used network topologies are Bus, Star and Ring which we are
going to discuss below.
Star Topology
Let’s Review
Network topology refers to the layout of the network in which all the devices are
connected.
Topology refers to the physical shape or design structure of a network including
the nodes, devices and cables.
In start topology, all the computers are connected to a centrally placed device called
hub or switch.
In ring topology, all the computers are connected to each other in a closed loop with a
single cable with each other.
In bus topology, all the nodes are connected to a single cable, with the help of
interface connectors.
Services of Internet
Search Engine
Search engines are the websites that allow the users to search
information based on keyword or a combination of keywords.
Search engines are used to locate web sites and information. To
search the information, users need to enter the desired search term
into the search field. After that, the search engine looks through its index for relevant
websites and displays them in the form of a list. www.google.com, www.yahoo.com,
www.bing.com, www.ask.com, etc. are some examples of search engines.
Web Browser
A browser is a software that is used to access the internet to view
the web pages. It allows us to visit websites and do the various
activities within them. The most common web browser software
are Microsoft Internet Explorer, Google’s Chrome, Mozilla
Firefox, Apple’s Safari, and Opera. The availability of browser
depends on the operating system that your computer system has used.
The process of receiving information at your computer from another computer through
a network is called downloading. This is a process of transferring a copy of a file from
a remote computer to the requesting (local) computer. It is just the reverse of uploading.
Each time when you visit a webpage, your computer or mobile device must download
the HTML, CSS, images, and any other relevant data in order to display the page in your
web browser.
Uploading
The process of transferring the information from your computer to another computer
through a network is called uploading. This is a process of transferring a copy of a
file from a local computer to the requesting computer. The most common method of
uploading a file to another computer or server is by using FTP (File Transfer Protocol). If
you are uploading a file to another site, you must have permission to access the site and
the directory where the file is to be placed.
Let’s Review
Internet is defined as an interconnection of networks. with allows computers on
different kind of networks to interact with each other.
Search engines are the websites that allow the users to search information
based on keyword or a combination of keywords.
Search engines are used to locate web sites and information.
The most common web browser software are Microsoft Internet Explorer, Google’s
Chrome, Mozilla Firefox, Apple’s Safari, Opera, etc.
The process of receiving information at your computer from another computer
through a network is called downloading.
The process of transferring the information from your computer to another
computer through a network is called uploading.
Web Chat
A web chat is a system that allows users to communicate in real time using easily
accessible web interfaces. It is an online interactive communication mechanism that
allows people to have real time discussion with one or more people through the Internet.
Let’s Review
A web chat is a system that allows users to communicate in real time using easily
accessible web interfaces.
A domain name is the address where the internet users can access your website.
A domain name is used for finding and identifying computers on the internet.
Internet Protocol address, is an identifying number for network hardware that
helps to connect to a network.
IP address allows a device to communicate with other devices.
World Wide Web was invented by Tim Berners-Lee in 1989. This was invented initially
for scientists to easily share data available as part of their experiments. It is a collection
of web resources and pages found on the network. To access the www, we must have web
browser. Web consists of three main components they are listed below.
HTML: Hypertext Mark-up Language is a standard mark-up language used to create
web pages.
URL: Uniform Resource Locator is the understandable form of a web address
which is used to identify a resource.
HTTP: Hyper Text Transfer Protocol acts as the foundation of the Web.
Telnet (Terminal Emulation Network)
Telnet was developed in 1969 to support in remote connectivity between computers over
a network. Telnet allows us to connect remote computers over a TCP/IP network. It is a
network protocol used on the Internet or local area networks to provide a bidirectional
interactive communications facility. The term telnet also refers to software which
implements the client part of the protocol.
Newsgroups
A newsgroup is an Internet-based online discussion forum where so many people can
put their views and ideas on a particular area of interested topic. It enables remotely
connected users to share, discuss and learn about their topic of interest by exchanging text
messages, images, videos and other forms of digital contents. It was created in 1979 by
some university students to exchange their messages with each other.
Electronic Mail
Electronic mail also called as an E- mail is a digital
message used for creating, sending, receiving and
storing textual data in the digital format over a
network. Electronic mail is one of the most widely
used features of the Internet. It allows us to send and
receive messages to and from anyone with an email
address, anywhere in the world. Instead of using a
pen to write a letter on paper, we are using keyboard
or voice to write an email message on an electronic
device like a phone or computer. Email addresses are written with a custom username at
the beginning followed by the email service provider’s domain name, with an @ sign.
Email system uses multiple protocols within the TCP/IP . When you configure an email
Let’s Review
Telnet was developed in 1969 to support in remote connectivity between
computers over a network.
A newsgroup is an Internet-based online discussion forum where so many people
can put their views and ideas on a particular area of interested topic.
Electronic mail is one of the most widely used features of the Internet.
Email allows us to send and receive messages to and from anyone with an email
address, anywhere in the world.
Hypertext Transfer Protocol is a set of rules for transferring files, such as text,
graphic images, sound, video, and other multimedia files, on the www.
Innovative Task
Take a short interview with you principal and subject teacher about the ISP that is
being used at your school. Also ask them about the positive and negative aspects
of it. Then, prepare a project report.
List out the name of various ISP of Nepal and make a short report.
Prepare a project report about the networking mechanism that is being used in your
school.
Visit some organizations nearby you and observe the networking structure over
there. Also prepare a report and submit to your teacher.
Visit a computer shop and list out the various types of Wi-Fi router models available
there.
Learning Outcomes
Ethical and social issues arising from the use of technology in all areas of our lives such
as business, health sector, education and so on. Because of the recent development in the
technology and their ability to transmit vast amounts of information in a short amount of
time, there is a great impact of ICT in the society. The implementations of technology in the
workplace create various social and ethical concerns so there should be further analysis of
technology in an organization. Information Communication Technology (ICT) has raised
new ethical concerns about the protection of personal privacy, protection of intellectual
property, user responsibility, acceptable access and use of information, software licenses
and piracy. A good ICT policy must be able to adequately consider these, and many other
associated issues.
The first IT policy was introduced in 2057 B.S. which was related to the IT education
and some other activities. Ministry of Information and Communication, Government of
Nepal introduced second National Information and Communication Technology Policy In
2015AD. In this chapter we are going to discuss about it.
Electronic Transaction Act deals with the issues that are related to cybercrime. This act
also helps to make and implement the laws. In Nepal, the House of Representatives
approved this act on December 4, 2063. At that time, ministry of environment, science
and technology formulated the Regulations. The new legislation has not only legalised all
forms of electronic transactions and digital signatures but has also clearly suggested out
the ways to regulate various computer-based activities and punish cybercrimes.
The electronic transaction and digital signature is valid not only for the private sector
but also for the government agencies. It allows the government offices to use electronic
medium for tender notice, vacancy announcement and others. It also validates public
procurement and acceptance of electronic applications.
The computer and cybercrimes such as hacking, piracy, copyright violation, fraudulent
and all other deceitful activities have been clearly defined and punishments are set
accordingly. The action against such crimes and punishment will be in the range of a
minimum Rs. 50,000 to a maximum Rs 3,00,000 in cash and six months to three years
custody.
Digital Footprint
A digital footprint is a track of data that you create while using the internet. It includes the
websites that you visit, email that you send, uploading videos or digital images and any
other form of transmission of information. Publishing a blog and posting social media
updates are another popular ways to expand your digital footprint. The status that you
have update and publish on Facebook or twitter contributes to your digital footprint. The
more you spend time on social networking websites, the larger your digital footprint will
be. Even “liking” a page or a Facebook post adds to your digital footprint, since the data
is saved on Facebook’s servers.
There are two types of digital footprint they are active and passive footprints which
depends on how your information is acquired. Posting on Facebook, Instagram, Twitter,
and other social media platforms, filling online forms, agreeing to install cookies on your
devices are the examples of active footprint.
In the same way, websites that install cookies in your device without disclosing it to you,
social media news channels and advertisers that use your likes, shares, and comments are
the examples of passive footprint.
Facebook: Facebook is a one of the world’s largest social network platform. It is a free
social networking website which allows the user to register and create profiles, upload
photos, video, send messages and keep in touch with friends, family and colleagues.
Twitter: Twitter is a free micro-blogging service that allows registered members to
broadcast short posts called tweets. Twitter members can broadcast tweets and follow
other users’ tweets by using multiple platforms and device.
Google+: It is read as Google plus. It is a Google’s social networking project, designed
to replicate the way people interact offline more closely than is the case in other social
networking services.
Instagram: It is a free photo and video sharing apps that allows the users to apply digital
filters, frames and special effects to their photos and then share them on a variety of social
networking sites.
Wikipedia: Wikipedia was founded in 2001 January. It is a free, open content online
encyclopaedia created through the collaborative effort of a community of users known as
Wikipedians. Anyone registered on the site can create an article for publication; however,
registration is not required to edit articles.
Blogs: Blog is a platform for casual dialogue and discussions on a specific topic or opinion.
Flickr: It is an image and video hosting website and online community. Photos can be
shared on Facebook, Twitter and other social networking sites.
LinkedIn Groups: It is a place where groups of professionals with similar areas of
interest can share information and participate in the conversations.
Innovative Task
Ask with any 20 people in locality and prepare a report about what types of social
media that they are using? How long time they use it in a day? And what type of
information and content they like to read?
Assignment
1. Select the best answer from the given options.
a. The first IT policy was introduced in Nepal in:
i. 2057 BS ii. 2061 BS iii. 2052 BS iv. 2072 BS
b. Which of the following is social media?
i. Photoshop ii. Facebook iii. Graphics iv. Television
c. When Electronic Transaction Act was approved in Nepal?
i. 2054 BS ii. 2063 BS iii. 2073 BS iv. 2050 BS
d. Which of the following is related to digital citizenship?
i. Communicating with respect ii. Harming to others with technology
iii. Junk Mails iv. Doing piracy
e. Which of the following is active digital footprint?
i. Posting on facebook ii. Filling online forms
iii. Chatting with others iv. Both i and ii
Learning Outcomes
Let’s Review
Security Threats
We all have to be secure in our office, locality, home, city, country and in this global
world. These days, protecting the computer system from the threats is very challenging. A
threat refers to anything that has the potential to cause serious harm to a computer system.
A threat can be malicious program, a natural disaster or a thief. Security threats may occur
from the user computer hardware and computer software. The aims of some types of
threats are; to get information from the system (without affecting the system resources)
and to alter the system resources or affect its operations.
Malicious Codes
Malicious code is the term used to describe any code in any part of a software system or
script that is intended to cause undesired effects, security breaches or damage to a system.
Malicious code is an application security threat that cannot be efficiently controlled by
conventional antivirus software. Malicious code describes a broad category of system
security terms that includes attack scripts, viruses, worms, Trojan horses, backdoors and
malicious active content.
Malicious code can enter network drives and spread on another system as well. Malicious
code can also cause network and mail server overload by sending email messages;
stealing data and passwords; deleting document files, email files or passwords; and even
reformatting hard drives.
Security mechanisms deal with prevention, detection, and recovery from a security attack.
Prevention involves mechanisms to prevent the computer from being damaged. Detection
requires mechanisms that allow detection of when, how, and by whom an attacked
occurred. Recovery involves mechanisms to stop the attack, assess the damage done, and
then repair the damage. Security mechanisms are built using personal and technology.
Personal are used to frame security policy and procedures, and for training and awareness.
Security mechanisms use technologies like cryptography, digital signature, firewall,
user identification and authentication, and other measures like intrusion detection, virus
protection, data and information backup as countermeasures for security attack. Let’s
discuss some of the security mechanism below.
Authentication System
Authentication is the process of ensuring and confirming the identity of the user before
revealing any information to the user. It provides confidence in the identity of the user or
the entity connected. It also assures that the source of the received data is claimed.
Authentication is facilitated by the use of username and password, smart card, biometric
methods like retina scanning and fingerprints.
Password: Passwords are the most common tool for restricting
access to the computer system. It is a set of secret characters or
words used to authenticate access to a digital system. Passwords
help ensure that computers or data can only be accessed by
those who have been granted the right to view or access them.
Passwords are typically used with a username. It can vary in length and can contain
letters, numbers and some other special characters. There are many authentication options
available today so that users do not have to depend on passwords that can be easily
cracked or compromised.
Biometric: Biometric technology is mainly used for
identification and access control. Biometrics includes
physiological characteristics such as fingerprints or retinal
scans, and behavioural characteristics such as typing patterns
and voice recognition system. A biometric system is a
technological system that uses information about a person to
identify that person. Biometric systems depend on specific
data about unique biological behaviours in order to work effectively. Any government
organizations, businesses and other organizations can use biometric systems to get more
information about the individuals. Many biometric systems are developed for security
Hardware Security
The protraction or security given to different computer parts and other peripheral devices
is called hardware security. If any physical part of the computer stops to work, the entire
system may not respond. Dust, heat, low or high temperature, voltage fluctuations, etc.
may cause serious problem on the hardware components. We can apply the given security
mechanisms to protect the hardware components of the computer system.
Regular Maintenance
Regular maintenance of a computer means taking regular steps that make your computer
work faster and more secure. Computer may get slow down and be unable to perform the
task, at that moment we can do proper maintenance and fix the errors that occur. Regular
maintenance helps us to find the hardware problems and keep the individual parts of
computer in good condition.
Let’s Review
The security given to different computer parts and other peripheral devices are
called hardware security.
Regular maintenance of a computer means taking regular steps that make your
computer faster and more secure.
A computer room with proper air condition maintains the temperature and
humidity.
To prevent the computer from fire we must have fire extinguishers.
Computer insurance provides cover for loss or damage of computer equipment.
Surge suppressor helps to protect the device against damage from the surges and
spikes.
The UPS helps to protect against potential electrical power problems by supplying
a consistent level of electrical power to a computer or other devices.
A voltage stabilizer regulates the voltage if the supply voltage fluctuates over a
given range.
A spike guard has multiple sockets for connecting electrical and electronic devices.
Volt guard controls the fluctuation of electric voltage.
Assignment
1. Select the best answer from the list of choices.
a. Computer security is also called as ………..
i. cyber security ii. virus security ii. program security iv. File security
b. Which of the following is security threats?
i. Downloading software ii. Updating software
iii. Removing software iv. Computer Virus
c. Which of the following is authentication system?
i. Password ii. Biometric iii. Cryptography iv. All of the them
d. What do you mean by encryption?
i. Converting plain text to cipher text ii. Converting cipher text to plain text
iii. Both of them iv. None of them
e. Which of the following is related to back up?
i. Storing on secondary storage ii. storing on primary memory
iii. Storing on cloud storage iv. Both i and iii
f. The temperature in the computer system should be maintained between ....to ......
i. 21oC and 24oC iii. 22oC and 25oC
ii. 23oC and 26oC iv. None of the above
g. ....... protects the machine and peripheral hardware s from left, electronic intrusion
and damage.
i. Information security iii. Hardware security
ii. Software security iv. None of the above
h. To prevent the loss of data during power failures, use a(n):
i. encryption program. iii. surge protector.
ii. firewall. iv. UPS.
Learning Outcomes
E-Commerce is massively used in the world these days. It has various benefits and
limitations. Let’s discuss some of the benefits and limitations of using E-Commerce.
Benefits
Easy to reach on the global market.
We can easily choice the products that we want.
Customers can easily select products from different providers.
It helps to save our time.
Easy to start and manage a business.
No need of physical company set-ups.
Low operational costs and better quality of services.
Limitations
Fraud and online insecurity is increasing rapidly.
Data privacy issues are increasing.
Customer cannot test or check the services or goods.
It is totally dependent on electronic technologies.
There is no guarantee of product quality.
Unnecessary rumour may spread with in a second all over the world.
Types of E-Commerce
M-Commerce
An international online payment gateway from Nepal has just started from 2017 A.D.
which provides a safe, secure and easy payment solution. More and more successful
merchants are using this online payment system in Nepal to increase their business
potential. Online payment gateways work in fast and safe way, by allowing consumers
to pay directly using internet and their credit or debit card. By establishing an online
gateway portal from an application or website to the bank the sharing of information and
data becomes possible.
Some of the online payment service providers in Nepal are Esewa, Khalti, Ipay, IME Pay,
Qpay, PayWay, and so on.
Innovative Task
Prepare a project report about any 5 popular e-commerce website those who are
providing e-commerce services in our country.
Take a short audio interview with your school principal and teachers then present
in the class. (Sample questions are provided below. You can ask some more
questions as you like).
What type of internet service you are using in your mobile?
How long hours do you stay connect with internet?
Do you know about internet banking?
Are you using internet banking facility?
Is there any apps installed in your mobile developed by the bank?
Do you have SMS banking system?
Do you have ATM card? Are you able to use it any time?
Do you use credit card for shopping?
Do you know about online-shopping? If yes, are you satisfied with their
services and product?
Are you using any online payment system?
What types of suggestions do you have for the students regarding the use
of technology?
Learning Outcomes
The uses of ICT tools are rapidly increasing these days in the world. Latest and updated
devices and software programs are introducing in the world. In this age of globalizations,
all of us must be updated with the latest technologies that are being used in the world. In
Nepal, the uses of ICT tools are increasing then before. People are using latest ICT tools
and software programs in our country as well. Here, we are going to discuss some of the
contemporary technologies that are used these days.
Cloud Computing
Artificial Intelligence
Artificial Intelligence (AI) is the area of computer science focusing on creating machines
that can engage on behaviours, that human consider intelligent. It refers to the simulation
of human intelligence in machines that are programmed to think like humans and simulator
their actions. The term may also be applied to any machine that displays qualities related
with a human mind such as learning and problem-solving.
The applications for artificial intelligence are endless. The technology can be applied to
many different sectors and industries. AI is being tested and used in the healthcare industry
and different treatment in patients, and for surgical procedures in the operating room.
The various application areas where AI is currently being used include game playing,
speech recognition, natural language processing, computer vision, expert systems, neural
networks, robotics, etc. Some of the business functions where AI is used are finance,
medicine, manufacturing industry, transportation, telecommunication, aviation, etc.
Virtual Reality
Virtual Reality (VR) is the use of computer technology to create a simulated environment.
It is an artificial environment that is created with software and presented to the user in such
a way that the user suspends belief and accept it as a real environment. On a computer,
VR is primarily experienced through two of the five senses: sight and sound. The simplest
E-Governance
Mobile Computing
Mobile computing is a generic term that refers to a variety of devices that allow people to
access data and information from wherever they are. Mobile computing transports data,
voice, and video over a network via a mobile device. Mobile devices can be connected to
a local area network (LAN), Wi-Fi or wireless technology by connecting via a wireless
local area network (WLAN). Mobile phone services also provide mobile computing
through their service plans. Mobile computing devices are portable devices capable of
operating, executing, providing services and applications like a computing device. There
are many benefits to mobile computing including the ability to get directions, entertain,
do business, and more, including:
Connectivity: You can stay connected to all sources at all times.
Social Engagement: You can interact with a variety of users via the Internet.
Personalization: You can tailor your mobile computing to your individual needs.
The following are the features of mobile computing
It a portable device so it can be used anywhere easily and it can be used at any time.
E-learning
Electronic Banking is an umbrella term for the process by which a customer may perform
banking transactions electronically without visiting an institution. All forms of banking
services and transactions performed through electronic means. E-banking includes the
systems that enable financial institution customers, individuals or businesses, to access
accounts, transact business, or obtain information on financial products and services
through a public or private network, including the internet.
E-banking is a safe, fast, easy and efficient electronic service that enables you access to
bank account and to carry out online banking services, 24 hours a day, and 7 days a week.
The customer using this facility can conduct transactional and non-transactional tasks
including:
The customer can view account statements.
The customer can check the history of the transactions for a given period by the
concerned bank.
Bank, statements, various types of forms, applications can be downloaded.
The customer can transfer funds, pay any kind of bill, recharge mobiles, etc.
The customer can buy and sell on e-commerce platforms.
The customer can invest and conduct trade.
The customer can book transport, travel packages, and medical packages.
There are many different types of e-banking services which you can use for various bank
transactions. Let us discuss some of the most popular options.
Internet Banking
Internet Banking is a type of e-banking service which allows you to do several financial
and non-financial transactions through the internet. You can use your PC or laptop and an
internet connection to use this facility. With the help of Internet Banking, you can transfer
funds to another bank account, check your account statement, pay online bills, etc.
Mobile Banking
Most banks now also have an app for Mobile Banking. Just like the online portal of the
bank used for Internet Banking, you can use the app for many different types of banking
transactions. If you use an Android or iOS device, you can download the app of your bank
and use this facility. The apps can also be used for transferring funds, checking account
statements, locate the nearest ATM, and other banking services.
Let’s Review
Mobile computing is a generic term that refers to a variety of devices that allow
people to access data and information from wherever they are.
Mobile phone services also provide mobile computing through their service plans.
Mobile computing devices are portable devices capable of operating, executing,
providing services and applications like a computing device.
E-learning is a new concept of delivering digital contents in learner oriented
environment using information and communication technology (ICT).
E-learning can be done using an Internet connection, a network, an Intranet, or a
storage disk.
Electronic Banking is an umbrella term for the process by which a customer may
perform banking transactions electronically without visiting an institution.
Internet Banking is a type of e-banking service which allows you to do several
financial and non-financial transactions through the internet.
The Internet of Things refers to the ever-growing network of physical objects that
feature an IP address for internet connectivity, and the communication that occurs
between these objects and other Internet-enabled devices and systems.
Assignment
1. Select the best answer from the list of choices.
a. What do you mean by contemporary technology?
i. Latest and update technology ii. Traditional type of technology
iii. Online technology iv. Phase out technology
b. Which of the following is the services of cloud computing?
i. Email ii. Audio and Video
iii. Creating and testing apps iv. All of them
c. Which of the following is related to AI?
i. Natural language processing ii. Operating system
iii. Hardware only iv. Software only
d. Which of the following is closer to E-Governance?
i. Providing computer ii. Proving water supply
iii. Providing E-Services iv. Providing loan
e. Which of the following is closer to E-learning?
i. General education ii. Online education
iii. Copyright iv. Offline education
f. Which of the following is E-Banking service?
i. Providing cheques ii. Providing voucher
iii. ATM card, SMS banking iv. All of them
2. Fill in the blanks with correct words / phrases.
a. The cloud is just an ……………. for the Internet.
b. .…………….. cloud services provide their services over the Internet with some
charges.
c. ……………………..refers to the simulation of human intelligence in machines
that are programmed to think like humans and simulator their actions.
Learning Outcomes
When we type some letters or words, the computer translates them in numbers as
computers can understand only numbers. A computer can understand positional number
system where there are only a few symbols called digits and these symbols represent
different values depending on the position they occupy in the number. Number systems
use different number bases. A number base indicates how many different digits are
available when using a particular numbering system. For example, the base of decimal
number is 10, which means it uses ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. The base of
binary number is 2, which means that it uses two digits that are 0 and 1.
A number system in base r or radix r uses unique symbols for r digits. One or more digits
are combined to get a number. The base of the number decides the valid digits that are
used to make a number. In a number, the position of digits starts from the right-hand side
of the number. The right most digits has position 0, the next digit on its left has position1,
and so on. The digits of a number have two kinds of values they are face value and
position value.
The face value of a digit is the digit located at that position. For example, in decimal
number 87, face value at position 0 is 7 and face value at position 1 is 8.
Position 3 2 1 0
Position Value 23 22 21 20
Quantity 8 4 2 1
Decimal Number System
Decimal number system has only ten (10) digits from 0 to 9. Every number (value)
represents 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 in this number system. The base of decimal number
system is 10, because it has only 10 digits. This is a positional notation numbering system.
Each position in a decimal number system represents a positive power of 10 i.e. 100, 101,
102, 103, 104, 105 and so on. (55)10, (799)10, (8459)10, etc. are the examples of decimal
number system. The position value and quantity of a digit at different positions in a
number are shown in the given table.
Position 3 2 1 0
Position Value 103 102 101 100
Quantity 1000 100 10 1
Octal Number System
Octal number system has only eight (8) digits from 0 to 7. Every number (value) represents
0, 1, 2, 3, 4, 5, 6 and 7 in this number system. The base of octal number system is 8,
because it has only 8 digits. (27)8, (760)8, (5473)8, etc. are the examples of octal number
system. This is a positional notation numbering system. Each position in a octal number
system represents a positive power of 8 i.e. 80, 81, 82, 83, 84, 85 and so on. The position
value and quantity of a digit at different positions in a number are shown in the given
table.
Position 3 2 1 0
Position Value 83 82 81 80
Quantity 512 64 8 1
Position 3 2 1 0
Position Value 163 162 161 160
Quantity 4096 256 16 1
Look at the decimal-hexadecimal-binary conversion table below.
Let’s Review
Number system with their base, used digits and example.
Number System Base Used Digits Example
Binary 2 0 and 1 (10101111)2
Octal 8 0, 1, 2, 3, 4, 5, 6 and 7 (755)8
Decimal 10 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 (7921)10
Hexadecimal 16 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, (D1FB)16
A, B, C, D, E and F
Number Conversion
= 2475 = 3566
Thus: (1341)10 = (2475)8 Thus: (1910)10 = (3566)8
Decimal into Hexadecimal:
Example 1: Convert (494)10 into (?)16 Example 2: Convert (945)10 into (?)16
= 1EE = 3B1
Thus: (494)10 = (1EE)16 Thus: (945)10 = (3B1)16
Binary Arithmetic
The arithmetic operations like addition, subtraction, multiplication and division performed
on the number is called binary arithmetic.
Binary Addition
It works in the same way, except that only 0’s and 1’s can be used, instead of the whole
range of 0-9. This actually makes binary addition much simpler than decimal addition.
The rules of binary additions are as follows:
0+0=0 As an example of binary addition we have,
0+1=1 101
1+0=1 +1 0 1
1 + 1 = 0 (plus a carry of 1 to next higher 1 0 1 0
column
Carry overs are performed in the same manner as in decimal arithmetic. Since 1 is the
largest digit in binary number system, any sum greater than 1 requires a digit to be carried
over. In the above example to add the number (1+1), we first consider the “ones” column
Binary Subtraction
Binary subtraction is also similar to that of decimal subtraction with the difference that
when 1 is subtracted from 0, it is necessary to borrow 1 from the next higher order bit and
that bit is reduced by 1.
The rules of binary subtraction are as follows:
0-0=0
1-0=1
1-1=0
0 - 1 = 1 with a borrow of 1 from the next column.
Subtract the following numbers:
a. 101 from 1001 b. 111 from 1000
Solution: Solution:
101 from 1001 111 from 1001
1 Borrow 1 Borrow
1001 1000
−1 0 1 −1 1 1
0100 0001
Solution: Solution:
11011 101
×101 ×111
11011 101
00000 101
+1 1 0 1 1 +1 0 1
10000111 100011
Binary Division
The rules of binary dicision are as follows:
0 ÷ 0 = Divide by zero error
0 ÷ 1 = 0
1 ÷ 0 = Divide by zero error
1 ÷ 1 = 1
Note that since division by 0 in any number system is meaningless, computers deal with
this problem by raising an error condition called ‘Divide by zero’ error.
Some rules for binary division are listed below.
Step 1 : Start from the left of the dividend.
Step 2 : Perform a series of subtractions, in which the divisor is subtracted from the
dividend.
Step 3 : If subtraction is possible, put a 1 in the quotient and subtract the divisor from the
corresponding digits of dividend.
Step 4 : If subtraction is not possible, record a 0 in the quotient.
101 11
− 11
-11
00
10 (Remainder) − 0
0 (Remainder)
So that, in the above example ‘a’ the quotient is 11 and remainder is 10. Like this in the
above example ‘b’ the quotient is 110 and remainder is 0.
Innovative Task
Prepare a decimal-octal-binary conversation table and decimal-hexadecimal-
binary conversation table in a chart paper and submit to your teacher as your
project work.
Assignment
1. Select the best answer from the list of choices.
A. A positional number system that utilizes the symbols 0 and 1.
i. Decimal number system iii. Binary number system
ii. Octal number system iv. Hexadecimal system
B. The decimal equivalent of binary number (1100110)2 is:
i. (102)10 iii. (103)10
ii. (104)10 iv. (105)10
C. The hexadecimal digits are 0 to 9 and A to:
i. E iii. F
ii. G iv. H
Learning Outcomes
DBMS is a software that stores data, processes them and provides information in an
organized way. A database management system (DBMS) is designed to manage a large
volume of information. It is a computerized system that stores data, processes them and
provides information in an organized form. Some of the popular DBMS softwares are
MS-Access, Oracle, FoxPro, SQL Server, My SQL, DBASE etc. Data management
involves both defining structures for storing information and providing mechanisms
for manipulating the information. Examples of the use of database systems are airline
reservation systems, company payroll, employee information systems, banking systems,
credit card processing systems, and sales and order.
Advantages of Database Systems
It reduces the data redundancy on the file. Redundant data are repeated and necessary data
exist on the file. So, we have to reduce it to save the memory of the computer.
Data stored on the DBMS are highly consistent. They are constant in nature.
It is possible to share data using DBMS. Various users are allowed to share data
according to their needs using the same database file.
It is possible to apply the centralized security system on DBMS.
It has a very high data integrity. We can retrieve data on complete form using
DBMS.
Disadvantages of Database Systems
High initial investment in hardware, software, and training.
Overhead for providing security, recovery, and integrity functions.
Cost for the hardware-upgrade to allow for the extensive programs and the workspaces
required for their execution and storage.
Cost for the maintenance of the software which remains forever.
An additional cost is required to transfer from a traditionally separate application
environment to an interpreted one.
High cost for backup and recovery.
Elements of Database
The core component of the database is a table. Database is the combination form of one
or more than one table. Tables are the basic blocks of database. A single table is used to
store data of a specific purpose or subject such as telephone directory, book records, etc.
Records
Data are stored in records. A record is composed of fields and contains all the data about
one particular person, company, or item in a database. Records appear as rows in the
database table. A record for S.N. 5 is given as below from the above table.
Book Name
Computer Science
Social Studies
Moral Science
Optional Mathematics
Nepali
Quantity Rate
10 100
Objects of MS-Access
In this view, you can add, edit and delete fields in a table. You can create as many fields
as required and select the data types for each field, add field description, set primary key
field and set field properties like data entry rules, validations, etc.
Click on Create Tab on menu.
Click on Table Design Button.
Set field SN to Primary Key (Not allowed to duplicate data for SN) by Right Click on
that field and choose Primary Key
Data Types
Data type is a field property that specifies and limits what kind of data can be entered
into that field. For example, values that are stored in a text field can contain only letters,
numbers, and a limited set of punctuation characters. After you enter the valid field name,
it allows a user to select the data type for the field. You can use the data type property to
specify the type of data stored in a table field such as text for name field, number for class
field, date and time for DOB field, etc. Each field can store data consisting of only a single
data type. The various data types are given below.
Maximum Default
Data
Description Data Field
Type
/ Space Size
Text It is used for text or combinations of text Up to 255 50 (2003
and numbers as well as numbers don’t Characters Version)
require calculations, such as phone num- 255
bers. (2007/10
Version)
Memo It is used for lengthy text and numbers. Up to 65,536 _
Characters
Number It is used for data to be included in 1,2,4 or 8 Long Integer
mathematical calculations. Bytes
Byte It stores numbers from 0 to 255 without 1 byte
decimals.
Integer It stores numbers from -32768 to +32768 2 bytes
without decimals.
Field Description
You can enter the description of each field in the description column. It helps you to
remember the use and purpose of a particular field. This is an optional part in a database.
It is displayed in the status bar when you select this field on a form.
The primary key uniquely identifies each record in the table. Primary key does not accept
null (0) value. It can either be a normal attribute that is guaranteed to be unique (such as
class roll number in a table with no more than one record per person). Primary keys may
consist of a single attribute or multiple attributes in combination. Primary key are used
for:
There are a number of ways to create a field as a primary key field. Some of them are,
Select the field to be used as a primary key and select the Primary key button.
Select the field to be used as a primary key and select the Primary key option from the
Edit menu.
Place the cursor on the field selection cell and right click on it, then you can click on
Primary Key option from the list.
Note: If we do not select any key as a primary key and try to save the table, by default
access creates an auto number field that can be used as the primary key.
Format It determines the way that the field appears when it is displayed or
printed in datasheets or in forms or reports that are bound to the
field. You can use any valid number format. In most cases, you
should set the format value to currency.
Decimal Places It specifies the number of decimal places to use when displaying
numbers.
Input Mask It displays editing characters to guide data entry. For example, an
input mask might display a dollar sign ($) at the beginning of the
field.
Caption It displays the label text that is displayed for this field by default in
forms, reports, and queries. If this property is empty, the name of
the field is used.
Default Value It automatically assigns the specified value to this field when a new
record is added.
Validation Rule It supplies an expression that must be true whenever you add or
change the value in this field. It is used in conjunction with the
validation text property.
Validation Text It displays when a value that is entered violates the expression in
the validation rule property.
Required It requires that data are entered in the field.
Setting Description/Example
General DateHere, if the value is date only, no time is displayed and if the value is
time only, no date is displayed. This setting is the combination of the
short date and long time. eg. 6/19/2012 (MM/DD/YYYY) and
7:34:23 PM (HH:MM:SS)
Long Date Long date setting, eg. Monday, August 25, 2012
Medium Date Medium date setting, eg. 26-Jun-07 (DD-MM-YY)
Short Date Short date setting, eg. 9/4/2012 (MM/DD-YYYY)
Long Time Long time setting, eg. 7:30:20 PM (HH:MM:SS)
Medium Time Medium time setting, eg. 7:30 PM (HH:MM)
Short Time Short time setting, eg. 17:34, 7:15 (HH:MM)
For Format String
Character Description/Function
0 Number is entered and required (0-9), no plus or minus sign.
9 Number is entered and optional (0-9), no plus or minus sign.
# Optional number or space, plus and minus sign is allowed.
L Letter is entered and required (A-Z).
? Letter is entered and optional (A-Z).
A Letter or number entered and required.
a Letter or number entered and optional.
& Any character or space required.
(Note: If you want to set primary key , press ‘Yes’ button or press ‘No’ button if you don’t
want to set primary key.)
To enter records on table:
Double click on the table name.
You will get a table that you have created with the name of fields.
Enter records on the table and press CTRL + S again to save it.
Next, for each field you add, you’ll want to check and change the assigned data type.
Select the first field.
Show the Data Tools Datasheet Contextual tab.
Check, and if necessary, change the Data Type and Format in the Data Type &
Formatting group
Repeat the steps as before.
Click the Save command on the Quick Access Toolbar.
Enter a table name.
Finally click on OK.
Adding Records in a Datasheet
Open datasheet, type the required data in the field.
Press Tab or Arrow to move to the next field. Or, simply place the mouse cursor in
the desired field.
While entering the data in a field next row for next record will be automatically
displayed. Repeat the above steps to enter the data in fields till it is required.
After finishing adding records in the datasheet, you can close the datasheet
simply by clicking on File tab and select Close option.
To remove the unwanted records from the datasheet, you can use this options. The contents
of cell can be deleted by selecting and pressing the delete button on keyboard.
To delete the record :
Position the cursor and select the record or records (rows) that you want to delete.
Select Delete record option that appears when you click the right button on mouse.
To delete the fields:
Position the cursor over the field name and select the field or fields (columns) that
you want to delete.
Select Delete Field option that appears when you click the right button on mouse.
Computer will ask for confirmation whether you want to delete or not.
Click on ‘Yes’ option to delete the records or fields.
Creating a Relationship
A primary feature of relational databases is that they contain multiple tables, each of
which can have a relationship with any of the other tables. Relationships are ties that are
created between tables in the database so that MS-Access can combine data from more
than one table to create reports. It is how tables determine how they correspond to each
other. To create a relationship, first we have to create the related tables as below.
Be sure to set a format and default value for the date created fields on both tables (you
shouldn’t need to enter this field - the system can do that). Now, to create the relationship
between all three tables we can do as below.
The Edit Relationships dialog will appear. Click Enforce Referential Integrity so that
it is checked. Check that the values are the same as the following screenshot and click
OK.
Types of Relationship
One-to-one relationship: For each record in one table, there is one and only one
matching record in a different table. It is as if two tables have the exact same primary
key. Typically, data from different tables in a one-to-one relationship will be combined
into one table.
One-to-many relationship: For each record in one table, there may be zero, one or
many records matching in a separate table. For example, you might have an invoice
header table related to an invoice detail table. The invoice header table has a primary
key, Invoice Number. The invoice detail table will use the invoice number for every
record representing a detail of that particular invoice. This is certainly the most
common type of relationship you will encounter.
Many-to-many relationship: This relationship cannot be defined in MS-Access without
the use of a mapping table. This relationship states that records in both tables can
have any number of matching records in the other table.
Query on Database
Queries are database objects that can be used to retrieve information from multiple tables
by joining these tables using common fields. Simply, queries are used to change, view,
and analyse the data. In MS-Access you can use queries to extract information (data)
from one (or more) tables (or from other queries). For example you can write a query
that returns all students that have a percentage that is less than 40. Besides limiting the
number of records with queries, you can also limit the number of columns (fields). For
example instead of returning all fields from the student table you can only select the
student ID, Student Name, Student percentage and Student email address.
Select Queries
Create a database and create a table in design view with the information such as
Student Roll , Name , Class, Math , Computer, English and Social then save the table.
Click on Create tab and select Query Design option.
Add the table and add the table field by double clicking over it.
Set the criteria as >90 under the computer field and save it.
Now, just click on the query, then you can see those records who have secured more
than 90 in computer.
Assignment
1. Choose the correct answer.
a. Access is used to develop
i. DBMS ii. software iii. Database iv. Word
b. What is the extension of Access database file?
i. DB ii . MDB iii. DBF iv. ADB
c. The name of caption can be declared upto
i. 2048 characters ii. 2063 characters
iii. 64,000 characters iv. 2005 characters
d. The logical data type of access is
i. Yes/no i. True/False iii. on/Off iv. All of the above
e. The OLE object can store graphics, sound upto….GB:
i. 1 ii. 2 iii.3 iv. 4
f. Which of the following is not a relational database?
i. dBase IV ii. FoxPro iii. Oracle i v. Reflex
g. Which of the following is a field property?
i. Indexed ii. Field Size iii. Caption iv. All
h. Integer needs ……..bytes space to store its values.
i. 8 ii. 2 iii. 3 iv. 4
i. Default field size of “Number” data type is:
i. Integer ii. Long Integer iii. Auto Number iv. Byte
j. Size of database are usually measured in term of:
i. Kilobyte ii. Terabyte iii. Megabyte iv. Gigabyte
Unit
Lesson 8 : Review on Qbasic Programming
Lesson 9 : Modular Programming in QBASIC
Practical Section on SUB Procedure
Practical Section on FUNCTION Procedure
Lesson 10 : File Handling in QBASIC
Practical Section on File Handling
Lesson 11 : Programming in C
Model Question Paper
List of Abbreviations
Lesson
Learning Outcomes
Features of QBASIC
Operators are the symbols that indicate the type of operation that has to be performed on
the data or on the values of variables. There are four types of operators in QBASIC. They
are Arithmetic Operators, Relational Operators, Logical Operators and String Operator.
Arithmetic Operators
Arithmetic Operators are used to perform mathematical calculations like addition,
subtraction, division, multiplication and exponential. The following table shows arithmetic
operators used in QBASIC.
QBASIC Statements
Branching Statement
Branching statement is a decision making statement. Depending upon the decision
branching statement can change the order of execution. Branching statements are divided
into two types.
Conditional Branching Statement
This statement allows the selective execution of statements based on a particular condition.
This statement directs the computer to another part of the program based on the results
Practical Assignment
CLS
INPUT “Enter first number “; A
INPUT “Enter second number “; B
INPUT “Enter third number “; C
IF A> AND A>C THEN
PRINT “The greatest number is”; A
IF B>A AND B>C THEN
Practical Assignment
CLS
INPUT “Enter your percentage “; P
IF P>= 80 THEN
Result$ = “Distinction”
ELSEIF p >= 60 THEN
Result$ = “First Division”
ELSEIF p >= 40 THEN
Result$ = “Second Division”
ELSEIF p >= 35 THEN
Result$ = “Third Division”
ELSE
Result$ = “Sorry! No result found”
END IF
Part Description
TEST CONDITION It is a numeric or string expression that evaluates whether
the statement is TRUE or FALSE.
Statements OF Loop It is a set of one or more QBASIC statements.
WHILE Statement It always checks the condition before it begins the loop.
LOOP It continues till the condition remains TRUE.
Practical Assignment
REM a program to print series from 1 to 10
CLS
C=1
WHILE C <= 10
PRINT C
C=c+1
WEND
END
Practical Assignment
REM a program to print the series from 1 to 10
CLS
c=1
DO WHILE c <= 10
PRINT c
c=c+1
LOOP
END
Practical Assignment
REM a program to print the series from 1 to 10.
CLS
C=1
DO UNTIL C = 11 This number will not be displayed.
PRINT C
C=C+1
LOOP
END
EXIT Statement
The EXIT statement is used to terminate the loop based on certain criteria before the
expected number of iterations. When the EXIT statement is executed, the control jumps
to next statement immediately after the loop. We can use the EXIT statement in all types
of loops.
Syntax: EXIT DO / FOR
Practical Assignment
CLS
X=1
DO
prod = x* 5
IF prod >50 THEN EXIT DO
PRINT prod
X=X
LOOP WHILE X<=10
END
Program 1
Write a program to input any three numbers and display its sum and average.
REM ‘to calculate sum and average of three numbers
CLS
INPUT “Enter first number”; A
INPUT “Enter second number”; B
INPUT “Entre third number”; C
SUM = A + B + C
AVG = (A + B + C) / 3
PRINT “The sum is”; SUM
PRINT “The average value is”; AVG
END
Program 2
Program 5
Program 6
Write a Qbasic program to find out the area of four walls of a room.
CLS
Input “Enter the height”;H
Input “Enter the length”; L
Input “Enter the Breadth”;B
Let AR= 2 * H * (L+B)
Print “The area of four walls =”;AR
End
Write a Qbasic program to enter any three numbers and calculate their sum and
average.
CLS
Input “Enter any number” ;A
Input “Enter any number” ;B
Input “Enter any number” ;C
Let Sum = A+B+C
Let Avg =Sum/3
Print “The sum=” ;Sum
Print “The Average is” ;Avg
End
Program 8
Write a Qbasic program to input student’s name, marks obtained in five different
subjects and find the total and average marks.
CLS
Input “Enter the name” ;N$
Input “Enter the marks in English” ;E
Input “Enter the marks in Computer” ;C
Input “Enter the marks in Maths” ;M
Input “Enter the marks in Science” ;S
Input “Enter the marks in Nepali” ;N
T=E+C+M+S+N
Let A=T/5
Print “The name of the student is” ;N$
Print “The total marks is” ;T
Print “The Average marks” ;A
End
Program 9
Write a Qbasic program to enter any number and check whether it is negative or
positive number.
CLS
Input “Enter the number”; N
Program 10
Write a Qbasic program to enter any number and find out whether it is even or odd
using the select case statement.
CLS
Input “Enter any number” ;N
Rem=N mod 2
Select case Rem
Case = 0
Print “The number is Even number”
Case Else
Print “The number is odd number”
End Select
End
Program 11
Program 12
Write a QBASIC program to enter any alphabet and test alphabet is ‘a’ or not using
the select case statement.
CLS
Input “Enter the alphabet”;A$
A$=UCase$ (A$)
Select Case A$
Case ‘A’
Print “It’s alphabet A”
Case Else
Print “It’s not alphabet A”
End Select
End
Program 13
Write a QBASIC program to generate the following series using For….Next…..
Loop.
1,3,5,7,9, 11, 13, 15………………...99
CLS
For I = 1 to 99 Step 2
Print I
Next I
End
Write a QBASIC program to print series as below using WHILE… WEND statement.
1,4,9,…upto 10th term.
CLS
I=1
While I < =10
Print I^2;
I=I+1
WEND
END
Program 16
Write a QBASIC program to read any 10 different numbers and find out the
greatest one among them.
CLS
READ G
FOR I = 2 to 10
READ N
IF N>G THEN G = N
DATA 19, 2, 56, 11, 76, 10, 22, 12, 55, 1
NEXT I
PRINT “The greatest Number is:”; G
END
Program 18
Write a QBASIC program to check whether the entered number is palindromic or
not.
CLS
INPUT “ENTER ANY NUMBER”; N
A=N
S=0
WHILE N <> 0
R = N MOD 10
S = S * 10 + R
N = N \ 10
WEND
IF A = S THEN
PRINT A; “This is a palindromic number.”
ELSE
PRINT A; “This is not a palindromic number.”
END IF
END
Program 22
Write a QBASIC program to check whether the entered number is Armstrong or
not.
CLS
INPUT “ENTER ANY NUMBER”; N
A=N
S=0
WHILE N <> 0
R = N MOD 10
S=S+R^3
N = N \ 10
WEND
IF A = S THEN
PRINT A; “It is an ARMSTRONG number.”
ELSE
PRINT A; “It is not an ARMSTRONG number.”
END IF
END
Program 24
Innovative Task
Prepare a chart paper including various QBASIC statements with their syntax and
submit to your teacher.
b. CLS
INPUT “Enter your choice (1 – 3)”; N
SELECT CASE Z
CASE 1
PRINT “Baishak”
CASE 2
PRINT “Jestha”
CASE 5
PRINT “Ashad”
d. CLS
c. CLS
FOR I = 1 TO 6
I=1
LOCATE I, 50 - I
While I < =10
FOR J = 1 TO I * 2 - 1
Print I^2;
PRINT USING “#”; I;
I = I + 1
NEXT
WEND
PRINT
END
NEXT
END
Learning Outcomes
Modular programming can be used to break up a large program into small units,
or to create code that can be easily reused. A modular program consists of a main module
and one or more auxiliary modules. Each module originates from a separate source
code file. The main module is compiled as an EXE, and calls functions in the auxiliary
modules. Modular programming is a technique or method which is used to divide
a program into many small, logical and functional modules or blocks. In a QBASIC
program module is a block of statements that is used to solve a particular problem. The
following are the advantages of using modular programming. When a program becomes
too large then it becomes difficult to write and debug the program. Thus, modular
programming helps a programmer to write and debug easily.
Different programmers can design different program modules independently.
It is easy to code the program and testing is very easy.
A module can be used in multiple places, which reduces the program codes.
Debugging of the program is easier and faster because they are divided into different
modules.
It is possible to use a single module in different places which reduces program codes.
A modular programming has two parts of modules they are main module and sub module.
Main Module: This module contains the entry point and the ending point of the program.
The top-level module which is located at the top of all procedures such as SUB-Procedures
or FUNCTION is called main-module. Procedure names and parameters are declared and
called from the main-module.
Sub Module: Sub module is a program which is written under the main module. A
program may have one or more sub modules under the main module. A sub-module may
have other sub-modules. It is also called a procedure. It is an isolated part of modular
program used for specific purposes. Sub module is controlled by the main module.
Main
Module
Sub procedure is a method to divide a large program into small programs. It is a small,
logical and manageable and functional part of a program that performs specific tasks and
does not return a value to the calling module. A sub procedure is needed to be declared
before it is used in a program. A CALL statement is used to call the sub procedure in a
program. It is written with SUB....END SUB statement. It has three parts, the first one
is the declaration part where we declare sub procedure, the second part is the main part
from where sub part is called and the third part is SUB part where we define our specific
tasks to do.
Features of sub procedure
Sub procedure does not return any value.
It does not have data type.
It always starts with the key word, SUB and ends with the keyword END SUB.
The parameters can be passed either by reference or by value.
To understand these 3 parts, look at the following example.
Example 1
DECLARE SUB SUM
CLS
CALL SUM
END
SUB SUM
Input “Enter the first number”; A
Input “Enter the second number”; B
S= A+B
Print “The sum is:” ; S
END SUB
In the above program we declared the sub procedure by using DECLARE keyword and
statements between CLS and END part. It is the main part where code runs and control
flow transfers to sub part by CALL keyword followed by sub name as a result the sub
part gets executed and we see output like (Enter the first number, ....). Again, when
SUB part ends then the control flow goes to the main part where we find END statement.
Finally, program is terminated. Let’s see another example of sub procedure. We can pass
value in sub procedure from the main part of the program by using parameters.
Let’s Review
Modular programming is a technique or method which is used to divide a
program into many small, logical and functional modules or blocks.
In a QBASIC program module is a block of statement that is used to solve a particular
problem.
A modular programming has two parts of modules. They are main module and sub
module.
The top-level module which is located at the top of all procedures such as
SUB-Procedures or FUNCTION is called the main-module.
Procedure names and parameters are declared and called from the main-module.
A sub module is a program which is written under the main module.
A procedure is a small, logical and manageable functional part of a program.
There are two types of procedures. They are sub procedure and function
procedure.
A CALL statement is used to call the sub procedure in a program.
SUB SUM
INPUT “Enter the first number”; A
INPUT “Enter the second number”; B defining sub procedure
INPUT “Enter the third number”; C
When a procedure is called from the main module, data or variables need to supply to the
procedure where they are needed to use. The arguments are the parameters that pass to
the procedure. The argument is also known as actual parameter and the parameter is also
known as formal parameter. The calling procedure can pass arguments to the procedure
in two ways. They are passing arguments by value and passing arguments by reference.
Passing Arguments by Value
When arguments are passed by value, it does not make any effect to the value of the
variables which are passed to a procedure as they are changed in the procedure. This
method is useful when we have to pass the same value to more than one procedure without
changing the values of the original variables in the calling program.
Example 4
DECLARE SUB SUM (A, B)
CLS
CALL SUM (50, 60)
END
Scope of Variables
This variable type determines the size and layout of the variable’s memory. It also
determines the range of values which need to be stored inside that memory and nature
of operations that can be applied to that variable. Variable is an element of QBASIC
programming. A variable is a quantity whose value changes during the execution of a
program. It is a named location in the memory that is used to store a value during a
program execution. There are two categories of a variable. They are local variable and
global variable which we are going to discuss below.
Local Variable
A variable which is declared inside a module and cannot be accessed by other modules
is known as local variable. The value of local variable destroys when the program flows
out of procedures. The local variable can be used within the module where it is defined.
Local variable is the variable declared and used inside the procedure by default. Let’s
study the given program.
Function procedure is a block of statement that performs specific task and return a value
whenever it is called. It is a small, logical and manageable functional part of a program
which performs specific tasks and returns single value to the main program or calling
module. It has three parts, first one is declaration part where we declare FUNCTION
procedure, second one is main part, from where FUNCTION procedure is called and
last one is FUNCTION part where we define our specific task to do. The syntax of this
procedure is given below.
Syntax:
DECLARE FUNCTION NAME [Parameter list]
[List of statements]
Function Name = Expression
[Statements…….]
END FUNCTION
In the above program, we declared the FUNTION procedure by using DECLARE keyword
and statements between CLS and END part. It is the main part where code runs and when
interpreter reads fifth line, flow of program jumps to the FUNCTION procedure. Inside
the function procedure, it calculates the area and returns the value in the main module.
After that it prints the area and when it reads END statements it terminates the program.
Difference between function procedure and sub procedure
Program 1 Program 2
Write a program to enter any two numbers Write a program to enter any two numbers
and display its sum. and display its difference.
DECLARE SUB SUM (A, B) DECLARE SUB DIFF (A, B)
CLS CLS
INPUT “ENTER FIRST NUMBER”; A INPUT “ENTER FIRST NUMBER”; A
INPUT “ENTER SECOND NUMBER”; B
INPUT “ENTER SECOND NUMBER”; B
CALL DIFF (A, B)
CALL SUM(A, B)
END
END SUB DIFF (A, B)
SUB SUM (A, B) D=A-B
S=A+B PRINT “DIFFERENCE”; D
PRINT “SUM OF TWO NUMBERS”; S END SUB
END SUB
Program 3 Program 4
Write a program to enter any two Write a program to find the area of four
numbers and display their average. walls.
DECLARE SUB AVERAGE (A, B) DECLARE SUB AREA (L,B,H)
CLS CLS
INPUT “ENTER FIRST NUMBER”; A INPUT “ENTER LENGTH” ; L
INPUT “ENTER SECOND NUMBER”; B INPUT “ENTER BREADTH” ; B
CALL AVERAGE (A, B)
INPUT “ENTER HEIGHT” ; H
END
CALL AREA (L,B,H)
SUB AVERAGE (A, B)
END
AVG = (A + B) / 2
SUB AREA (L,B,H)
PRINT “AVERAGE OF TWO NUM”; AVG
A=2*H*(L+B)
END SUB
PRINT “AREA IS”; A
END SUB
Program 7 Program 8
Write a program to calculate the area of a Write a program to convert Nepalese
rectangle. currency into Indian Currency.
DECLARE SUB AREA (L, B) DECLARE SUB CON(N)
CLS CLS
INPUT “ENTER LENGTH”; L INPUT “ENTER NC ” ; P
INPUT “ENTER BREADTH”; B CALL CON(P)
CALL AREA(L, B) END
END SUB CON(P)
SUB AREA (L, B)
C=P/1.6
A=L*B
PRINT “INDIAN CURRENCY ”; C
PRINT “AREA OF RECTANGLE ”; A
END SUB
END SUB
CLS CLS
Program 11 Program 12
Write a program to calculate the area and Write a program to calculate the area and
perimeter of a rectangle. perimeter of a square.
DECLARE SUB AREA (L, B)
DECLARE SUB AREA (L)
DECLARE SUB PERIMETER (L, B)
DECLARE SUB PERIMETER (L)
CLS
CLS
INPUT “ENTER LENGTH”; L
INPUT “ENTER BREADTH”; B INPUT “ENTER LENGTH”; L
CALL AREA (L, B) CALL AREA (L)
CALL PERIMETER(L, B) CALL PERIMETER(L)
END END
SUB AREA (L, B) SUB AREA (L)
A=L*B A=L^2
PRINT “AREA OF RECTANGLE ”; A PRINT “AREA OF SQUARE”; A
END SUB END SUB
SUB PERIMETER (L, B) SUB PERIMETER (L)
P = 2 * (L + B) P=4*L
PRINT “PERIMETER OF RECT ”; P PRINT “PERIMETER OF SQUARE ”; P
END SUB END SUB
Program 15 Program 16
Write a program that accepts three different
Write a program to check whether the
numbers and display the smallest number.
given number is positive or negative.
DECLARE SUB SMALL(A,B,C)
CLS DECLARE SUB TEST(N)
INPUT “ENTER FIRST NUBER” ; A CLS
INPUT “ENTER SECOND NUMBER” ; B INPUT “Enter a number”; N
INPUT “ENTER THIRD NUMBER” ; C CALL TEST(N)
CALL SMALL(A,B,C)
END
END
SUB SMALL(A,B,C) SUB TEST(N)
IF A<B AND B<C THEN IF N>0 THEN
PRINT “THE SMALLEST NUMBER IS” ; A PRINT N; “It is positive number.”
ELSE IF B<A AND A<C THEN ELSE
PRINT “THE SMALLEST NUMBER IS” ; B
PRINT N; “It is negative number”
ELSE
PRINT “THE SMALLEST NUMBER IS” ; C END IF
END SUB END SUB
Program 19 Program 20
Write a program to reverse the given Write a program to display 2 3 5 8 12
string. ……upto 10th term.
CLS DECLARE SUB series ()
INPUT “ENTER A WORD” ; W$ CLS
CALL REV(W$) CALL series
END
END
SUB series
SUB REV(N$)
I=2
FOR I = LEN(N$) TO 1 STEP-1 FOR J = 1 TO 10
C$=C$+MID$(N$,I,1) PRINT I;
NEXT I I=I+J
PRINT “REVERSED STRING IS” ; C$ NEXT J
END SUB END SUB
Program 23 Program 24
Write a program to display the series as 2 Write a program to display reverse of
22 222 2222 22222 . input-string.
DECLARE SUB series () DECLARE SUB REV(A$)
CLS CLS
CALL series INPUT “ENTER ANY STRING”;A$
END CALL REV(A$)
SUB series END
I=2 SUB REV(A$)
FOR I= LEN(A$) TO 1 STEP -1
FOR J = 1 TO 5
B$=MID$(A$,I,1)
PRINT I;
W$=W$+B$
I = I * 10 + 2
NEXT I
NEXT J
PRINT “REVERSED STRING=”W$
END SUB END SUB
Program 27 Program 28
Write a program to display the series in the
given pattern. Write a program to display the series as 3
1 12 27 48 upto 10th terms.
121 DECLARE SUB series ()
12321
1234321 CLS
123454321 CALL series
12345654321
END
DECLARE SUB series ()
CLS SUB series
CALL series I=3
END
SUB series FOR j = 1 TO 10
FOR I# = 1 TO 6 PRINT I * j ^ 2;
A# = A# * 10 + 1
NEXT j
PRINT A# ^ 2
NEXT END SUB
END SUB
Program 31 Program 32
Write a program to check whether a
Write a program to display the series as supplied number is perfect square or
3 12 27 48 upto 10th terms. not.
DECLARE SUB series () DECLARE SUB PSQR(N)
CLS CLS
INPUT “ENTER A NUMBER” ; N
CALL series CALL PSQR(N)
END END
SUB series SUB PSQR(N)
S=SQR(N)
I=3
IF S = INT(S) THEN
FOR j = 1 TO 10 PRINT “it is perfect square”
PRINT I * j ^ 2; ELSE
PRINT “it is not perfect square”
NEXT j
ENDIF
END SUB END SUB
Tips: Consider a number; if it is exactly divisible by 2 then write the quotient for the
next number. If it is not exactly divisible by 2 then multiply the number by 3 and add
1 which will be the next number. Repeat the same process for the second and so on.
Here, first number itself is 7.
7
2 = 3×7+1 = 11
22
2 = 11
22
2 = 11×3+1 = 34
34
2 = 17
17
2 = 17×3+1 = 52, So on.
j. 1 k. 3 l. 5
12 33 54
123 333 543
1234 3333 5432
12345 33333 5432
p. 30 q. 2 4 6 8 10
4 6 8 10
28 30 6 8 10
26 28 30 8 10
10
24 26 28 30
22 24 26 28 30
4. Write down the output of the given program.
a. DECLARE SUB OUTP () b. DECLARE SUB OUTP ()
CLS CLS
CALL OUTP CALL OUTP
END END
SUB OUTP SUB OUTP
A=1 W$ = “DHADING”
B=1 FOR I = 1 TO LEN(W$) STEP 1
DO PRINT LEFT$(W$, I)
PRINT A; NEXT
IF B MOD 3 = 0 THEN PRINT END SUB
B=B+1
A=A+1
LOOP UNTIL B > 9
END SUB
Program 1
Write a program to calculate the average of three numbers.
DECLARE FUNCTION AVGE (A, B, C)
CLS
INPUT “ENTER FIRST NUMBER”; A
INPUT “ENTER SECOND NUMBER”; B
INPUT “ENTER THIRD NUMBER”; C
AV = AVGE(A, B, C)
PRINT “AVERAGE OF THREE NUMBERS”; AV
END
FUNCTION AVERAGE (A, B, C)
AVGR = (A + B + C) / 3
AVERAGE = AVGR
END FUNCTION
Program 2
Write a program to find the area of four walls.
DECLARE FUNCTION AREA(L,B,H)
CLS
INPUT “ENTER LENGTH” ; L
INPUT “ENTER BREADTH” ; B
INPUT “ENTER HEIGHT” ; H
PRINT “THE AREA OF FOUR WALLS= ” ; AREA(L,B,H)
END
FUNCTION AREA(L,B,H)
AREA=2*H*(L+B)
END FUNCTION
Program 3
Write a program to calculate the circumference of a circle.
DECLARE FUNCTION CIR(A)
CLS
Program 4
Write a program to calculate the simple interest.
DECLARE FUNCTION SI(P,T,R)
CLS
INPUT “ENTER PRINCIPLE” ; P
INPUT “ENTER TIME” ; T
INPUT “ENTER RATE” ; R
PRINT “SIMPLE INTEREST IS = ” ;SI(P,T,R)
END
FUNCTION SI(P,T,R)
SI=(P*T*R)/100
END FUNCTION
Program 5
Write a program to convert the Nepalese currency into Indian currency.
DECLARE FUNCTION Convert (N)
CLS
INPUT “Enter NC”; p
PRINT “IC”; Convert(p)
END
FUNCTION Convert (p)
conv = p / 1.6
Convert = conv
END FUNCTION
Program 8
Write a program to calculate the volume of a cylinder using [Hint: PI*R^2*H]
DECLARE FUNCTION VOL(R,H)
CLS
CONST PI=3.14
Program 9
Write a program to display the greater number among any two numbers.
DECLARE FUNCTION GREAT(A,B)
CLS
INPUT “Enter any two number”; A,B
PRINT “The greater number is”; GREAT(A,B)
END
FUNCTION GREAT(A,B)
IF A>B THEN
GREAT= A
ELSE
GREAT=B
END IF
END FUNCTION
Program 10
Write a program to check whether an input number is even or odd.
DECLARE FUNCTION CONV$(N)
CLS
INPUT “ENTER A NUMBER ” ; P
PRINT CONV$(P)
END
FUNCTION CONV$(P)
IF P MOD 2 = 0 THEN
CONV$= “EVEN NUMBER”
Program 11
Write a program that asks any three numbers and displays the difference between the
greatest and the smallest among the three numbers.
DECLARE FUNCTION DIF(A,B,C)
CLS
INPUT “Enter three numbers”; A, B, C
PRINT “THE DIFFERENCE=”; DIF(A, B, C)
END
FUNCTION DIF (A, B, C)
G=0
S=0
IF A > B AND A > B THEN
G=A
ELSEIF B > A AND B > C THEN
G=B
ELSE
G=C
END IF
IF A < B AND A < C THEN
S=A
ELSEIF B < A AND B < C THEN
S=B
ELSE
S=C
END IF
DIF = G – S
END FUNCTION
Innovative Task
Assignment
1. Write a FUNCTION program for the following questions.
a. Write a program to display the product of any three numbers.
b. Write a program to read the length, breadth and height of a box. Calculate its volume
and surface area.
c. Write a program to calculate the average of three numbers.
d. Write a program to get temperature in Celsius from the user and then print the
temperature in Fahrenheit. (Hint: F=9C/5+32).
e. Write a program to get a word from the user and then print it in reverse order.
f. Write a program to input a string and count the total number of consonants.
g. Write a program to get radius of the circle and display the area.
h. Write a program to display the factorial of a given number.
i. Write a program to display the greater number among any two numbers.
NEXT P=3.14
END CIR=2*PI*A
xyz$ = c$
END FUNCTION
Learning Outcomes
File is a collection data or information. Almost all information stored in a computer must
be in a file. In our daily life, we create different types of files such as paint file, word pad
file, excel file, text file, etc. We also save our QBASIC programs with .BAS file extension
that is also a type of file. So, we can say that everything in computer is stored in a file. File
handling is a process to create data file, write data to the data file and read data from it. It
is simply a writing program and storing information in files for future use which helps in
managing data and working with data, we can search data from files, delete it, and so on.
The file of the computer can be categorized into two types which are explained below.
Program File
Program file is a set of instructions written in a computer language for data processing
under unique file name. Program files are associated with providing access and execution
of a program on the computer system. A program file extension is added to a file name by
the program itself. It contains instructions which are used to manipulate data and display
the output. The program files extension of Qbasic is .BAS is extension.
Data File
Data file are a collection of data such as name, address, phone, etc. that are required for
data processing. In data file, related data are stored in a row known as a record. Data file
are stored separately from the program file. It provides data to the program files. Data
files are linked to a program file during the execution. Let’s discuss some advantages of
data files.
Types of Files
OPEN statement: This statement is used to open sequential data file for writing data to the
data file or reading data from the data file using Output, Input, or Append mode.
Syntax: OPEN “FILENAME.DAT” FOR <MODE> AS #FILE NUMBER
WRITE # statement: This statement is used to send or store one or more data items to
the specified file using either output or append mode. It inserts commas between the data
items and it encloses strings in double quotation marks.
Syntax: WRITE # File number, Variable list
PRINT # statement: This statement is used to add spaces between data items while storing
data and it does not enclose strings in double quotation marks.
The purpose of opening data files is called file mode. The Common modes of opening
data files are listed below.
OUTPUT: In file handling this mode is used to create a new sequential file and writes data
into it. It starts writing data always from the beginning of the file.
Syntax: OPEN “filename” FOR file mode AS # file number
Where, file name refers to the name of file that is to open, file mode refers to output,
input or append modes of opening file, file number refers to a reference number to the file
opened.
Example: OPEN “file.dat” FOR OUTPUT AS #2orOPEN “O”, #2, “file.dat”
It opens the file file.dat file in output mode the file is referenced to as file number #2. Here,
the user creates a new file file.dat for the purpose of writing data into the file.
INPUT: In file handling this mode is used to read / display data from the existing data
files.
Example: OPEN “file.dat” FOR INPUT AS #2 or OPEN “I”, #2, “file.dat”
APPEND: In file handling this mode is used to add more records in the existing data file.
It starts adding data after the last record of the previous file.
Example: OPEN “file.dat” FOR APPEND AS #2 or OPEN “A”, #2, “file.dat”
Creating a file has three stages that we are going to discussed below.
a. Creating a file for output by using a statement such as:
Open “file.dat” FOR OUTPUT AS #1
b. Store the data
This is typically achieved by accepting input from the keyboard and then writing it to
the file using a WRITE#1 statement. The statements that are written to the file must include
the correct channel number. An example of how to store a single record is included
below.
INPUT “Enter the name”; Name$
INPUT “Enter the address” Add$
Example 1
Write a program to store only one record of an employee including his / her employee ID,
name, post and department in data file EMP.DAT
OPEN “EMP.DAT” FOR OUTPUT AS #1
CLS
INPUT “ENTER ID”;I
INPUT “ENTER NAME”; N$
INPUT “ENTER POST”; P$
INPUT “ENTER DEPARTMENT”;D$
WRITE #1,I, N$, P$, D$
CLOSE #1
Example 2
Write a program to store the records of employee including their Employee ID, name,
post and department in a data file EMP.DAT
OPEN “EMP.DAT” FOR OUTPUT AS #2
TOP:
CLS
INPUT “ENTER ID”;I
INPUT “ENTER NAME”; N$
INPUT “ENTER POST”; P$
INPUT “ENTER DEPARTMENT”;D$
Data read from a sequential file is read in order starting from the beginning of the file. You
should make sure that the statement read the file, read the fields in the same order, they
were written to the file and you stopped reading when the end of file reached. Reading a
sequential file consists of the following three stages.
a. Open the file for reading
OPEN “file.dat” FOR INPUT AS#1
b. Read records from the file
INPUT #1, Name$, Add$, T = Will read an entire records and store the results in
string variables.
PRINT “Name:” Name$ = Print out values to screen in an appropriate format.
PRINT “Address”; Add$
PRINT “Telephone Number”; T
Example 1
Write a program to display all the records of data file “STUDENT.DAT”.
CLS
OPEN “STUDENT.DAT” FOR INPUT AS #1
DO WHILE NOT EOF(1)
INPUT #1, N$,R,C,S
PRINT “NAME”,“ROLL NO”,“CLASS”,“SECTION”
PRINT N$,R,C,S
LOOP
CLOSE #1
END
Example 2
Write a program to display those records whose salary is greater than 15000 from the data
file “STAFF.DAT”.
OPEN “STAFF.DAT” FOR INPUT AS #1
DO WHILE NOT (EOF)
INPUT #1,N$,ADD$,A,S
IF S>=15000 THEN
PRINT N$,ADD$,A,S
ENDIF
LOOP
CLOSE #1
END
Sometimes, we need to go back to a file and add records to the end of it. This is done in a
similar manner to creating a file and adding records. But in this case the file is opened in
a different mode.
OPEN filename FOR APPEND AS #n
Here, the APPEND keyword indicates that any output is going to the end; rather than the
beginning of a file. In #n, n indicates the file number.
Appending records to the end of file consist of the following stages.
a. Open the file
OPEN “file.dat” FOR APPEND AS #1
b. Writing records to the file
INPUT “Enter the name”; N$
INPUT “Enter the address”; Add$
INPUT “Enter telephone number”; T
WRITE #1, N$, Add$, T
c. Closing the file when you have finished
CLOSE #1
Example
A sequential data file “STUDENT.DAT” contains few records under the fields name, roll
no and marks for three subjects. WAP to add few more records into the same data file.
OPEN “STUDENT.DAT” FOR APPEND AS #1
TOP :
CLS
INPUT “ENTER ROLL NUMBER”;RN
INPUT “ENTER NAME”; N$
INPUT “ENTER MARKS OF ANY THREE SUBJECTS”;X,Y,Z
WRITE #1,RN,N$,X,Y,Z
INPUT “DO YOU WANT TO CONTINUE?”;CH$
IF UCASE$(CH$) = “Y” THEN GOTO TOP
CLOSE #1
END
If you are interested in certain records, you have to start at the beginning of the file and
read a record at a time in order. You can read the file of a record at a time and only print
out those records which meet your requirements.
Example 1
WAP to search record according to the supplied name from the data file “RESULT.DAT”
where fields are student’s name, class and marks secured in three subjects.
OPEN “RESULT.DAT” FOR INPUT AS #1
TOP:
CLS
FLAG = 0
INPUT “ENTER NAME TO SEARCH”;S$
WHILE NOT EOF(1)
INPUT #1,N$,C,X,Y,Z
IF UCASE$(S$)=UCASE$(N$) THEN
FLAG =1
PRINT N$,C,X,Y,Z
END IF
WEND
IF FLAG = 0 THEN PRINT “DATA NOT FOUND”
INPUT “DO YOU WANT TO RETRY?”; CH$
IF UCASE$(CH$)= “Y” THEN GOTO TOP
CLOSE #1
END
Program 1
Write a program to create a sequential data file “RESULT.DAT” to store name, address
and marks obtained in 3 different subjects of students.
OPEN “RESULT.DAT” FOR OUTPUT AS #1
DO
CLS
INPUT “Enter name”; N$
INPUT “Enter address”; A$
INPUT “Enter marks in three different subjects”; M1, M2, M3
WRITE #1, N$, A$, M1, M2, M3
INPUT “Do you want to continue(Y/N)”;CH$
LOOP WHILE UCASE$(CH$)=“Y”
CLOSE #1
END
Program 2
Create a sequential data file “std.dat” to store name and marks obtained in English, Maths
and Science for a few students.
OPEN “STD.DAT” FOR OUTPUT AS #1
DO
CLS
INPUT “Enter name”; N$
INPUT “Enter marks in English”; E
INPUT “Enter marks in Maths”; M
INPUT “Enter marks in Science”; S
WRITE #1, N$, E, M, S
INPUT “Do you want to continue(Y/N)”; CH$
LOOP WHILE UCASE$(CH$) =“Y”
CLOSE #1
END
Program 4
Create a sequential data file “HOTEL.DAT” to store customer’s name, address, and phone
number. Program should terminate with the user’s choice.
OPEN “HOTEL.DAT” FOR OUTPUT AS #1
DO
CLS
INPUT “Enter customers name”; CN$
INPUT “Enter address”; A$
INPUT “Enter phone number”; P#
WRITE #1, CN$, A$, P#
INPUT “Do you want to continue(Y/N)”; CH$
LOOP WHILE UCASE$(CH$) = “Y”
CLOSE #1
END
Program 6
Create a sequential data file “Price.dat” to store item name, quantity and rate. Also
calculate the total amount. Program should terminate according to the user’s choice.
OPEN “PRICE.DAT” FOR OUTPUT AS #1
DO
CLS
INPUT “Enter item name”; N$
INPUT “Enter quantity”; Q
INPUT “Enter rate”; R
T= Q*R
WRITE #1, N$, Q, R
INPUT “Do you want to continue(Y/N)”;CH$
LOOP WHILE UCASE$(CH$)=“Y”
CLOSE #1
END
Program 11
Write a program to display all records having salary less than 2500 from the data file
“ADD.INF” having the field’s name, post and salary.
OPEN “ADD.INF” FOR INPUT AS #1
CLS
WHILE NOT EOF(1)
INPUT #1, N$, P$, S
IF S<2500 THEN PRINT N$, P$, S
WEND
CLOSE #1
END
Program 13
Write a program to open a data file “STUDENT.DAT” that contains name, address,
telephone number and parent’s name of some students. Now display all those records
whose address is “LALITPUR”.
OPEN “STUDENT.DAT” FOR INPUT AS #1
CLS
WHILE NOT EOF(1)
INPUT #1, N$, A$, T#, PN$
IF UCASE$(A$) =“LALITPUR” THEN PRINT N$, A$, T#, PN$
WEND
CLOSE #1
END
Innovative Task
Write any five file handling programming in A4 size paper and submit to your
teacher as your project work.
11 Programming in C
Learning Outcomes
Structured Programming
Features of C Programming
C programming is a simple language in the sense that it provides a structured approach,
library functions, data types, etc.
It is a machine independent language so it can be executed on different machines with
some machine specific changes.
It is a structured programming language.
It has lots of inbuilt functions that make the development fast.
It supports the feature of dynamic memory allocation.
It provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
In C, we can call the function within the function. It provides code reusability for
every function.
Elements of C Programming
C Character Set
C programming uses the uppercase English alphabets A to Z, the lowercase letters a to z,
the numeric digits 0 to 9, and certain special characters such as !, * , +, - , % , <, > , & , [
], { }, ; , ?, @, “ “, ^ , #, !#, etc.
Constants
Constants are those values which never change during the execution of the program. There
are various constants in C programming. Some of the constants are explained below.
Character constant: Character constant is always enclosed in single quotes such as ‘A’. It
indicates only one character such as char = ‘B’
Integer constant: A normal integer constant is written as 5647. It includes both positive
and negative numbers such as int num = 150, int num = -140.
Long integer constant: A long integer is recognized by the presence of L (uppercase or
lowercase) at the end of the constant, for example: 2748723L.
Floating point constants: A floating point constant contains a decimal point (555.102)
or an exponent (1e-2) or both. Their type is double unless suffixed. The suffix of f or F
indicates float; 1 or L indicates long double.
String constant: It is a sequence of characters which is written in pair of double quotes
(“ “). It is declared as array of characters. A string constant may consist of any combination
of digits, letters, escaped sequences and spaces. It also includes numbers but such numbers
cannot be used for mathematical calculations. Some examples of string constants are char
name = “Divyansh”, char age = “15”, etc.
Variables
A variable defines a location name where we can put value and we can use these values
whenever required in the program. Variable is a name or identifier which indicates some
physical address in the memory, where data will be stored in the form of the bits of string.
The value of a variable can be changed at different times of executions and it may be
chosen by the programmer.
Rules for naming variable:
Variable name must begin with letter or underscore.
Variables are case sensitive.
Variables name can be constructed with digits, letters.
Special symbols are not allowed other than underscore.
C keywords are not allowed to use.
Statements
A statement is a command given to the computer that instructs the computer to take
a specific action, like display message on the console, performing the mathematical
operation and so on. In C program, collection of statements and each statement must be
terminated with a semicolon (;).
Operators Example/Description
> x > y (x is greater than y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
Logical Operators
These operators are used to perform logical operations on the given two variables. There
are three logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).
Operators Example/Description
&& (logical AND) (x>5)&&(y<5)
It returns true when both conditions are true.
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the conditions is true.
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it
false.
Bit wise Operators
These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT),
Operators Description
It is an increment operator which increases the value of operand.
++
Such as num = x ++ , num = ++ x.
It is a decrement operator which decreases the value of operand.
--
Such as num = x -- , num = -- x.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Special Operators
Below are some of the special operators that the C programming language offers.
Operators Description
& This is used to get the address of the variable.
There are few basic data types in C. They are listed in the table below:
C programming has various library functions for data input and output, such as getchar,
putchar, scanf, printf, gets and puts. All these built-in functions are present in C header
files. These functions enable the transfer of data between the C program and standard
input/output devices. Input function means to provide the program with some data to be
used in the program and output function means to display data on screen or write the data
to a printer or a file.
The printf function is used to output data onto the standard output device. In general, the
printf function is written as
where the <control string> refers to a string containing required formatting information
as in scanf, and arg1, arg2, ..., argn are individual data variables whose values are to
be printed. However, unlike scanf, these data variable names are not preceded by the &
symbol. This is because printf is expected to only output the values of these variables and
not their addresses.
getchar()
This is a single character input function. getchar() reads a single character from the
standard input data stream. When you input a single character for the C program to read,
you must indicate end of data stream or end of input by pressing the return/enter key after
entering your response character.
putchar()
This is a single character output function. putchar() writes a single character to the standard
output data stream. The file associated with the standard output device, is normally the
console.
The standard library function gets accepts input in the form of a string. The character
string may even include white space characters. Each call to gets will read all the
characters from the input steam until an end of line character is encountered. The end of
line character is represented as \n and gets generated when you press the enter key. gets
assigns the read string to the variable that is passed as its parameters. gets assigns NULL
when an error occurs.
clrscr() function
The clrscr() function is used to clear the screen and move cursor to upper left hand corner
of screen. It can be used anywhere in the program. It is better to use before the declaration
part.
A header file is a file having an extension .h which contains C function declarations macro
definitions. It holds the definitions of various functions and their associated variables
that need to be imported into your C program with the help of pre-processor #include
statement. The default header file that comes with the C compiler is the stdio.h. Including
a header file means that using the content of header file in your source program. The basic
syntax of using these header files is given below.
Syntax: #include <file>
Some common header files included in C programming are listed below.
#include<stdio.h>: This standard input-output header file is used to perform input and
output operations in C such as scanf() and printf().
#include<string.h>: This string header file is used to perform string manipulation
operations like strlen and strcpy.
#include<conio.h>: The console input-output header file is used to perform console
input and console output operations like clrscr() to clear the screen and getch() to get the
character from the keyboard.
#include<stdlib.h>: The standard library header file is used to perform standard utility
functions like dynamic memory allocation, using functions such as malloc() and calloc().
#include<math.h>: The math header file is used to perform mathematical operations like
sqrt() and pow(). To obtain the square root and the power of a number respectively.
#include<ctype.h>: The character type header file is used to perform character type
functions like isaplha() and isdigit(). To find whether the given character is an alphabet
or a digit respectively.
#include<time.h>: The time header file is used to perform functions related to date
and time like setdate() and getdate(). To modify the system date and get the CPU time
respectively.
#include<graphics.h>: This header file provides access to a simple graphics library that
makes it possible to draw lines, rectangles, ovals, arcs, polygons, images, and strings on
a graphical window.
Example 1
Write a program to Display “ Shubharambha Publication Pvt. Ltd. “
#include <stdio.h>
int main()
{
printf(“Shubharambha Publication Pvt.Ltd”);
return 0;
}
Output
Shubharambha Publication Pvt.Ltd
Example 2
Write a program to add any two integers.
#include <stdio.h>
int main()
{
int firstNumber, secondNumber, sum;
printf(“Enter two integers: “);
scanf(“%d %d”, &firstNumber, &secondNumber);
Output
Enter two integers: 20 10
20 + 10 = 30
In this program, the user is asked to enter two integers. Two integers entered by the user
is stored in variables firstNumber and secondNumber respectively. This is done using
scanf() function. Then, variables firstNumber and secondNumber are added using +
operator and the result is stored in sum.
Finally, the sum is displayed on the screen using printf() function.
Example 3
Write a program to input temperature in Celsius and display the temperature in Fahrenheit.
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
printf(“Enter the temperature in celcius :”);
scanf(“%f”, &celsius);
fahrenheit = 9.0 / 5 * celsius + 32;
printf(“Temperature in fahrenheit : %0.2f”, fahrenheit); r
eturn 0;
}
Example 4
Write a program which accepts principle, rate and time from user and prints the simple
interest.
#include <stdio.h>
int main()
{
Control Statements in c
The statements that are used to control the flow of execution of statements are known
as conditional control statements. Control statements enable us to specify the flow of
program control. It is the order in which the instructions in a program must be executed.
They make it possible to make decisions, to perform tasks repeatedly or to jump from one
section of code to another.
if statement
This is a popular decision making statement and is used to control the flow of execution
of statements. It is basically a two way decision statement and is used in conjunction with
as expression .The syntax is given below.
If(test condition)
{
statements;
}
If-else statement
The if-else statement is used to carry out a logical test and then take one of two possible
actions depending on the outcome of the test (i.e., whether the outcome is true or false).
The syntax for if-else statement is given below.
if (condition)
{
statements
}
else
{
statements
}
Looping Statements in c
When you need to execute a block of code several number of times then you need to use
looping statement in C. In C programming language there are three types of loops they
are while, for and do-while.
While loop
This loop checks the condition at first. Iif the condition is true then control goes inside
the loop body otherwise it goes outside the body. It repeats in clock wise direction. The
syntax is given below.
Do loop
A do while loop is a control flow statement that executes a block of code at least once,
and then repeatedly executes the block, or not, depending on a given condition at the end
of the block (in while). The syntax is given below.
do
{
Statements;
........
Increment/decrement (++ or --)
} while();
Example 11
#include<stdio.h>
#include<conio.h>
void main()
{
int i; Output
clrscr(); 1
i=1; 2
do 3
{ 4
printf(“\n%d”,i);
i++;
}
while(i<5);
getch();
}
Program 1
Write a program that allows the user to input two integers and displays the largest integer.
#include <stdio.h>
int main()
{
int num1, num2;
printf(“Enter two integers :”);
scanf(“%d%d”, &num1, &num2);
if (num1 > num2)
{
printf(“Largest number is %d.”, num1);
}
else
{
printf(“Largest number is %d.”, num2);
}
return 0;
}
Program 2
Write a program that prompts the user to input a number and displays if the number is
even or odd.
#include <stdio.h>
int main()
{
int num;
printf(“Enter a num:”);
scanf(“%d”, &num);
if(num % 2 == 0)
{
printf(“The number is even”);
}
Program 4
Write a program in C to read 10 numbers from keyboard and find their sum and average
by using for loop.
#include <stdio.h>
void main()
{
int i,n,sum=0;
float avg;
printf(“Input the 10 numbers : \n”);
for (i=1;i<=10;i++)
{
Program 6
Write a C program to print ODD numbers from 1 to N using while loop.
#include <stdio.h>
int main()
{
int number;
int n;
number=1;
Program 9
Write a program to print all uppercase alphabets using while loop.
#include <stdio.h>
int main()
{
char alphabet;
alphabet=’A’;
printf(“Uppercase alphabets:\n”);
while(alphabet<=’Z’)
{
printf(“%c”,alphabet);
alphabet++;
}
return0;
}
Program 11
Write a program using while or do while loop to read any integer number and print its
multiplication table.
#include <stdio.h>
int main()
{
intnum;
int i;
printf(“Enter an integer number: “);
scanf(“%d”,&num);
i=1;
while(i<=10){
printf(“%d\n”,(num*i));
i++;/*Increase loop counter*/
}
return0;
}
Program 13
Write a program to print the uppercase and lowercase alphabets from A to K.
#include <stdio.h>
int main()
{
char i;
printf(“Capital (upper) case characters:\n”);
for(i=’A’; i<=’K’; i++)
printf(“%c”,i);
printf(“\n\nLower case characters:\n”);
for(i=’a’; i<=’k’; i++)
printf(“%c”,i);
return0;
}
Assignment
1. Answer the following question.
a. What is C programming? Define it with its features.
b. Who was the inventor of C? When was it invented?
c. What are the advantages and disadvantages of C programming?
d. Define structure programming.
e. What are the elements of C programming?
f. Define C constant with its types.
g. What are the rules for naming variables?
h. Write differences between single character constant and string constant.
i. List out the operators used by C language.
j. Explain logical operators.
k. Define conditional operators with syntax.
l. What are the various data types used by C language?
m. List out some of the input and output functions used in C.
n. Write down the name of some format specifiers used by C.
o. Define header file with syntax.
p. What is control statement? Explain some control statements with syntax.
q. What is looping statement? Write down the types of looping statements with their
syntax.
AC : Alternate Current
ADSL : Asymmetric Digital Signature Line
ANSI : American National Standard Institute
ARP : Address Resolution Protocol
ARPA : Advance Research Project Agency
ASCC : Automatic Sequence Controlled Calculator
ASCII : American Standard Code for Information Interchange
ATM : Automated Teller Machine
AVI : Audio-Video Interleaved
CAD : Computer Aided Design
CAE : Computer Aided Education
CAM : Computer Aided Manufacturing
CAN : Computer Association of Nepal
CBT : Computer Based Training
CDMA : Code Division Multiple Access
CMOS : Complementary Metallic Oxide Semiconductor
COBOL : Common Business Oriented Language
CREN : Council Research European Network
CRT : Cathode Ray Tube
CSMA/CD : Carrier Sense Multiple Access / Coliseum Detection
CVT : Constant Voltage Transformer
DARPA : Department of Advance Research Project Agency
DBMS : Database Management System
DHCP : Dynamic Host Configuration Protocol