0% found this document useful (0 votes)
65 views127 pages

Programming For Problem Solving

This document provides an introduction to computer programming and problem solving. It defines a computer and describes the basic anatomy of a computer including hardware components like the CPU, memory, storage, and input/output devices. It also discusses software and different types. The document then introduces computer networks, describing basic elements like senders, mediums, and receivers. It explains different data transmission modes like simplex, half-duplex, and full-duplex. Finally, it discusses data transmission speeds and different bandwidth categories.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views127 pages

Programming For Problem Solving

This document provides an introduction to computer programming and problem solving. It defines a computer and describes the basic anatomy of a computer including hardware components like the CPU, memory, storage, and input/output devices. It also discusses software and different types. The document then introduces computer networks, describing basic elements like senders, mediums, and receivers. It explains different data transmission modes like simplex, half-duplex, and full-duplex. Finally, it discusses data transmission speeds and different bandwidth categories.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Unit I
Introduction
Syllabus

Simple model of a Computer – Hardware – Software – Data Representation, Introduction to


Computer Networks and Internet, Problem Solving Techniques – Bottom up design and top
down design - applications, Introduction to Algorithms and Flow Chart.

1. COMPUTER
An automatic electronic apparatus for making calculations or controlling operations that are
expressible in numerical or logical terms.

2. ANATOMY OF A COMPUTER/ SIMPLE MODEL OF A COMPUTER/ BASIC


ORGANISATION OF A COMPUTER
A computer can accept input , process or store data and produce output according to a set of
instructions which are fed into it. A computer can be divided into two components: Hardware
and software. Hardware is the tangible part of the computer where as software is intangible set of
instructions that control the hardware and make it perform specific task.

2.1 Hardware
Hardware is the physical components of the computer that includes all mechanical, electrical and
electronic parts attached to it. A computer consists of major components as follows:

SVCE Page 1
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Input and Output devices , central processing unit, memory unit and storage devices, interface
unit.

2.1.1 Input devices:


Input devices are electronic or electro-mechanical equipment that provide a means of
communicating with the computer system for feeding input data and instructions. The data and
instructions are typed, submitted or transmitted to a computer through input devices. Most
common input devices are:

Keyboard
A computer keyboard is one of the primary input devices used with a computer that looks similar
to those found on electric typewriters, but with some additional keys. Keyboards allow you to
input letters, numbers, and other symbols into a computer that can serve as commands or be used
to type text.

Mouse
A mouse is the pointing device attached to a computer. It is used to move the cursor around the
screen and to point to an object for the purpose of selecting or activating objects on graphical
interface.

Scanner
A scanner is a device that captures pictures or documents so that they can be stored in storage
devices, seen on a video screen, modified suitably, transported to other computers or printed on a
printer.

2.1.2 Output devices


Output devices mirror the input data or show the output results of the operations on the input
data or print the data. Some of the common output devices are

Monitor
The monitor displays the computer's user interface and open programs, allowing the user to
interact with the computer, typically using the keyboard and mouse.

Printer
Printer is a device that prints any data, report, documents, picture, diagrams etc.

2.1.3 Central Processing unit


CPU is the brain of the computer. Most of the processing takes place in CPU. During processing,
it locates and executes program instructions. It also fetches data from memory and i/o devices
and sends data back. CPU is divided into different functional units which are described below:

SVCE Page 2
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Registers
These are high-speed storage devices. It contains a set of general purpose registers that are used
for temporary storage of data values as needed during processing.
Special purpose registers are reserved for special purpose. Instruction Register (IR) holds the
current instruction to be executed. Program Counter (PC) is a register that holds the address of
the next instruction to be executed.

Arithmetic Logic Unit (ALU)


It is the part of the CPU that performs arithmetic operations, such as addition and subtraction as
well as logical operations, such as comparing two numbers.

Control Unit (CU)


This coordinates the processing by controlling the transfer of data and instructions between main
memory and registers in CPU.
It also coordinates the execution of Arithmetic Logic Unit (ALU) to perform operations on data
stored in particular registers.
It consists of

an instruction decoding circuit that interprets what action should be performed.
a control and timing circuit detects all the other parts of the computer by producing the
respective control signals.

2.1.4 Memory Unit


A storage area is needed in a computer to store instructions and data either temporarily or
permanently , so that subsequent retrieval of the instructions and data can be possible on
demand.
CPU uses registers exclusively to store and manipulate data and instruction during the
processing. Apart from registers, there are two types of memory as follows:

Primary Memory is the area where data and programs stored while the program is being
executed along with the data .

Secondary memory provides large, non volatile and inexpensive storage for programs and
data.
2.1.5 Interface Unit
The interface unit interconnects the CPU with memory and also with the various input / output
devices. The instruction and data move between the CPU and other hardware components
through interface unit.

SVCE Page 3
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

2.2 Software
Software provides the instructions that tells the hardware exactly what is to be performed and in
what order. This set of instruction is sequenced and organised in a computer program. A program
is a series of instructions which is intended to direct a computer to perform certain functions and
executed by the processor.
Software is generally categorised as follows:

System software is designed to facilitate and coordinate the use of computer by making
hardware operational. Examples: Operating system, language translator, loader, linker.
Application program is designed to perform specific tasks for the user. Example Word,
Excel, AutoCAD, Internet explorer.

3. COMPUTER NETWORK

A computer network is a network of geographically distributed multiple computers connected in


a manner to exchange information among them. Sharing of resources, and sharing of processing
load are some of the major objectives of a computer network.

3.1 Basic elements of a communication system

Communication is the process of transferring messsages from one point to another. The three
basic elements of a communication system are:

1. Sender – which creates the message to be transmitted.


2. Medium – which carries the message
3. Receiver – which receives the message

3.2 Data Transmission modes

There are three ways or modes of transmitting data from one point to another. These are simplex,
half duplex and full duplex.

SVCE Page 4
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

3.2.1 Simplex:

Communication takes place in only one direction.

Examples of simplex include radio broadcasting, television broadcasting, computer to printer

communication, and keyboard to computer connections.

3.2.2 Half Duplex

In half duplex mode, data can be transmitted in both directions on a signal carrier except not at
the same time. At a certain point, it is actually a simplex channel whose transmission direction
can be switched. Walkie-talkie is a typical half duplex device. It has a ―push-to-talk‖ button
which can be used to turn on the transmitter but turn off the receiver. Therefore, once you push
the button, you cannot hear the person you are talking to but your partner can hear you. An
advantage of half-duplex is that the single track is cheaper than the double tracks.

3.2.3 Full Duplex

A full duplex communication channel is able to transmit data in both directions on a signal
carrier at the same time. It is constructed as a pair of simplex links that allows bidirectional
simultaneous transmission. Take telephone as an example, people at both ends of a call can
speak and be heard by each other at the same time because there are two communication paths
between them. Thus, using the full duplex mode can greatly increase the efficiency of
communication.

SVCE Page 5
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

3.3Data Transmission speed

The speed with which data can be transmitted from one device to another. Data rates are often
measured in megabits (million bits) or megabytes (million bytes) per second. These are usually
abbreviated as Mbps and MBps,respectively.

A term used to describe the data handling capacity of a communication system is bandwidth.
Bandwidth is the range of frequencies that is available for the transmission of data. The
communication data transfer rate is measured in a unit called baud. Baud is identical to bits per
second. Depending on their transmission speeds, communication channels are grouped into the
following three basic categories:

3.3.1Narrow band:

Narrowband or subvoice grade channels range in speed from 45 to 300 baud. They are used for
handling low data volumes and are adequate for low-speed devices. They are mainly for
telegraphs lines and low speed terminals.

3.3.2Voice band:

Voice band channels handle moderate data volumes and can transmit data at speeds upto 9600 baud.
Their major application is ordinary telephone voice communication. They are also used for data
transmission from slow I/O devices to CPU or vice-versa.

3.3.3Broad band:

Broadband are used when large volumes of data are to be transmitted at high speed. These systems
provide data transmission rates of 1 million baud or more.

3.4Data Transmission media

3.4.1Transmission media is a pathway that carries the information from sender to receiver. We use
different types of cables or waves to transmit data. Data is transmitted normally through electrical or
electromagnetic signals.

3.4.1Types of Transmission Media

Transmission media is broadly classified into two groups.


SVCE Page 6
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Wired or Guided Media or Bound Transmission Media : Bound transmission media are the
cables that are tangible or have physical existence and are limited by the physical
geography. Popular bound transmission media in use are twisted pair cable, co-axial cable and
fiber optical cable. Each of them has its own characteristics like transmission speed, effect of
noise, physical appearance, cost etc.

 Wireless or Unguided Media or Unbound Transmission Media : Unbound


transmission media are the ways of transmitting data without using any cables. These
media are not bounded by physical geography. This type of transmission is called
Wireless communication. Nowadays wireless communication is becoming popular.
Wireless LANs are being installed in office and college campuses. This transmission
uses Microwave, Radio wave, Infra red are some of popular unbound transmission media.

Twisted Pair (Copper Conductors)

A twisted pair is a pair of copper wires, with diameters of 0.4-0.8 mm, twisted together and
wrapped with a plastic coating. The twisting reduces the electrical noise and the error rate of the
data transmission. Each conductor is separately insulated by some low-smoke and fires retardant
substance.

Co-axial Cable

Coaxial cable is a robust shielded copper wire two-conductor cable in which a solid center
conductor runs concentrically (coaxial) inside a solid outer circular conductor.
SVCE Page 7
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Coaxial cable includes shield for improved performance and therefore is expensive. Cable TV
networks use coaxial cable. Local Area Networks can operate over coaxial cable to the
10BASE5, 10BASE2 and 10BASET specifications. In general, coaxial cable enables longer
distance transmission at higher data rates than twisted pair cable but this is more expensive.

There are two types of coaxial cables.


Baseband: It transmits a single signal at a time at very high speed. The signal on baseband cable
must be amplified at a specified distances. It is used for local area networks.

Broadband: It can transmit many simultaneous signals using different frequencies.

Advantages:

 High Bandwidth
 Better noise Immunity
 Easy to install and expand
 Inexpensive
Disadvantages:

 Single cable failure can disrupt the entire network

Fiber-Optics Cable

A cable with central glass tube covered with protective shield which transmit data using photons
is fiber optics cable. These cables transmit data via concentrated bursts of laser beams which are
carried through bundles of hair thin glass fibers.

They have advantages over electronic cables in transmission speed and volume. This technology
has revolutionized telecommunication applications which used electronic cables. Fiber optics
cables as free from electro-magnetic interference as well as wire tapping. fiber optics cable
considered a broad band communication channel

Advantages:
Increased capacity and bandwidth

Light weight

Less signal attenuation


Disadvantages:

Difficult to install and maintain

High cost
SVCE Page 8
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Fragile
Radiowaves
These are easy to generate and can penetrate through buildings.The sending and receiving
antennas need not be aligned. Frequency Range:3KHz – 1GHz. AM and FM radios and cordless
phones use Radiowaves for transmission.

Microwaves
It is a line of sight transmission i.e. the sending and receiving antennas need to be properly
aligned with each other. The distance covered by the signal is directly proportional to the height
of the antenna. Frequency Range:1GHz – 300GHz. These are majorly used for mobile phone
communication and television distribution.

Infrared
Infrared waves are used for very short distance communication. They cannot penetrate through
obstacles. This prevents interference between systems. Frequency Range:300GHz – 400THz. It
is used in TV remotes, wireless mouse, keyboard, printer, etc.

4.NETWORK TOPOLOGIES

Network Topology is the schematic description of a network arrangement, connecting various


nodes(sender and receiver) through lines of connection.

4.1Types Of Network Topologies

4.1.1BUS Topology

Bus topology is a network type in which every computer and network device is connected to
single cable. When it has exactly two endpoints, then it is called Linear Bus topology.

Features of Bus Topology

 It transmits data only in one direction.

SVCE Page 9
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Every device is connected to a single cable


Advantages of Bus Topology

 It is cost effective.
 Cable required is least compared to other network topology.
 Used in small networks.
 It is easy to understand.
 Easy to expand joining two cables together.
Disadvantages of Bus Topology

 Cables fails then whole network fails.


 If network traffic is heavy or nodes are more the performance of the network decreases.
 Cable has a limited length.
 It is slower than the ring topology.

4.1.2RING Topology

It is called ring topology because it forms a ring as each computer is connected to another

computer, with the last one connected to the first. Exactly two neighbours for each device.

Features of Ring Topology


A number of repeaters are used for Ring topology with large number of nodes, because if
someone wants to send some data to the last node in the ring topology with 100 nodes, then the
data will have to pass through 99 nodes to reach the 100th node. Hence to prevent data loss
repeaters are used in the network.

SVCE Page 10
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

The transmission is unidirectional, but it can be made bidirectional by having 2 connections


between each Network Node, it is called Dual Ring Topology.

In Dual Ring Topology, two ring networks are formed, and data flow is in opposite direction in
them. Also, if one ring fails, the second ring can act as a backup, to keep the network up.

Data is transferred in a sequential manner that is bit by bit. Data transmitted, has to pass through
each node of the network, till the destination node.

Advantages of Ring Topology

 Transmitting network is not affected by high traffic or by adding more nodes, as only the
nodes having tokens can transmit data.
 Cheap to install and expand

Disadvantages of Ring Topology

 Troubleshooting is difficult in ring topology.


 Adding or deleting the computers disturbs the network activity.
 Failure of one computer disturbs the whole network.

4.1.3STAR Topology

In this type of topology all the computers are connected to a single hub through a cable. This hub

is the central node and all others nodes are connected to the central node.

Features of Star Topology

 Every node has its own dedicated connection to the hub.


 Hub acts as a repeater for data flow.

SVCE Page 11
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Can be used with twisted pair, Optical Fibre or coaxial cable.

Advantages of Star Topology

 Fast performance with few nodes and low network traffic.


 Hub can be upgraded easily.
 Easy to troubleshoot.
 Easy to setup and modify.
 Only that node is affected which has failed, rest of the nodes can work smoothly.

Disadvantages of Star Topology

 Cost of installation is high.


 Expensive to use.
 If the hub fails then the whole network is stopped because all the nodes depend on the
hub.
 Performance is based on the hub that is it depends on its capacity

4.1.4MESH Topology

It is a point-to-point connection to other nodes or devices. All the network nodes are connected
to each other. Mesh has n(n-1)/2 physical channels to link n devices.

SVCE Page 12
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Features of Mesh Topology

 Fully connected.
 Robust.
 Not flexible.

Advantages of Mesh Topology

 Each connection can carry its own data load.


 It is robust.
 Fault is diagnosed easily.
 Provides security and privacy.

Disadvantages of Mesh Topology

 Installation and configuration is difficult.


 Cabling cost is more.
 Bulk wiring is required.

4.1.5TREE Topology

It has a root node and all other nodes are connected to it forming a hierarchy. It is also called

hierarchical topology. It should at least have three levels to the hierarchy.

Features of Tree Topology

 Ideal if workstations are located in groups.


 Used in Wide Area Network.
Advantages of Tree Topology

 Extension of bus and star topologies.


 Expansion of nodes is possible and easy.

SVCE Page 13
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Easily managed and maintained.


 Error detection is easily done.
Disadvantages of Tree Topology

 Heavily cabled.
 Costly.
 If more nodes are added maintenance is difficult.
 Central hub fails, network fails.

4.1.6HYBRID Topology

It is two different types of topologies which is a mixture of two or more topologies. For example
if in an office in one department ring topology is used and in another star topology is used,
connecting these topologies will result in Hybrid Topology (ring topology and star topology).

Features of Hybrid Topology

 It is a combination of two or topologies


 Inherits the advantages and disadvantages of the topologies included

SVCE Page 14
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Advantages of Hybrid Topology

 Reliable as Error detecting and trouble shooting is easy.


 Effective.
 Scalable as size can be increased easily.
 Flexible.
Disadvantages of Hybrid Topology

 Complex in design.
 Costly.

5.NETWORK DEVICES (HUB, REPEATER, BRIDGE, SWITCH, ROUTER,


GATEWAYS AND BROUTER)

5.1 Repeater – A repeater operates at the physical layer. Its job is to regenerate the signal over
the same network before the signal becomes too weak or corrupted so as to extend the length to
which the signal can be transmitted over the same network. An important point to be noted about
repeaters is that they do not amplify the signal. When the signal becomes weak, they copy the
signal bit by bit and regenerate it at the original strength. It is a 2 port device.

5.2 Hub – A hub is basically a multiport repeater. A hub connects multiple wires coming from
different branches, for example, the connector in star topology which connects different stations.
Hubs cannot filter data, so data packets are sent to all connected devices. In other
words, collision domain of all hosts connected through Hub remains one. Also, they do not have
intelligence to find out best path for data packets which leads to inefficiencies and wastage.

5.3 Bridge – A bridge operates at data link layer. A bridge is a repeater, with add on
functionality of filtering content by reading the MAC addresses of source and destination. It is
also used for interconnecting two LANs working on the same protocol. It has a single input and
single output port, thus making it a 2 port device.

5.4 Switch – A switch is a multi port bridge with a buffer and a design that can boost its
efficiency(large number of ports imply less traffic) and performance. Switch is data link layer
device. Switch can perform error checking before forwarding data, that makes it very efficient as
it does not forward packets that have errors and forward good packets selectively to correct port
only.

5.5 Routers – A router is a device like a switch that routes data packets based on their IP
addresses. Router is mainly a Network Layer device. Routers normally connect LANs and
WANs together and have a dynamically updating routing table based on which they make
decisions on routing the data packets. Router divide broadcast domains of hosts connected
through it.
SVCE Page 15
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

5.6 Gateway – A gateway is a passage to connect two networks together that may work upon
different networking models. They basically works as the messenger agents that take data from
one system, interpret it, and transfer it to another system. Gateways are also called protocol
converters and can operate at any network layer. Gateways are generally more complex than
switch or router.

6. TYPES OF COMMUNICATION NETWORKS

Communication Networks can be of following 3 types:

 Local Area Network (LAN)


 Metropolitan Area Network (MAN)
 Wide Area Network (WAN)

SVCE Page 16
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

6.1Local Area Network (LAN)

It is also called LAN and designed for small physical areas such as an office, group of buildings
or a factory. LANs are used widely as it is easy to design and to troubleshoot. Personal
computers and workstations are connected to each other through LANs.

LAN can be a simple network like connecting two computers, to share files and network among
each other while it can also be as complex as interconnecting an entire building.

LAN networks are also widely used to share resources like printers, shared hard-drive etc.

Characteristics of LAN

 LAN's are private networks, not subject to tariffs or other regulatory controls.
 LAN's operate at relatively high speed when compared to the typical WAN.
 There are different types of Media Access Control methods in a LAN, the prominent ones
are Ethernet, Token ring.
 It connects computers in a single building, block or campus, i.e. they work in a restricted
geographical area.

Advantages of LAN

 Resource Sharing
 Software Applications Sharing
 Easy and Cheap Communication
SVCE Page 17
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Centralized Data
 Data Security
 Internet Sharing

Disadvantages of LAN

 High Setup Cost


 Privacy Violations
 Data Security Threat
 LAN Maintenance Job
 Covers Limited Area

6.2Metropolitan Area Network (MAN)

Characteristics of MAN

 It generally covers towns and cities (50 km)


 Communication medium used for MAN are optical fibers, cables etc.
 Data rates adequate for distributed computing applications.

Advantages of MAN

 Extremely efficient and provide fast communication via high-speed carriers, such as fibre
optic cables.
 It provides a good back bone for large network and provides greater access to WANs.
 The dual bus used in MAN helps the transmission of data in both directions

SVCE Page 18
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

simultaneously.
 A MAN usually encompasses several blocks of a city or an entire city.

Disadvantages of MAN

 More cable required for a MAN connection from one place to another.
 It is difficult to make the system secure from hackers and industrial espionage(spying)
graphical regions.

6.3 Wide Area Network (WAN)

It is used for the network that covers large distance such as cover states of a country. It is not
easy to design and maintain. Communication medium used by WAN are PSTN or Satellite links.
WAN operates on low data rates.

Characteristics of WAN

 It generally covers large distances(states, countries, continents).


 Communication medium used are satellite, public telephone networks which are
connected by routers.

Advantages of WAN

 Covers a large geographical area so long distance business can connect on the one
network.
 Shares software and resources with connecting workstations.

SVCE Page 19
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Messages can be sent very quickly to anyone else on the network. These messages can
have picture, sounds or data included with them(called attachments).
 Expensive things(such as printers or phone lines to the internet) can be shared by all the
computers on the network without having to buy a different peripheral for each computer.
 Everyone on the network can use the same data. This avoids problems where some users
may have older information than others.

Disadvantages of WAN

 Need a good firewall to restrict outsiders from entering and disrupting the network.
 Setting up a network can be an expensive, slow and complicated. The bigger the network
the more expensive it is.
 Once set up, maintaining a network is a full-time job which requires network supervisors
and technicians to be employed.
 Security is a real issue when many different people have the ability to use information
from other computers. Protection against hackers and viruses adds more complexity and
expense.

7. INTERNET

The Internet is a global system of interconnected computer networks that use the standard
Internet protocol suite (TCP/IP) to serve billions of users worldwide. It is a network of networks
that consists of millions of private, public, academic, business, and government networks, of
local to global scope, that are linked by a broad array of electronic, wireless and optical
networking technologies. The Internet carries a vast range of information resources and services,
such as the interlinked hypertext documents of the World Wide Web (WWW) and the
infrastructure to support electronic mail.

7.1 Uses of Internet

Internet has been the most useful technology of the modern times which helps us not only in our
daily lives, but also our personal and professional lives developments. The internet helps us
achieve this in several different ways.

For the students and educational purposes the internet is widely used to gather information so as
to do the research or add to the knowledge of various subjects. Even the business professionals
and the professionals like doctors, access the internet to filter the necessary information for their
use. The internet is therefore the largest encyclopedia for everyone, in all age categories. The
internet has served to be more useful in maintaining contacts with friends and relatives who live
abroad permanently.

SVCE Page 20
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

7.2 Advantages of Internet:

 E-mail: Email is now an essential communication tools in business. With e-mail you can
send and receive instant electronic messages, which works like writing letters. Your
messages are delivered instantly to people anywhere in the world, unlike traditional mail
that takes a lot of time. Email is free, fast and very cheap when compared to telephone,
fax and postal services.
 24 hours a day 7 days a week: Internet is available, 24x7 days for usage.
 Information: Information is probably the biggest advantage internet is offering. There is
a huge amount of information available on the internet for just about every subject,
ranging from government law and services, trade fairs and conferences, market
information, new ideas and technical support. You can almost find any type of data on
almost any kind of subject that you are looking for by using search engines like google,
yahoo, msn, etc.
 Online Chat: You can access many ‗chat rooms‘ on the web that can be used to meet
new people, make new friends, as well as to stay in touch with old friends.
 Services: Many services are provided on the internet like net banking, job searching,
purchasing tickets, hotel reservations, guidance services on array of topics engulfing
every aspect of life.
 Communities: Communities of all types have sprung up on the internet. Its a great way
to meet up with people of similar interest and discuss common issues.
 E-commerce: Along with getting information on the Internet, you can also shop online.
There are many online stores and sites that can be used to look for products as well as
buy them using your credit card. You do not need to leave your house and can do all
your shopping from the convenience of your home. It has got a real amazing and wide
range of products from household needs, electronics to entertainment.
 Entertainment: Internet provides facility to access wide range of Audio/Video songs,
plays films. Many of which can be downloaded. One such popular website is YouTube.
 Software Downloads: You can freely download innumerable, softwares like utilities,
games, music, videos, movies, etc from the Internet.

7.3 Limitations of Internet

 Theft of Personal information: Electronic messages sent over the Internet can be easily
snooped and tracked, revealing who is talking to whom and what they are talking about.
If you use the Internet, your personal information such as your name, address, credit
card, bank details and other information can be accessed by unauthorized persons. If you
use a credit card or internet banking for online shopping, then your details can also be
‗stolen‘.
 Negative effects on family communication: It is generally observed that due to more
time spent on Internet, there is a decrease in communication and feeling of togetherness
among the family members.
 Internet addiction: There is some controversy over whether it is possible to actually be
addicted to the Internet or not. Some researchers, claim that it is simply people trying to
SVCE Page 21
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

escape their problems in an online world.


 Virus threat: Computers are mainly getting these viruses from the Internet. Virus is a
program which disrupts the normal functioning of your computer systems. Computers
attached to internet are more prone to virus attacks and they can end up into crashing
your whole hard disk.
 Spamming: It is often viewed as the act of sending unsolicited email. This multiple or
vast emailing is often compared to mass junk mailings. It needlessly obstruct the entire
system. Most spam is commercial advertising, often for dubious products, get-rich-
quick schemes, or quasi-legal services. Spam costs the sender very little to send — most
of the costs are paid for by the recipient or the carriers rather than by the sender

7.4 SERVICES OF INTERNET -E-mail, FTP, Telnet

7.4.1 E-Mail (Electronic Mail)

E-mail or Electronic mail is a paperless method of sending messages, notes or letters from one
person to another or even many people at the same time via Internet. E-mail is very fast
compared to the normal post. E-mail messages usually take only few seconds to arrive at their
destination. One can send messages anytime of the day or night, and, it will get delivered
immediately. You have the privilege of sending something extra such as a file, graphics, images
etc. along with your e-mail. The biggest advantage of using email is that it is cheap, especially
when sending messages to other states or countries and at the same time it can be delivered to a
number of people around the world. It allows you to compose note, get the address of the
recipient and send it. Once the mail is received and read, it can be forwarded or replied. One can
even store it for later use, or delete. In e-mail even the sender can request for delivery receipt and
read receipt from the recipient.

Features of E-mail:

 One-to-one or one-to-many communications


 Instant communications
 Physical presence of recipient is not required
 Most inexpensive mail services, 24-hours a day and seven days a week
 Encourages informal communications

7.4.2 FTP (File Transfer Protocol)

File Transfer Protocol, is an Internet utility software used to uploaded and download files. It
gives access to directories or folders on remote computers and allows software, data and text
files to be transferred between different kinds of computers.

SVCE Page 22
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

FTP works on the basis of same principle as that of Client/Server. FTP ―Client‖ is a program
running on your computer that enables you to communicate with remote computers. The FTP
client takes FTP command and sends these as requests for information from the remote computer
known as FTP servers. To access remote FTP server it is required, but not necessary to have an
account in the FTP server. When the FTP client gets connected, FTP server asks for the
identification in terms of User Login name and password of the FTP client. If one does not have
an account in the remote FTP server, still he can connect to the server using anonymous login.

Using anonymous login anyone can login in to a FTP server and can access public archives;
anywhere in the world, without having an account. One can easily Login to the FTP site with the
username anonymous and e-mail address as password.

Objectives of FTP :

 Provide flexibility and promote sharing of computer programs, files and data
 Transfer data reliably and more efficiently over network
 Encourage implicit or indirect use of remote computers using Internet
 Shield a user from variations in storage systems among hosts.
Telnet (Remote Computing)

Telnet or remote computing is telecommunication utility software, which uses available


telecommunication facility and allows you to become a user on a remote computer. Once you

SVCE Page 23
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

gain access to remote computer, you can use it for the intended purpose. The TELNET works in
a very step by step procedure. The commands typed on the client computer are sent to the local
Internet Service Provider (ISP), and then from the ISP to the remote computer that you have
gained access. Most of the

ISP provides facility to TELENET into your own account from another city and check your e-
mail while you are travelling or away on business.

8. PROBLEM SOLVING TECHNIQUES

A computer cannot solve a problem on its own. One has to provide step by step solutions of the
problem to the computer. In fact, the task of problem solving is not that of the computer. It is the
programmer who has to write down the solution to the problem in terms of simple operations
which the computer can understand and execute. In order to solve a problem by the computer,
one has to pass though certain stages or steps.

They are
1. Understanding the problem
2. Analyzing the problem
3. Developing the solution
4. Coding and implementation.

1. Understanding the problem: Here we try to understand the problem to be solved in totally.
Before proceeding to the next stage or step, we should be absolutely sure about the objectives of
the given problem.

2. Analyzing the problem: After understanding thoroughly the problem to be solved, we look
into different ways of solving the problem and evaluate each of these methods. The idea here is
to search an appropriate solution to the problem under consideration. The end result of this stage
is a broad overview of the sequence of operations that are to be carried out to solve the given
problem.

3. Developing the solution: Here the overview of the sequence of operations that was the result
of analysis stage is expanded to form a detailed step by step solution to the problem under
consideration.

4. Coding and implementation: The last stage of the problem solving is the conversion of the
detailed sequence of operations in to a language that the computer can understand. Here each
step is converted to its equivalent instruction or instructions in the computer language that has
been chosen for the implementation.

8.1 Top-Down Design

SVCE Page 24
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

We know that a system is composed of more than one sub-systems and it contains a number of
components. Further, these sub-systems and components may have their own set of sub-system
and components and creates hierarchical structure in the system.

Top-down design takes the whole software system as one entity and then decomposes it to
achieve more than one sub-system or component based on some characteristics. Each sub-system
or component is then treated as a system and decomposed further. This process keeps on running
until the lowest level of system in the top-down hierarchy is achieved.

Top-down design starts with a generalized model of system and keeps on defining the more
specific part of it. When all components are composed the whole system comes into existence.

Top-down design is more suitable when the software solution needs to be designed from scratch
and specific details are unknown.

Top down program design is an approach to program design that starts with the general concept
and repeatedly breaks it down into its component parts. In other words, it starts with the abstract
and continually subdivides it until it reaches the specific. Consider creating the prime
factorization of a number like 1540. The steps involved might look like:

 1540
 2 x 770
 2 x 2 x 385
 2 x 2 x 5 x 77
 2 x 2 x 5 x 7 x 11

Top down program design works the same way. We start with the overall objective and wind up
with a series of steps needed to accomplish it.

Top-down analysis, therefore, simplifies or reduces the complexity of the process of problem
solving. It is not limited by the type of program. Top-down analysis is a general method for
attending to any problem. It provides a strategy that has to be followed for solving all problems.
There are two essential ideas in top-down analysis:
 subdivision of a problem
 hierarchy of tasks

Subdivision of a problem means breaking a big problem into two or more smaller problems.
Therefore, to solve the big problem, first these smaller problems have to be solved. Top-down
analysis does not simply divide a problem into two or more smaller problems.It goes further than
that. Each of these smaller problems is further subdivided. This process continues downwards,
creating a hierarchy of tasks, from one level to the next, until no further break up is possible.

The four basic steps to top-down analysis are as follows:


Step 1: Define the complete scope of the problem to determine the basic requirement for its
solution. Three factors must be considered in the definition of a programming problem.
SVCE Page 25
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Input: What data is required to be processed by the program?


Process: What must be done with the input data? What type of processing is required?
Output: What information should the program produce? In what form should it be presented?

Step 2: Based on the definition of the problem, divide the problem into two or more separate
parts.
Step 3: Carefully define the scope of each of these separate tasks and subdivide them further, if
necessary, into two or more smaller tasks.
Step 4: Repeat step 3. Every step at the lowest level describes a simple task, which cannot be
broken further.

8.2 Bottom-up Design

The bottom up design model starts with most specific and basic components. It proceeds with
composing higher level of components by using basic or lower level components. It keeps
creating higher level components until the desired system is not evolved as one single
component. With each higher level, the amount of abstraction is increased.

Bottom-up strategy is more suitable when a system needs to be created from some existing
system, where the basic primitives can be used in the newer system.

Bottom up program design works in the exact opposite way. It starts with the component parts
and repeatedly combines them to achieve the general concept. In other words, it starts with the
specific and continually combines it until it reaches the abstract. For example, consider the
factorization from the previous section. For bottom up design the steps involved might look like:

 2 x 2 x 5 x 7 x 11
 2 x 2 x 5 x 77
 2 x 2 x 385
 2 x 770
 1540

8.3 Difference Between Top-down Approach and Bottom-up Approach

Top-down Approach Bottom-up Approach


A top-down approach is essentially the breaking A bottom-up approach is the piecing together of
down of a program to gain insight into its module (or small program) to give rise to more
compositional small program (or module) in a complex program, thus making the original
reverse engineering fashion. modules of the emergent program.
Structure / procedure oriented programming Object oriented programming languages like
languages like C programming language follows C++ and JAVA programming language follows
top-down approach. bottom-up approach.
A top-down approach begins with high level A bottom-up approach begins with low level
design and ends with low level design or design or development and ends with high level
development. design.
SVCE Page 26
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

In top-down approach, main function is written In bottom-up approach, code is developed from
first and all sub functions are called from main modules and then these modules are integrated
function thus, sub-functions are written based with main function
on the requirement

9. ALGORITHM

An algorithm is an effective procedure for solving a problem in a finite number of steps. A


program is composed of algorithm and data. The four common ways of representing an
algorithm are the Step-form, Pseudo-code, Flowchart and Nassi-Schneiderman.

9.1 Key Features of an Algorithm

An algorithm can be stated using three basic constructs: sequence, decision, and repetition.

Sequence
Sequence means that each step or process in the algorithm is executed in the specified order.

The decision constructs— if ... then, if ... then ... else ...
In algorithms the outcome of a decision is either true or false; there is no state in between.
The outcome of the decision is based on some condition that can only result in a true or false
value. For example, if today is Friday then collect pay is a decision and the decision takes the
general form:

if proposition then process

A proposition, in this sense, is a statement, which can only be true or false. It is either true that
‗today is Friday‘ or it is false that ‗today is not Friday‘. It can not be both true and false. If the
proposition is true, then the process or procedure that follows the then is executed.

The decision can also be stated as:

if proposition then process1


else process2

This is the if … then … else … form of the decision. This means that if the proposition is true
then execute process1, else, or otherwise, execute process2 The first form of the decision if
proposition then process has a null else, that is, there is no else.

The repetition constructs— repeat and while


Repetition can be implemented using constructs like the repeat loop, while loop, and if.. then ..
goto .. loop.The Repeat loop is used to iterate or repeat a process or sequence of processes until
some condition becomes true.
SVCE Page 27
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

It has the general form:


Repeat
Process1
Process2
..............
………..
ProcessN
Until proposition

Example:

Repeat
Fill water in kettle
Until kettle is full
The process is ‗Fill water in kettle,‘ the proposition is ‗kettle is full‘.
The Repeat loop does some processing before testing the state of the proposition. What happens
though if in the above example the kettle is already full? If the kettle is already full at the start of
the Repeat loop, then filling more water will lead to an overflow. This is a drawback of the
Repeat construct.
In such a case the while loop is more appropriate. The above example with the while loop is
shown as follows:
while kettle is not full
fill water in kettle

Since the decision about the kettle being full or not is made before filling water, the possibility of
an overflow is eliminated. The while loop finds out whether some condition is true before
repeating a process or a sequence of processes.

If the condition is false, the process or the sequence of processes is not executed. The general
form of while loop is:

while proposition
begin

Process 1

Process 2
………..
………...
Process N
end

The if .. then goto .. is also used to repeat a process or a sequence of processes until the given
proposition is false. In the kettle example, this construct would be implemented as follows:

SVCE Page 28
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

1. Fill some water in kettle


2. if kettle not full then goto 1

So long as the proposition ‗kettle not full‘ is true the process, ‗fill some water in kettle‘ is
repeated. The general form of if .. then goto .. is:

Process1
Process2
……….
……….
ProcessN
if proposition then goto Process1

Termination
The algorithm must end after a finite number of steps.

Correctness
The prepared algorithm needs to be verified for its correctness. Correctness means how easily its
logic can be argued to meet the algorithm‘s primary goal. This requires the algorithm to be made
in such a way that all the elements in it are traceable to the requirements.

9.2 EXAMPLE ALGORITHMS


1. Write the algorithm for finding the sum of any two numbers.

Solution Let the two numbers be A and B and let their sum be equal to C. Then, the desired algorithm is given as follows:
1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. C = A + B
5. PRINT C
6. STOP

2. Write the algorithm for determining the remainder of a division operation where the dividend and divisor are both
integers.

Solution Let N and D be the dividend and divisor, respectively.


Assume Q to be the quotient, which is an integer, and R to be the remainder. The algorithm for the given problem is as follows.
1. START
2. PRINT “ENTER DIVIDEND”
3. INPUT N
4. PRINT “ENTER DIVISOR”
5. INPUT D
6. Q <- N/D (Integer division)
7. R <- N – Q * D
8. PRINT R
9. STOP

SVCE Page 29
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

3. Write an algorithm that compares two numbers and prints either the message identifying the greater number or the
message stating that both numbers are equal.

Solution This example demonstrates how the process of selection or decision making is implemented in an algorithm using the
stepform. Here, two variables, A and B, are assumed to represent the two numbers that are being compared. The algorithm for this
problem is given as follows.

1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. IF A > B THEN
PRINT “A IS GREATER THAN B”
5. IF B > A THEN
PRINT “B IS GREATER THAN A”
6. IF A = B THEN
PRINT “BOTH ARE EQUAL”
7. STOP

4. Write an algorithm to check whether a number given by the user is odd or even.

Solution Let the number to be checked be represented by N. The number N is divided by 2 to give an integer quotient, denoted
by Q. If the remainder, designated as R, is zero, N is even; otherwise N is odd. This logic has been applied in the following algorithm.

1. START
2. PRINT “ENTER THE NUMBER”
3. INPUT N
4. Q <- N/2 (Integer division)
5. R <- N – Q * 2
6. IF R = 0 THEN
PRINT “N IS EVEN”
7. IF R != 0 THEN
PRINT “N IS ODD”
8. STOP

5. Write an algorithm for the addition of N given numbers.

Solution Let the sum of N given numbers be represented by S. Each time a number is given as input, it is assigned to the
variable A. The algorithm using the loop construct ‘if … then goto …’ is used as follows:

1. START
2. PRINT “HOW MANY NUMBERS?”
3. INPUT N
4. S <- 0
5. C <- 1
6. PRINT “ENTER NUMBER”
7. INPUT A
8. S <- S + A
9. C <- C + 1
10. IF C <= N THEN GOTO 6
11. PRINT S
12. STOP

10 FLOWCHART

A flowchart comprises a set of various standard shaped boxes that are interconnected by flow lines. Flow lines
have arrows to indicate the direction of the flow of control between the boxes. The activity to be performed is
written within the boxes in English. In addition, there are connector symbols that are used to indicate that the
flow of control continues elsewhere, for example, the next page.

SVCE Page 30
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

Guidelines for drawing a flowchart


Flowcharts are usually drawn using standard symbols; however, some special symbols can also be developed
when required. Some standard symbols frequently required for flowcharting many computer programs are
shown in the figure.

The following are some guidelines in flowcharting.


 In drawing a proper flowchart, all necessary requirements should be listed out in a logical order.
 There should be a logical start and stop to the flowchart.
 The flowchart should be clear, neat, and easy to follow.
 There should be no ambiguity in understanding the flowchart.
 The usual direction of the flow of a procedure or system is from left to right or top to bottom.
 Only one flow line should emerge from a process symbol.

 Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible
answer, can leave the decision symbol.

 Only one flow line is used in conjunction with a terminal symbol.

SVCE Page 31
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

 A sequence of steps or processes that are executed in a particular order is shown using process
symbols connected with flow lines. One flow line enters the first process while one flow line emerges
from the last process in the sequence.

 Selection of a process or step is depicted by the decision making and process symbols. Only one input
indicated by one incoming flow line and one output flowing out of this structure exists. The decision
symbol and the process symbols are connected by flow lines.

 Iteration or looping is depicted by a combination of process and decision symbols placed in proper
order. Here flow lines are used to connect the symbols and depict input and output to this structure.

SVCE Page 32
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

10.1 EXAMPLE FLOWCHARTS

1. Draw a flowchart to find the largest of three numbers A, B,and C.


Solution

2. The XYZ Construction Company plans to give a 5% year-end bonus to each of its employees earning Rs 5,000 or
more per year, and a fixed bonus of Rs 250 to all other employees. Draw a flowchart and write the step-form
algorithm for printing the bonus of any employee.

SVCE Page 33
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING

3. Draw a flowchart for calculating the simple interest using the formula SI = (P * T * R)/100, where P denotes the
principal amount, T time, and R rate of interest.

SVCE Page 34
Unit 2 - IT18101 Programming for Problem Solving

Unit II
Syllabus

Introduction to ‘C’ programming – structure of a ‘C’ program – compilation and linking


processes. Conversion of simple algorithm to program.

Constants, Variables – Data Types – Expressions using operators in ‘C’ – Managing Input
and Output operations – Decision Making and Branching – Looping statements – solving
simple scientific and statistical problems.

1. INTRODUCTION TO ‘C’ PROGRAMMING


The story started with the Common Programming Language (CPL) which Martin Richards at
the University of Cambridge turned into Basic Combined Programming Language (BCPL).
This was essentially a type-less language, which allowed the user direct access to the
computer memory.
This made it useful to system programmers. Ken Thompson at Bell Labs, USA, wrote his
own variant of this and called it B. In due course, the designers of UNIX modified it to
produce a programming language called C. Dennis Ritchie, also at Bell Labs, is credited for
designing C in the early 1970s. Subsequently, UNIX was rewritten entirely in C. In 1983, an
ANSI standard for C emerged, consolidating its international acceptance. Ninety percent of
the code of the UNIX operating system and of its descendants is written in C. The name C is
doubly appropriate being the successor of B and BCPL.

2. STRUCTURE OF A ‘C’ PROGRAM


The general structure of a C program is depicted in the following figure:

Structure of a C Program
preprocessor directives tells the preprocessor to look for special code libraries, make
substitutions in the code and in other ways prepare the code for translation into machine
language.
Declaration is the program statement that serves to communicate to the language translator
information about the name and type of the data objects needed during program execution.
global declaration is visible to all parts of the program. All functions including main() can be
divided into two sections – local definition and statements.

SVCE Page 1
Unit 2 - IT18101 Programming for Problem Solving
Local definitions would be at the beginning of the functions which is followed by statement
section. It describes the data that will be used in the function.
Statement section consists of the instructions that cause the computer to do something.

3 COMPILATION AND LINKING PROCESSES

There are mainly three steps:


1. Writing the C program
2. Compile the program and
3. Executing it.

For these steps, there requires some software components, namely an operating system, a text
editor, and the C compiler, assembler, and linker. The editor is used to create and modify the
program code while the compiler transforms the source program to object code. Operating
system is responsible for the execution of the program.

Writing or Editing the source program using an text editor or an IDE and saving it with .c
extension. In UNIX or Linux, the most common text editor is the vi editor.

SVCE Page 2
Unit 2 - IT18101 Programming for Problem Solving

Preprocessing is the first phase of the C compilation. It processes include-files, conditional


compilation instructions and macros. The preprocessor is invoked as the first part of your
compiler program’s compilation step.

fig: Typical steps for entering, compiling,and executing C programs

Compilation is the second pass. It takes the output of the preprocessor, and the source code,
and generates assembler source code. The compiler examines each program statement
contained in the source program and checks it to ensure that it conforms to the syntax and
semantics of the language.

Assembly is the third stage of compilation. It takes the assembly source code and produces an
assembly listing with offsets. object file. After the program has been translated into an
equivalent assembly language program, the next step in the compilation process is to translate
the assembly language statements into actual machine instructions. On most systems, the
assembler is executed automatically as part of the compilation process.

SVCE Page 3
Unit 2 - IT18101 Programming for Problem Solving
Linking is the final stage of compilation. After the program has been translated into object
code, it is ready to be linked. The purpose of the linking phase is to get the program into a
final form for execution on the computer.

The process of compiling and linking a program is often called building. The final linked file,
which is in an executable object code format, is stored in another file on the system, ready to
be run or executed.

When the program is executed, each of the statements of the program is sequentially executed
in turn. If the program requests any data from the user, known as input, the program
temporarily suspends its execution so that the input can be entered.

Different types of errors that may occur:


 Compile errors: A compiler error occurs when a given program does not follow the
grammatical rules of the C program.

 Linking errors These are given by the linker or at runtime and ends the program. The
linker can also detect and report errors, for example, if part of the program is missing
or a non-existent library component is referenced.

 Runtime errors An error that occurs during the execution of a program.


 Logical errors: are errors in a program that execute without performing the intended
action.

Removing errors from a program is called debugging. Any type of error in your program is
known as bug.

4. CONVERSION OF SIMPLE ALGORITHM TO PROGRAM


Once the algorithm, for solution of a problem, is formed and represented using any of the
tools like step-form or flowchart or pseudo code, etc., it has to be transformed into some
programming language code. The general procedure to convert an algorithm into a program is
given as follows:
 Code the algorithm into a program—Understand the syntax and control structures
used in the language that has been selected and write the equivalent program
instructions based upon the algorithm that was created.
 Desk-check the program—Check the program code by employing the desk-check
method and make sure that the sample data selected produces the expected output.
 Evaluate and modify, if necessary, the program—Based on the outcome of desk-
checking the program, make program code changes, if necessary, or make changes to
the original algorithm, if need be.
 Do not reinvent the wheel—If the design code already exists, modify it, do not
remake it.
To demonstrate the procedure of conversion from an algorithm to a program in C, an example
is given below.

SVCE Page 4
Unit 2 - IT18101 Programming for Problem Solving
Problem statement Write the algorithm and the corresponding program in C for adding two
integer numbers and printing the result.

Solution
Algorithm
1. START
2. DECLARE A AND B AS INTEGER VARIABLES
3. PRINT “ ENTER TWO NUMBERS ”
4. INPUT A, B
5. R = A + B
6. PRINT “ RESULT = ”
7. PRINT R
8. STOP.

Program in C
int main( )
{
int A, B;
printf(“\n ENTER TWO NUMBERS:”);
scanf(“%d%d”,&A,&B);
R = A + B;
printf(“\n RESULT = ”);
printf(“%d”,R);
return 0;
}

5 CONSTANTS, VARIABLES, DATA TYPES

5.1 Concept Of A Variable


Variables are used for holding data values so that they can be utilized in various
computations in a program.
The C compiler generates an executable code which maps data entities to memory locations.
For example, the variable definition
int salary = 65000;
causes the compiler to allocate a few bytes to represent salary. The exact number of bytes
allocated and the method used for the binary representation of the integer depends on the
specific C implementation.

All variables have three important attributes.


 A data type that is established when the variable is defined, e.g., integer, real,
character. Once defined the type of a C variable cannot be changed.
 A name of the variable
 A value that can be changed by assigning a new value to the variable. The kind of
values a variable can assume depends on its type. For example, an integer variable can
only take integer values, e.g., 2, 100, –12.
A minimum of 31 characters must be supported by a compiler that conforms to the C
language standard, Variable names are case sensitive, which means that the names NUM and
num are distinct.
In C, a variable must be declared before it can be used.

SVCE Page 5
Unit 2 - IT18101 Programming for Problem Solving
5.2 Data Types In C
The type, or data type, or a variable determines a set of values that a variable might take and
a set of operations that can be applied to those values. Data types can be broadly classified as
shown in the below figure.

Fig: Classification of Data types

C has five basic data types and they are as follows:


 character—Keyword used is char
 Integer—Keyword used is int
 floating point—Keyword used is float
 double precision floating point—Keyword used is double
 valueless—Keyword used is void

Fig: Basic/Primitive data types in C

Sizes and ranges of basic data types in C for a 16-bit computer

SVCE Page 6
Unit 2 - IT18101 Programming for Problem Solving

5.3 Constants

Constants are identifiers whose value do not change during program execution.

Declaring constants

Syntax

const datatype var = value;

Usage
for example, const float pi = 3.14156;
specifies that the variable pi can never be changed by the program. Any attempt by code
within the program to alter the value of pi will result in a compile time error. The value of a
const variable must be set at the time the variable is declared
Example
#include <stdio.h>
int main()
{
const int value = 42;
/* constant, initialized integer variable */
value = 100;
/* wrong! − will cause compiler error */
return 0;
}

6. PROGRAM STATEMENT
A statement is a syntactic constructions that performs an action when a program is executed.
All C program statements are terminated with asemi-colon (;). A program statement, in C,
can be classified as

SVCE Page 7
Unit 2 - IT18101 Programming for Problem Solving
6.1 Declaration

Definition:
Declaration is a program statement that serves to communicate to the language translator
information about the name and type of the data objects needed during program execution.

A declaration statement begins with the type, followed by the name of one or more variables.

Syntax
data_type variable_name_1, variable_name_2, ..., variable_name_n;

Usage

int x;
float y;
char c;

The variable x can store a integer value, y can store a floating point value and c can able to
store a single character.

Declaration of multiple variables of the same data types can be done in one statement. For
example,
int a;
int b;
int c;
can be rewritten as int a, b, c;

6.2 Expression statement

Definition
Expression statement is the simplest kind of statement which is no more than an expression
followed by a semicolon. An expression is a sequence of operators and operands that
specifies computation of a value.

Example

x=3+2*10;
y=x+5;
n=n/10;

6.3 Compound statement


Compound statement is a sequence of statements that may be treated as a single statement
in the construction of larger statements.

6.4 Labeled statements


Labeled statements can be used to mark any statement so that control may be transferred to
the statement by switch statement.

6.5 Control statement


Control statement is a statement whose execution results in a choice being made as to which
of two or more paths should be followed. In other words, the control statements determine the

SVCE Page 8
Unit 2 - IT18101 Programming for Problem Solving
‘flow of control’ in a program. The kinds of control flow statements supported by different
languages vary, but can be categorized by their effect:
 continuation at a different statement
 executing a set of statements only if some condition is met
 executing a set of statements zero or more times, until some condition is met
 executing a set of distant statements, after which the flow of control usually returns
 stopping the program, preventing any further execution (unconditional halt).

6.6 Selection statements


Selection statements allow a program to select a particular execution path from a set of one
or more alternatives. Various forms of the if..else statement belong to this category.

6.7 Iteration statements


Iteration statements are used to execute a group of one or more statements repeatedly. while,
for, and do..while statements falls under this group.

6.8 Jump statements


Jump statements cause an unconditional jump to some other place in the program. goto
statement falls in this group.

6.9 Assignment

Syntax
variable_name = expression;

Example
i = 6;
i = i + 1;

The assignment operator replaces the content of the location ‘i’ with the evaluated value of
the expression on its right-hand side. The assignment also acts as an expression that returns
the newly assigned value.

6.10 Initialization
When a variable is declared, the C compiler does not assign any value to the variable, unless
it is instructed to do so.

Syntax
data type variable_name=constant;

Example
int i = 100; /* 100 is an initializer */

SVCE Page 9
Unit 2 - IT18101 Programming for Problem Solving

7. OPERATORS IN C
An operator is a symbol that specifies the mathematical, logical, or relational operation to be
performed.

Classification of operators in C language

SVCE Page 10
Unit 2 - IT18101 Programming for Problem Solving

Different operators in C

SVCE Page 11
Unit 2 - IT18101 Programming for Problem Solving

7.1 Arithmetic Operators in C

There are three types of arithmetic operators in C: binary, unary, and ternary. Binary
operators C provides five basic arithmetic binary operators as shown in figure.

The remainder operator (%) always expects integers for both of its operands.

Unary operators The unary ‘–’ operator negates the value of its operand

Unary increment and decrement operators The unary ‘++’ and ‘--’ operators increment or
decrement the value in a variable by 1. There are ‘pre’ and ‘post’ variants for both operators
that do slightly different things as explained below.

var++ increment ‘post’ variant; var-- decrement ‘post’ variant


++var increment ‘pre’ variant ; --var decrement 'pre’ variant

Example
The following example illustrate the use of increment and decrement the value in a variable
by 1;

int i = 42;
i++; /* increment contents of i, same as i = i + 1; i is now 43 */

i-- ; /* decrement contents of i, same as i = i – 1; i is now 42 */

++i; /* increment contents of i, same as i = i + 1; i is now 43 */

--i; /* decrement contents of i, same as i = i – 1; i is now 42 */

Basic Rules for using ++ and -- operators


 The operand must be a variable but not a constant or an expression.
 The operator ++ and -- may precede or succeed the operand.

SVCE Page 12
Unit 2 - IT18101 Programming for Problem Solving
Pre and post variations of ++ and -- operators:

7.2 Relational Operators in C


C provides six relational operators for comparing numeric quantities. Relational operators
evaluate to 1, representing the true outcome, or 0, representing the false outcome.

SVCE Page 13
Unit 2 - IT18101 Programming for Problem Solving
7.3 Logical Operators in C
C provides three logical operators for forming logical expressions. Like the relational
operators, logical operators evaluate to 1 or 0. Logical negation is a unary operator that
negates the logical value of its single operand. If its operand is non-zero, it produces 0, and if
it is 0, it produces 1. Logical AND produces 0 if one or both its operands evaluate to 0.
Otherwise, it produces 1. Logical OR produces 0 if both its operands evaluate to 0.
Otherwise, it produces 1.

7.4 Bitwise Operators in C


C provides six bitwise operators for manipulating the individual bits in an integer quantity.
Bitwise operators expect their operands to be integer quantities and treat them as bit
sequences. Bitwise negation is a unary operator that complements the bits in its operands.
Bitwise AND compares the corresponding bits of its operands and produces a 1 when both
bits are 1, and 0 otherwise. Bitwise OR compares the corresponding bits of its operands and
produces a 0 when both bits are 0, and 1 otherwise. Bitwise exclusive or compares the
corresponding bits of its operands and produces a 0 when both bits are 1 or both bits are 0,
and 1 otherwise.

The general form of the right shift statement is


variable_name >> number of bit positions;
and that of the left shift statement is
variable_name << number of bit positions;

SVCE Page 14
Unit 2 - IT18101 Programming for Problem Solving

7.5 Conditional Operator in C


The conditional operator has three expressions.

Syntax
expression1 ? expression2 : expression3

Usage
First, expression1 is evaluated; it is treated as a logical condition. If the result is non-zero,
then expression2 is evaluated and its value is the final result. Otherwise, expression3 is
evaluated and its value is the final result.
Example
int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */

7.6 Comma Operator


This operator allows the evaluation of multiple expressions, separated by the comma, from
left to right in order and the evaluated value of the rightmost expression is accepted as the
final result.

Syntax
expressionM = (expression1, expression2, …,expressionN);
Example
int i = 0;
int j;
j = (i += 1, i += 2, i + 3);

In this example, the comma operator is used with three expressions on the right hand side of
the assignment operator.Hence, the comma operator takes these three expressions and
evaluates them from left to right and returns the value of the rightmost expression. Thus, in
this example, the operator first evaluates “i += 1” which increments the value of i. Then the
next expression “i += 2” is evaluated which adds 2 to i, leading to a value of 3. The third
expression is evaluated and its value is returned as the operator’s result. Thus, j is assigned a
value of 6.

7.7 sizeof Operator


C provides a useful operator, sizeof(), for findng the size of memory allocated to any data
item or type. It takes a single operand that may be a type name (e.g., int) or an expression
(e.g., 100) and returns the size of the specified entity in bytes. The outcome is totally
machine-dependent.

#include <stdio.h>
main()
{
printf(“char size = %d bytes\n”, sizeof(char));
printf(“int size = %d bytes\n”, sizeof(int));
printf(“long size = %d bytes\n”, sizeof(long));
printf(“fl oat size = %d bytes\n”, sizeof(float));
printf(“double size = %d bytes\n”, sizeof(double));
printf(“HELLO size = %d bytes\n”, sizeof(“HELLO”));
}

SVCE Page 15
Unit 2 - IT18101 Programming for Problem Solving
Output
char size = 1 bytes
int size = 2 bytes
long size = 4 bytes
float size = 4 bytes
double size = 8 bytes
HELLO size = 6 bytes

7.8 Expression Evaluation—Precedence and Associativity


There is no BODMAS rule in C language as found in algebra. Operators have rules of
precedence and associativity that are used to determine how expressions are evaluated. When
there is more than one operator occurring in an expression, it is the relative priorities of the
operators with respect to each other that will determine the order in which the expression will
be evaluated. This priority is known as precedence.

Consider the following expression:

4+3*2

the operator ‘*’ has higher precedence than ‘+’, causing the multiplication to be executed
first, then the addition. Hence, the value of the expression is 10. An equivalent expression is
4 + (3 * 2)

Precedence and associativity of operators

SVCE Page 16
Unit 2 - IT18101 Programming for Problem Solving
8. MANAGING INPUT AND OUTPUT OPERATIONS

To accomplish a task. it is necessary to read data from the keyboard and display data on the
screen.C provides several functions that gives different levels of input and output capability.
The input and output functions in C are built around the concept of a set of standard data
streams being connected from each executing program to the basic input/output devices.
The <stdio.h> header file contains the various declarations necessary for the functions
together with the macros and type declarations needed for input and output functions. The
input/ output functions fall into two categories: non-formatted read (input) and display
(output) functions and formatted read (input) and display (output) functions.

8.1 NON-FORMATTED INPUT AND OUTPUT

These can handle one character at a time. For output functions, it prints a single character on
the console.

Single Character Input and Output


A number of functions provide for character-oriented input and output. The declarations
format of two of these are given as follows:

int getchar(void); //function for character input


int putchar(int c); //function of character output

getchar() is an input function that reads a single character from the standard input device,
normally a keyboard. putchar() is an output function that writes a single character on the
standard output device, the display screen. There are two other functions, gets() and puts(),
that are used to read and write strings from and to the keyboard and the display screen
respectively. A string may be defined as an arranged collection of characters.

The getchar() input function reads an unsigned char from the input stream stdin. To read a
single character from the keyboard, the general form of the statement used to call the
getchar() function is given as follows:

char_variable = getchar();

where char_variable is the name of a variable of type char. The getchar()input function
receives the character data entered, through the keyboard, and places it in the memory
location allotted to the variable char_variable. The following code

int ch;
ch = getchar();

places the character read from the keyboard in the lower byte of the variable named ‘ch’.

putchar() writes a character to the stdout data stream. To write a single character on the
screen, the general form of the statement used to call the putchar() function is given as
follows:

putchar(char_variable);

SVCE Page 17
Unit 2 - IT18101 Programming for Problem Solving
where char_variable is the name of a variable that is of type char. The character data stored in
the memory location, allotted to the variable char_variable, is displayed on the display screen.

getch() This input function reads, without echoing on the screen, a single character from the
keyboard and
immediately returns that character to the program.

General statement form:


ch = getch(); /* ‘ch’ is a character variable */

getche() This input function reads, with echo on the screen, a single character from the
keyboard and immediately returns that character to the program.

General statement form:


ch = getche(); /* ‘ch’ is a character variable */

putch() This output function writes the character directly to the screen. On success, the
function putch() returns the character printed. On error, it returns EOF. General statement
form:
putch(ch); /* ‘ch’ is a character variable */

When used in programs, the above functions require the header file conio.h to be included.

8.2 FORMATTED INPUT AND OUTPUT FUNCTIONS


When input and output is required in a specified format, the standard library functions scanf()
and printf() are used. The scanf() function allows the user to input data in a specified format.
It can accept data of different data types. The printf() function allows the user to output data
of different data types on the console in a specified format.

8.2.1 Output Function printf ( )

Syntax

printf(“control_string”,variable1,variable2,variable3,...);

where the ‘...’ means a list of variables that can be written separated by commas.

The control string in printf(), enclosed in quotation marks, has three types of objects:
 Ordinary characters/text messages.
 Conversion specifier/format specifier field.
 Control code/ Escape sequence.

Conversion specifier/format specifier field:

%[flags][width][.precision][length modifier]type specifier

Flags

SVCE Page 18
Unit 2 - IT18101 Programming for Problem Solving
Flag is an optional argument which specifies output justification such as
numerical sign, trailing zeros or octal, decimal, or hexadecimal prefixes. Table shows the
different types of flags with their description.
Flags Descriptions
- Left justify with the given field width
+ Display the data with its numerical sign
# Used to provide additional specifiers like
o-octal,
x/X/0x/0X-hexa decimal values
0 The number is padded with zeros instead of spaces.

Width
Width is an optional arguement which specifies the minimum number of
positions in the output. If data needs more space than specified, then printf overrides the
width specified by the user. If the number of output characters is smaller than the specified
width, then the output is right justified with blank spaces to the left.
Precision
Precision is optional arguement which specifies the number of decimal places
to be printed for a floating point number.
Length Modifiers

Type specifier/Conversion code

Code Qualifying input


c Single character
d Integer values
f Floating Point values
E,e Floating Point value in exponential form
o Octal numbers
X,x Hexa decimal values
u Unsigned integer values
s Sequence of characters or strings
List of commonly used escape sequences

SVCE Page 19
Unit 2 - IT18101 Programming for Problem Solving
Example

printf(“number=%3d\n”, 10);
printf(“number=%2d\n”, 10);
printf(“number=%1d\n”, 10);
printf(“number=%7.2f\n”, 5.4321);
printf(“number=%.2f\n”, 5.4391);
printf(“number=%.9f\n”, 5.4321);
printf(“number=%f\n”, 5.4321);

The output of these statements in order are:

8.2.2 Input Function scanf ( )

The scanf() function works in much the same way as the printf().

Syntax:
scanf(“control_string”,variable1_address,variable2_address,...);

where the control string, also known as format string is a list of format specifiers indicating
the format and type of data to be read from the standard input device, which is the keyboard,
and stored in the corresponding address of variables. There must be the same number of
format specifiers and addresses as there are input fields.

Parts of conversion specifier field for scanf()

Format Specifiers for scanf()

The format string in scanf() has the following general form:

“< character string >< % conversion specifier field >”

SVCE Page 20
Unit 2 - IT18101 Programming for Problem Solving
Here character string is optional and has to be used with care. Each ‘conversion specifi er
field’ is coded as follows:

%[*]<width><size><conversion-code>

Each conversion (or format) specifi er begins with the percent character, %, after which
come the following, in the given order.
1. An optional assignment-suppression character, *,which states that the value being read will
not be assigned to an argument, but will be dropped.
2. An optional width specifi er, <width>, which designates the maximum number of
characters to be read that compose the value for the associated argument. Encountering white
space, before the entire width is scanned, terminates the input of this value and moves to the
next.
3. An optional conversion-code modifi er, <size>, which modifies the conversion code to
accept format for a type of :
h = short int,
l = long int, if the format specifi ers provide for an integer conversion,
l = double, if the format specifiers provide for a floating-point conversion, and
L = long double, which is valid only with floatingpoint conversions.

Add two integer numbers and print the input numbers and result.
Solution
#include <stdio.h>
main()
{
int a,b,c;
printf(“\nThe first number is ”);
SVCE Page 21
Unit 2 - IT18101 Programming for Problem Solving
scanf(“%d”,&a);
printf(“\nThe second number is ”);
scanf(“%d”,&b);
c=a+b;
printf(“The answer is %d \n”,c);
}
Output:
The first number is 5
The second number is 9
The answer is 14

9. CONTROL STATEMENTS
Control statements embody the decision logic that tells the executing program what action to
carry out next depending on the values of certain variables or expression statements.The
control statements include selection, iteration, and jump statements that work together to
direct program flow.

Program control statements/constructs in C

Specifying Test Condition For Selection And Iteration


A test condition used for selection and iteration is expressed as a test expression. If an
expression evaluates to true, it is given the value of 1. If a test expression evaluates to false, it
is given the value of 0.

Relational expression can be formed using relational operators. A relational operator takes
two operands and compares them to each other, resulting in a value of true (1) or false (0).
The syntax for relational expression is as follows:

SVCE Page 22
Unit 2 - IT18101 Programming for Problem Solving
The relational operators may be used with integer, float, double, or character operands.
Some examples of expressions are given below.
a>2
a<b+c
a == 3
a! = 0
a <= b
a >= 2

9.1 SELECTION/BRANCHING STATEMENT

A selection statement is a control statement that allows choosing between two or more
execution paths in a program. The selection statements in C are the if statement, the ifelse
statement, and the switch statement. These statements allow us to decide which statement to
execute next. Each decision is based on a boolean expression (also called a condition or test
expression), which is an expression that evaluates to either true or false. The result of the
expression determines which statement is executed next.

When dealing with selection statements, there are generally three versions: one-way, two-
way, and multiway. One-way decision statements do a particular thing or they do not. Two-
way decision statements do one thing or do another. Multi-way decision statements can do
one of many different things depending on the value of an expression.

9.1.1 One way decision using if statement

One-way decisions are handled with an if statement that either do some particular thing or do nothing at
all. The decision is based on a ‘test expression’ that evaluates to either true or false. If the test expression
evaluates to true, the corresponding statement is executed; if the test expression evaluates to false, control
goes to the next executable statement.

Syntax
if(TestExpr)
{
stmtT;
}

TestExpr is the test expression. stmtT can be a simple statement or a block of statements
enclosed by curly braces {}.

Flowchart for if construct

SVCE Page 23
Unit 2 - IT18101 Programming for Problem Solving
Example:

To check whether the person is eligible for voting

#include<stdio.h>
main()
{
int age;
printf("enter your age\n");
scanf("%d",&age);
if (age >= 18)
{
printf("You are eligible for voting");
}
}
Output 1
Enter your age:28
you are elgible for voting
Output 2
Enter your age:8

9.1.2 Two-way decisions using if-else statement

Two-way decisions are handled with if-else statements that either do one particular thing or
do another. Similar to one-way decisions, the decision here is based on a test expression.

Syntax
if(TestExpr)
{
stmtT;
}
else
{
stmtF;
}

Flowchart for if-else construct

SVCE Page 24
Unit 2 - IT18101 Programming for Problem Solving
Example:

To check whether the person is eligible for voting or not

#include<stdio.h>
main()
{
int age;
printf("enter your age\n");
scanf("%d",&age);
if (age >= 18)
{
printf("You are eligible for voting");
}
else
{
printf("You are not eligible for voting");
}

Output 1
Enter your age:28
You are eligible for voting
Output 2
Enter your age:8
You are not eligible for voting

9.1.3 Two-way decisions using Conditional Operator


Consider the situation in which there are two or more alternatives for an expression. Such a
situation can be handled using conditional operator.

Syntax

expr1 ? expr2 : expr3

It executes by first evaluating expr1, which is normally a relational expression, and then
evaluates either expr2, if the first result was true, or expr3, if the first result was false.

Example:
Finding largest of two numbers using conditional operator

#include <stdio.h>
int main()
{
int a,b,c;
printf(“\n ENTER THE TWO NUMBERS: ”);
scanf(“%d %d”, &a, &b);
c=a>b?a:b;
printf(“\n LARGER NUMBER IS %d”,c);
return 0;
}

SVCE Page 25
Unit 2 - IT18101 Programming for Problem Solving

Output 1
ENTER THE TWO NUMBERS: 5 7
LARGER NUMBER IS 7

Output 2
ENTER THE TWO NUMBERS: 15 7
LARGER NUMBER IS 15

9.1.3 Multi-way decisions using if-else-if ladder

Multi-way decision statements use if-else-if nested if or switch statements. They are used to
evaluate a test expression that could have several possible values. if-else-if statements are
often used to choose between ranges of values.

Syntax

if(TestExpr1)
stmtT1;
else if(TestExpr2)
stmtT2;
else if(TestExpr3)
stmtT3;
...
else if(TestExprN)
stmtTN;
else
stmtF;

Flowchart of an if-else-if construct

SVCE Page 26
Unit 2 - IT18101 Programming for Problem Solving
Example
To check whether the given character is alphabet, digit or special character
#include <stdio.h>
int main()
{
char c;
printf("Enter a character:");
c=getchar();
if (c>='A' && c<='Z')|| (c>='a' && c<='z')
{
printf("Alphabet");
}
elseif (c>='0' && c<='9')
{
printf("Digit");
}
else
{
printf("Special Character");
}
}
Output 1
Enter a character:f
Alphabet
Output 2
Enter a character:9
Digit
Output 3
Enter a character:$
Special Character

Nested if
When any if statement is written under another if statement, this cluster is called a nested if.
A simple illustration of a nested if is given below.
The if statement that tests for divisibility by 5 is located inside of the if statement that tests
for divisibility by 3 therefore it is considered to be a nested if statement.

if (number % 3 == 0)
{
printf(“number is divisible by 3. \n”);
if (number % 5 == 0)
{
printf(“number is divisible by 3 and 5. \n”);
}
}

9.1.3 Multi-way decisions using switch Statement


When there are a number of else alternatives as above, another way of representing this
multi-way selection is by the switch statement.

The switch statement is used to pickup or execute a particular group of statements from
several available group of statements. It allows us to make a decision from the number of

SVCE Page 27
Unit 2 - IT18101 Programming for Problem Solving
choices.It is a multiway decision statement, it tests the value of given variable or expression
against a list of “case” values and when a match is found, a block of statements associated
with that “case” is executed.

Syntax

switch(expr)
{
case constant1:
stmtList1;
break;
case constant2:
stmtList2;
break;
case constant3:
stmtList3;
break;
………………………….
………………………….
default:
stmtListn;
}

The switch statement evaluates the expression and then looks for a matching case label. If
none is found, the default label is used. If no default is found, the statement does nothing.

SVCE Page 28
Unit 2 - IT18101 Programming for Problem Solving
The following is an example where the control expression is a character variable grade.

switch(grade)
{
case ‘O’:
printf(“Outstanding”);
break;
case ‘A’:
printf(“Excellent”);
break;
case ‘B’:
printf(“Very Good”);
break;
case ‘C’:
printf(“Good”);
break;
case ‘D’:
printf(“Fair”);
break;
case ‘F’:
printf(“Fail”);
break;
default:
printf(“Illegal entry”);
break;
}
Example
Simple Calculator using switch-case
#include <stdio.h>
int main()
{
int n1,n2,result;
char c;
printf("Enter the operation to be performed + - * /: ");
c=getchar();
printf("Enter the first number:");
scanf("%d",&n1);
printf("Enter the second number:");
scanf("%d",&n2);
switch(c)
{
case ‘+’:
res=n1+n2;
printf(“Result = %d”,res);
break;
case ‘-’:
res=n1+n2;
printf(“Result = %d”,res);
break;
case ‘*’:
res=n1*n2;
printf(“Result = %d”,res);

SVCE Page 29
Unit 2 - IT18101 Programming for Problem Solving
break;
case ‘/’:
res=n1/n2;
printf(“Result = %d”,res);
break;
default:
printf(“Illegal entry”);
break;
}
}
Output 1
Enter the operation to be performed + - * /:+
Enter the first number:5
Enter the second number:7
Result =12
Output 1
Enter the operation to be performed + - * /:%
Illegal entry

9.2 ITERATION AND REPETITIVE EXECUTION


A loop allows one to execute a statement or block of statements repeatedly. C has has three
loop constructs: while, for and do-while.

9.2.1 While Construct


while statement is a pre-test loop. It uses a test expression to control the loop. Since it is a
pre-test loop, it evaluates the test expression before every iteration of the loop.

stmT will be executed repeatedly till the value of TestExpr becomes 0. stmT may be a single
statement or multiple statements terminated by a semicolon. To use the while statement, the
test expression should contain a loop control variable. The initialization of the loop control
variable has to be done before the loop starts and updating must be included in the body of
the loop. The expanded form of the while statement is the figure.

SVCE Page 30
Unit 2 - IT18101 Programming for Problem Solving

Example

#include <stdio.h>
main()
{
int c;
c=5; // Initialization
while(c>0) // Test Expression
{
printf(“ \n %d”,c);
c=c-1; // Updating
}
}

This loop contains all the parts of a while loop. When executed in a program, this loop will
output
5
4
3
2
1

9.2.2 for Construct


A loop formed by using the for statement is generally called a determinate or defi nite loop
because the programmer knows exactly how many times it will repeat. The number of
repetitions can be determined mathematically by manually checking the logic of the loop.

Syntax

for(initialization; TestExpr; updating)


{
stmT;
}

Initialization
This part of the loop is the first to be executed. The statement(s) of this part are
executed only once. This statement involves a loop control variable.

SVCE Page 31
Unit 2 - IT18101 Programming for Problem Solving
TestExpr
TestExpr represents a test expression that must be true for the loop to continue
execution.
stmT
stmT is a single or block of statements.
Updating
The statements contained here are executed every time through the loop before the
loop condition is tested. This statement also involves a loop control variable.

Flowchart of for loop

Example
#include<stdio.h>
main()
{
int i;
for(i = 0; i < 10; i++)
{
printf(“%d ”,i);
}
}
Output
0123456789

The above for loop operates as follows:


1. Set i equal to 0
2. If i is less than 10, execute the body of the loop, that is, ‘printf’ and go to step3;
otherwise, go to the next instruction after the for loop and continue.
3. Increment i
4. Go to step 2

The following figure explains the three expressions in the for loop used in the above program
that are separated by semicolons and that control the operation of the loop.

SVCE Page 32
Unit 2 - IT18101 Programming for Problem Solving

9.2.3 do-while Construct


do-while is a post-test loop, the code is always executed once. At the completion of the loop
code, the test expression is tested. If the test expression evaluates to true, the loop repeats; if
the expression is false the loop terminates.

The do keyword is placed on a line of code at the top of the loop. A block of statements
follows it with a test expression after the keyword while, at the bottom of the loop.

Syntax
do
{
stmT; /* body of statements would be placed here*/
}while(TestExpr);

The test expression TestExpr must evaluate to ‘true’ for the do-while loop to iterate after the
first time. StmT may be a single statement or a block of statements. The main difference
between the while and do-while loop is the placement of the test expression.

Since the do-while has the test expression at the end of the loop, it is guaranteed that the body
of the loop will execute at least once. In the while loop, it is possible to come upon a
condition that is not satisfied and hence does not enter the loop.

Flowchart of do-while

SVCE Page 33
Unit 2 - IT18101 Programming for Problem Solving
Example

#include <stdio.h>
main()
{
int c=5;
while(c<5)
{
printf(“ Hello”);
c++;
}
}

Output:

The program will print nothing. As the condition c<5 fails, neither the printf() statement nor
c++ will be executed.

#include <stdio.h>
main()
{
int c=5;
do
{
printf(“Hello”);
c++;
} while(c<5);
}
Output:
Hello
Here the statements within the loop are executed at least once.

9.2.4 Which loop to be used?


The while and for constructs are pre-test loops and the do-while construct is post-test loop.
The while and do-while loops are event-controlled whereas the for loop is counter-controlled.
The for loop is appropriate when one knows in advance how many times the loop will be
executed. The while and do-while loops are used when it is not known in advance when the
loop should terminate;the while loop is used when one may not want to execute the loop body
even once, and the do-while loop when one wants to execute the loop body at least once.

9.3 goto Statement

The goto statement is another type of control statement supported by C. The control is
unconditionally transferred to the statement associated with the label specified in the goto
statement.
Syntax
goto label_name;

A statement label is defined in exactly the same way as a variable name, which is a sequence
of letters and digits, the fi rst of which must be a letter. The statement label must be followed
by a colon (:).

SVCE Page 34
Unit 2 - IT18101 Programming for Problem Solving

The following program is used to find the factorial of a number.

#include <stdio.h>
int main()
{
int n, c;
int f=1;
printf(“\n Enter the number:”);
scanf(“%d”,&n);
if(n<0) goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“\n FACTORIAL IS %ld”, f);
end:
return 0;
}

9.4 SPECIAL CONTROL STATEMENTS

There are certain control statements, which terminate either a loop or a function. There are
three such statements namely: return, break, and continue.

9.4.1 return Statement


The return type is used in the definition of a function to set its returned value and the return
statement is used to terminate execution of the function.

Syntax
return;
return expression;

9.4.2 break Statement


The break statement is used in loop constructs such as for, while and do-while, and switch
statement to terminate execution of the loop or switch statement.

Syntax
break;

SVCE Page 35
Unit 2 - IT18101 Programming for Problem Solving
After a break statement is executed within a loop or a case in a switch construct, execution
proceeds to the statement that follows the loop construct or switch statement. The following
is an example of the use of a break statement.

#include <stdio.h>
int main( )
{
int c=1;
for(;c<=5;c++)
{
if(c==3)
break;
printf(“\t %d”, c);
}
return 0;
}
The program will print 1 2 instead of 1 2 3 4 5.

9.4.3 continue Statement


The continue statement does not terminate the loop but goes to the test expression in the
while and do-while statements and then goes to the updating expression in a for statement.

Syntax:
continue;

SVCE Page 36
Unit 2 - IT18101 Programming for Problem Solving
Example
#include <stdio.h>
int main()
{
int c=1;
while(c<=5)
{
if(c==3) continue;
printf(“\t %d”, c);
c++;
}
return 0;
}
Output: 1 2 4 5

9.4.4 Difference Between break and continue

9.5 NESTED LOOPS

A nested loop refers to a loop that is contained within another loop. If the program has to
repeat a loop more than once, it is a good candidate for a nested loop. In nested loops, the
inside loop (or loops) executes completely before the outside loop’s next iteration. It must be
remembered that each inner loop should be enclosed completely in the outer loop;
overlapping loops are not allowed.

Example
for(count = 1; count < 100; count++)
{
do
{
/* the do...while loop */
}while(x != 0);
} /* end of for loop */

An example of the nested loop is to print the following:


*
**
***
****

SVCE Page 37
Unit 2 - IT18101 Programming for Problem Solving
In each row, there are several ‘ *’ to be printed. In row one, one star has to be printed; in row
two, two stars have to be printed; in row three, three stars have to be printed, and so on. So an
outer loop is required to keep track of the number of rows to be printed and in each iteration
of the outer loop, an inner loop is required to keep track of the printing of stars that
corresponds to the row.

Program using nested for loop

#include <stdio.h>
int main()
{
int row,col;
for(row=1;row<=4;++row)
{
for(col=1;col<=row;++col)
{
printf(“* \t”);
}
printf(“\n”);
}
return 0;
}

SVCE Page 38
Unit 3 Arrays IT18101-Programming for Problem solving
Unit III
Arrays and Strings
SYLLABUS
Arrays – Initialization – Declaration – One dimensional and Two dimensional arrays - String- String
operations –Arrays of strings.

1. INTRODUCTION TO ARRAYS

An array can be defined as a data structure consisting of an ordered set of data values of the
homogeneous (same) type. An array is a collection of individual data elements that is
 Ordered—one can count off the elements 0, 1, 2, 3, ...
 Fixed in size
 Homogeneous—all elements have to be of the same type, e.g., int, float, char,

An array is also a sequential data structure which means all the elements are stored in sequential
memory order.
Each value in an array is called an element of the array. The elements of the array share the same
variable name but each element has its own unique index number.

In C, arrays are of two types: one-dimensional and multidimensional. The number of subscript or index
determines dimensions of the array. An array of one dimension is known as a one-dimensional array or
1-D array, while an array of two dimensions is known as a two-dimensional array or 2-D array.

2. ONE-DIMENSIONAL ARRAY
Conceptually you can think of a one-dimensional array as a row, where elements are stored one after
another as shown in the figure.

Since the array is one dimensional, there will be a single subscript or index whose value refers to the
individual array element which ranges from 0 to (n–1), where n is the total number of elements in the
array.

2.1 Declaration of a One-dimensional Array

To use an array variable in a program, it must be declared. When defining an array in a program, three
things needs to be specified.

SVCE Page 1
Unit 3 Arrays IT18101-Programming for Problem solving
 the type of data it can hold, i.e., int, char, double, float, etc.
 the number of values it can hold, i.e., the maximum number of elements it can hold
 a name

Syntax
data_type array_name [SIZE];

 All the array elements hold values of type <data type>


 The size of the array is indicated by <SIZE>, the number of elements in the array. <SIZE> must
be an int constant or a constant expression.
 lower bound = 0
 upper bound = size –1
 size = upper bound + 1

Example

a) int x[7];

This statement declares a one-dimensional array named x having 7 elements, each of type int.

b) float num[100], min, max;

This statement declares three entities of type float: an array nurn having 100 elements and scalar
variables min and max.

c) #define MAX_SUB 5

int mark[MAX_SUB];

This example first defines a symbolic constants MAX_SUB with value 6 followed by a one
dimensional array named marks of type int and size 6. This array can be used to store the marks of a
student in six subjects.

2.2 Initializing Array values

2.2.1 Compile Time Intialization

Variables can be assigned values during declaration like the following example.
int x = 7;

SVCE Page 2
Unit 3 Arrays IT18101-Programming for Problem solving
Arrays can be initialized in the same manner. However, since an array has multiple elements, braces
are used to denote the entire array of values and commas are used to separate the individual values
assigned to the elements in the array initialization statements as shown.

Example

Automatic sizing

While initializing, the size of a one dimensional array may be omitted:


int arr[] = {3,1,5,7,9};

Here, the C compiler will deduce the size of the array from the initialization statement. From the above
initialization statement, the size of the array is deduced to be 5.

2.2.2 Run time intialization

Arrays can be declared and initialized during run time by getting the size and elements of an array from
the user as shown in below code

#include<stdio.h>
main()
{
int i,n;
printf("Enter the size of an array: ");
scanf("%d",&n);
int a[n];
for (i=0;i<n;i++)
{
printf("Enter the %d element: ",i);
scanf("%d",&a[i]);
}
}

Output
Enter the size of an array:5
Enter the 0 element: 10
Enter the 1 element: 25
Enter the 2 element: 15
Enter the 3 element: 17
Enter the 4 element: 20

SVCE Page 3
Unit 3 Arrays IT18101-Programming for Problem solving
During Program execution, sequence memory defined by the user and the values are assigned as shown
below:
a[0] a[1] a[2] a[3] a[4]
10 25 15 17 20

2.2.3 Accessing Array Elements

The elements of an array can be accessed by their indices.


Suppose an array named mark is declared as

int mark[5];

The first element is mark[0], second element is mark[1] and so on.

Few key notes:


 Arrays have 0 as the first index not 1. In this example, mark[0]

 If the size of an array is n, to access the last element, (n-1) index is used. In this example,
mark[4]

 Suppose the starting address of mark[0] is 2120. Then, the next address, a[1], will be 2122,
address of a[2] will be 2124 and so on. It's because the size of a int is 2 bytes.

Example Operations in an array

These operations include the following, for an array named ‗ar‘.

(a) To increment the ith element, the given statements can be used.

ar[i]++;
ar[i] += 1;
ar[i] = ar[i] + 1;

(b) To add n to the ith element, the following statements may be used,

ar[i] += n;
ar[i] = ar[i] + n;

(c) To copy the contents of the ith element to the kth element, the following statement may be written.

ar[k] = ar[i];

SVCE Page 4
Unit 3 Arrays IT18101-Programming for Problem solving

(d) To copy the contents of one array ‗ar‘ to another array ‗br‘, it must again be done one by one.

int ar[10],br[10];
for(i = 0; i < 10; i = i + 1)
br[i] = ar[i];

(e) To exchange the values in ar[i] and ar[k], a ‗temporary‘ variable must be declared to hold one
value, and it should be the same data type as the array elements being swapped. To perform this task,
the following C statements are written

int temp;
temp = ar[i]; /* save a copy of value in ar[i] */
ar[i] = ar[j]; /* copy value from ar[j] to ar[i] */
ar[j] = temp; /* copy saved value of ar[i] to ar[j] */

(f) Storing values given by the user in an array Reading the input into an array is done as shown.

int a[10]; /* an array with 10 ―int‖ elements */


int i;
for(i=0 ; i< 10; i++)
{
scanf(“%d”, &a[i]);
}

(g) Printing an array The following code segment prints the elements of an array, a[10].

for(i=0 ; i< 10; i++)


{
printf(“%d”, a[i]);
}

(h) Initialization of all of the elements of the sample array to 0

for(i = 0; i < 5; i++)


{
a[i] = 0;
}

(i) To find the sum of elements of an array

#include<stdio.h>
main()
{
int i,n,sum;
int a[10];
SVCE Page 5
Unit 3 Arrays IT18101-Programming for Problem solving
printf("Enter the size of an array: ");
scanf("%d",&n);

for (i=0;i<n;i++)
{
printf("Enter the %d element: ",i);
scanf("%d",&a[i]);
}

sum = 0; /*initialize total to zero */

for(i = 0; i <n;i++)
{
sum = sum + a[i]; /* add in a number */
/*sequentially retrieve each array element and adds the element to the
sum. */
}
printf("Sum of elements of an array is %d",sum);
}

2.3 MULTIDIMENSIONAL ARRAYS

A multi-dimensional array is an array that has more than one dimension. It is an array of arrays; an
array that has multiple levels.

2.3.1 Two- Dimensional Arrays

The simplest multi-dimensional array is the 2D array, or two-dimensional array. It is technically an


array of arrays. A 2D array is also called a matrix, or a table of rows and columns.

Declaration of 2D array

Declaring a multi-dimensional array is similar to the one-dimensional arrays. For a 2D array, we


need to tell C that we have 2 dimensions.

Syntax
data_type array_name[size1][size2];

Here, data_type is the name of some type of data, such as int. Also, size1 and size2 are the sizes of the
array‘s first and second dimensions, respectively.

Example
int two_d[3][3];

SVCE Page 6
Unit 3 Arrays IT18101-Programming for Problem solving
In the example,a 2D array is created with three rows and three columns. The array looks like the
following table.

Column 0 Column 1 Column 2


Row 0 two_d[0][0] two_d[0][1] two_d[0][2]
Row 1 two_d[1][0] two_d[1][1] two_d[1][2]
Row 2 two_d[2][0] two_d[2][1] two_d[2][2]
Intialization of 2D array

There are more than one way to intialize a 2D array:

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Accessing a 2D array

The elements of a multidimensional array are stored contiguously in a block of computer memory. In
scanning this block from its start to its end, the order of storage is such that the last subscript of the
array varies most rapidly whereas the first varies least rapidly. For instance, the elements of the two-
dimensional array x[2][2] are stored in the order: x[0][0], x[0][1], x[1][0], x[1][1].

Example

#include <stdio.h>
main()
{
int i,j;
int a[3][2] = {{4,7},{1,0},{6,2}};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 2; j++)
{
printf(―%d\t‖, a[i][j]);
}
printf(―\n‖);
}
}

SVCE Page 7
Unit 3 Arrays IT18101-Programming for Problem solving
Since computer memory is essentially one-dimensional with memory locations running straight from 0
up through the highest, a multidimensional array cannot be stored in memory as a grid. Instead, the
array is dissected and stored in rows. Consider the following two-dimensional array.

In the computer, the above array actually ‗looks‘ like this.

2.3.2 Three-dimensional Array

A 3D array is an array of arrays of arrays! It is a matrix, but with a third dimension added, like a Rubix
cube.

Declaration of 3D array

A three-dimensional array require three sizes one for each dimension

Syntax
data_type array_name[size1][size2][size3]

Example
int non_cube[2][6][8];

SVCE Page 8
Unit 3 Arrays IT18101-Programming for Problem solving
Initialization of a 3D Array

int a[2][2][2] = {{ {1,1},{1,2}},


{ {2,1},{2,3}}
};

Accessing 3D array
The following program is an example to store values entered by the user in a three-dimensional array
and display it.
#include <stdio.h>
int main()
{
// this array can store 12 elements

int i, j, k, test[2][3][2];

printf("Enter 12 values: \n");

for(i = 0; i < 2; ++i)


{
for (j = 0; j < 3; ++j)
{
for(k = 0; k < 2; ++k )
{
scanf("%d", &test[i][j][k]);
}
}
}

// Displaying values with proper index.

printf("\nDisplaying values:\n");

for(i = 0; i < 2; ++i) {


for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

return 0;
}

SVCE Page 9
Unit 3 Arrays IT18101-Programming for Problem solving
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12

Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

SVCE Page 10
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Unit 3 Arrays and Strings


Syllabus

Arrays – Initialization – Declaration – One dimensional and Two dimensional arrays - String-
String operations –Arrays of strings.

1. STRINGS

Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the null character, which is a character all of whose bits are zero.The null or
string-terminating character is represented by another character escape sequence, \0.

1.1 Declaration of a String


Strings can be declared like one-dimensional arrays. For example,
char str[30];
char text[80];

1.2 String Initialization


Character arrays or strings allow a shorthand initialization, for example,
char str[9] = “I like C”;
which is the same as char str[9] = {„I‟,„ ‟,„l‟,„i‟,„k‟,„e‟,„ ‟,„C‟,„\0‟};

Whenever a string, enclosed in double quotes, is written, C automatically creates an array of


characters containing that string, terminated by the \0 character. C language allows the
alternative notation
char msg[] = “Hello”;

1.3 Printing Strings

Strings can be displayed on screen using different ways as described in the below table:

Function Syntax Example Description


printf() printf(“%s”,strname); char s1[100]=”helloworld”; Strings can be
printf(“%s”,s1); displayed using
printf by specifying
%s as the type
specifier.
puts() puts(str); char s1[100]=”helloworld”; Puts displays the line
puts(s1); of text.
putchar() putchar(char) char c=‟y‟; Putchar displays a
putchar( c); single character on
screen
putc() putc(char) char c=‟y‟; Putc displays a single
putc( c); character on screen

IT/SVCE Page 1
IT18101 PROGRAMMING FOR PROBLEM SOLVING

1.4 Reading Strings


Strings can be read from the user using different ways as described in the below table:

Function Syntax Example Description


scanf() scanf(“%s”,strname); char s1[100]; Scanf gets a single word from the
scanf(“%s”,s1); user using scanf by specifying %s as
the type specifier.Since string name
itself specifies starting address of the
string, no need to specify & while
writing the varname.
gets() gets(str); char s1[100]; Gets reads a line of text from the
gets(s1); user and store it in s1.
getchar() Var=getchar() char c; getchar reads a single character
c=getchar(); from the user and return the ASCII
value of the char.
getc() Var=getc(char) char c; getc reads a single character from
c=getc( c); the user and return the ASCII value
of the char.
getch() Var=getch() char c; getch reads a single character from
c=getch(); the user and return the ASCII value
of the char.The character entered by
the user will not be echoed on the
screen

1.5 String Manipulation Using built-in Function

C has the weakest character string capability of any general-purpose programming language.
Strictly speaking,there are no character strings in C, just arrays of single characters that are really
small integers. If s1 and s2 are such „strings‟ a program cannot

 assign one to the other: s1 = s2;


 compare them for collating sequence: s1 < s2
 concatenate them to form a single longer string: s1 + s2
 return a string as the result of a function

A set of standard C library functions that are contained in <string.h> provides limited support for
manipulating strings as shown in the below table.

IT/SVCE Page 2
IT18101 PROGRAMMING FOR PROBLEM SOLVING

1.5.1 Copying a string into another

Since C never lets entire arrays to be assigned, the strcpy() function can be used to copy one
string to another.

Syntax
strcpy(desn_str,src_str);

#include <string.h>
int main()
{
char s1[] =“Hello, world!”;
char s2[20];
strcpy(s2, s1);
puts (s2);
return 0;
}
Output:
Hello,world!

IT/SVCE Page 3
IT18101 PROGRAMMING FOR PROBLEM SOLVING

1.5.2 Comparing strings


Another function, strcmp(), takes the start addresses of two strings as parameters and returns the
value zero if the strings are equal. If the strings are unequal, it returns a negative or positive
value. The returned value is positive if the first string is greater than the second string and
negative if the first string is lesser than the second string.

Syntax
int strcmp(string1,string2);

Example:

#include <stdio.h>
#include <string.h>
int main()
{
char x[50];
gets(x);
if(strcmp(x,“A Programming Example”) == 0)
printf(“Equal \n”);
else
printf(“Unequal \n”);
}
Output
Hello
Unequal

1.5.3 Putting strings together (concatenation of two strings)


The arithmetic addition cannot be applied for joining of two or more strings in the
manner string1 = string2 + string3; or
string1 = string2 +”RAJA”;
For this, the standard library function, strcat(), that concatenates strings is needed. strcat()
concatenates two strings and stores the result in the first string
Syntax
strcat(str1,str2);

Example:
#include <stdio.h>
#include <string.h>
main()
{
char s1[30] =“Hello,”;
char s2[] =“world!”;
strcat(s1, s2);
printf(“%s\n”, s1);
}

IT/SVCE Page 4
IT18101 PROGRAMMING FOR PROBLEM SOLVING

2. String Manipulation Without Using built-in Function

2.1 Copying one string to another


#include <stdio.h>
#include <string.h>
main()
{
char src[30], dest[30];
int i = 0;
printf(“\n Enter the source string: ”);
scanf(“%s”,src);
while(src[i] != „\0‟)
{
dest[i] = src[i];
i++;
}
dest[i] = „\0‟;
printf(“\n Source string is :%s\n”, src);
printf(“\n Destination string is : %s\n”, dest);
}
Output
Enter the source string:hello
Source string is :hello
Destination string is : hello

2.2 Putting strings together (Concatenate two strings)


#include <stdio.h>
#include <string.h>
main()
{
char s1[30], s2[30];
int i ,j,len;
printf(“\n Enter the first string: ”);
gets(s1);
printf(“\n Enter the second string: ”);
gets(s2);
len=strlen(s1);
for(i=len,j=0;s2[j] != „\0‟;j++,i++)
{
s1[i]=s2[j];

}
s1[i] = „\0‟;
printf(“\n Concatenated string is : %s\n”, s1);
}

IT/SVCE Page 5
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Output
Enter the first string:hello
Enter the second string:world
Concatenated string is :helloworld

2.3 Finding the length of the string

#include <stdio.h>
#include <string.h>
main()
{
char s1[30];
int i ;
printf(“\n Enter the string: ”);
gets(s1);
i=0;
while(s[i]!=‟\0‟)
{
i++;
}
printf(“\n Length of the string is : %d\n”,i);
}
Output
Enter the first string:hello
Length of the string is :5

2.4 Reversing a string


#include <stdio.h>
#include <string.h>
main()
{
char s[30],rev[30];
int i ,j,len;
printf(“\n Enter the string: ”);
gets(s);
len=strlen(s);
for(i=len,j=0;i<=0;j++,i--)
{
rev[j]=s[i];

}
rev[j] = „\0‟;
printf(“\n Reversed string is : %s\n”, s1);
}
Enter the string: hello
Reversed string is :olleh

IT/SVCE Page 6
IT18101 PROGRAMMING FOR PROBLEM SOLVING

3 Array of strings:
Array of strings are used to store multiple strings under the same name.A two-
dimensional array of strings can be declared as follows:

char <string_array_name>[<row_size>][<columns_size>];

Row size indicates the number of strings and column size indicates the maximum number of
caharacters presen in the strings

Example
char s[5][30];

Initialization
Two-dimensional string arrays can be initialized as shown
char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};

which is equivalent to

Here every row is a string. That is, s[i] is a string.

3.1 Manipulating String Arrays


The following program demonstrates how an individual string of an array of strings can be used
to take input from the user.

#include <stdio.h>
int main()
{
int i;
char s[10][30];
for(i=0;i<5;i++)
{
scanf(“%s”,s[i]);
}
for(i=0;i<10;i++)
{

IT/SVCE Page 7
IT18101 PROGRAMMING FOR PROBLEM SOLVING

printf(“\n%s”,s[i]);
}
}
Output
cat
rat
mat
sat
dog
cat
rat
mat
sat
dog

3.2 Sorting names in alphabetical order

#include <stdio.h>
#include <string.h>
main()
{
char s[10][30], t[30];
int i,j,n;
printf(“\n how many strings:”);
scanf(“%d”,&n);
printf(“\n enter the strings:\n”);
for(i=0;i<n;i++)
{
scanf(“%s”,s[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1; j<n; ++j)
{
if(strcmp(s[i],s[j])>0)
{
strcpy(t,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],t);
}
}
}
printf(“\n **sorted array**\n”);
for(i=0;i<n;i++)
{
printf(“\n%s”,s[i]);

IT/SVCE Page 8
IT18101 PROGRAMMING FOR PROBLEM SOLVING

}
}
Output:
how many strings:5
enter the strings:
cat
rat
mat
sat
dog
**sorted array**
cat
dog
mat
rat
sat

IT/SVCE Page 9
IT18101 PROGRAMMING FOR PROBLEM SOLVING
UNIT – IV

Syllabus
Function – definition of function – Declaration of function – Pass by value - Pass by reference–
Recursion - Enumerators - Structures - Unions.

1. FUNCTIONS
 A function is a self-contained block of program statements that performs a particular task.

1.1 Why are Functions Needed?


 Makes programs significantly easier to understand and maintain by breaking up a program into
easily manageable chunks.
 The main program can consist of a series of function calls rather than countless lines of code.
 Well written functions may be reused in multiple programs.
 Functions can be used to protect data .
 Different programmers working on one large project can divide the workload by writing
different functions.

1.2 Function Prototype or Function Declaration :


A user-written function should normally be declared prior to its use to allow the compiler to perform
type checking on the arguments used in its call statement or calling construct.

Syntax:
return_data_type function_name (data_type variable1, ...);
Or
return_data_type function_name (data_type_list);

 function_name
This is the name given to the function and it follows the same naming rules as that for
any valid variable in C.
 return_data_type
This specifies the type of data given back to the calling construct by the function after it
executes its specific task.
 data_type_list
This list specifies the data type of each of the variables, the values of which are expected to be
transmitted by the calling construct to the function.

Examples:
(a) float FtoC(float faren);
(b) double power(double, int);
(c) int isPrime(int);
(d) void printMessage(void);
(e) void fibo_series(int);

When a function returns no value, it is required to include “void” as the function type .

IT/SVCE 1
IT18101 PROGRAMMING FOR PROBLEM SOLVING
1.3 Function Definition :
 The collection of program statements in C that describes the specific task done by the function
is called a function definition.
 It consists of the function header and a function body, which is a block of code enclosed in
braces.

Syntax:

return_data_type function name(data_type variable1, data_type variable2,……)


{
/* Function Body */
}
 The list of variables in the function definition is also referred to as the formal parameters .
 A value of the indicated data type is returned to the calling function when the function is
executed.

A function that has no parameters and does not return a value would have the following header.
void function_name(void)

1.4 return Statement


Used to terminate the execution of a function and returns control to the calling function.
return statement may or may not return a value to the calling function. The type of value returned from
the function and the return type specified in function prototype and function definition must match.

Syntax:

return <expression>;

Write a function that computes x power n


double power(double x, int n)
{
int i;
double result = 1.0;
for( i = 1; i<=n; i++)
{
result *= x;
}
return result;
}

1.5 Function Calling


Function call statement invokes the statement. When a function is invoked the compiler jumps to the
called function to execute the statements that are part of the function.Once the called function is
executed the program control passes back to the calling function.

IT/SVCE 2
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Syntax:

function_name(variable1, variable2,…);
or
variable_name = function_name(variable1, variable2,…);

 If there are no arguments to be passed in the function, i.e., the argument is void, then the calling
statement would be function_name(); variable_name = function_name();
 Information will be passed to the function via special identifiers or expression called arguments
or actual parameters and returned via the return statement.

IT/SVCE 3
IT18101 PROGRAMMING FOR PROBLEM SOLVING

2.PASSING ARGUMENT TO A FUNCTION


Like normal variable, pointer variable can be passed as function argument and it can return from
function.
There are two approaches to passing argument to a function:
 Call by Value
 Call by Reference/Address

2.1CALL BY VALUE:
In call by value, a copy of actual arguments is passed to formal arguments of the called function and
any change made to the formal arguments in the called function have no effect on the values of actual
arguments in the calling function.
If data is passed by value, the data is copied from the variable used in for example main() to a variable
IT/SVCE 4
IT18101 PROGRAMMING FOR PROBLEM SOLVING
used by the function. So if the data passed (that is stored in the function variable) is modified inside the
function, the value is only changed in the variable used inside the function.

#include<stdio.h>

void main()
{
int A=10,B=20;

printf("\nValues before calling %d, %d",A,B);

fun(A,B); //Statement 1

printf("\nValues after calling %d, %d",A,B);

void fun(int X,int Y) //Statement 2


{
X=11;
Y=22;
}

Output :

Values before calling 10, 20


Values after calling 10, 20

2.2 CALL BY REFERENCE:

In call by reference, the location (address) of actual arguments is passed to formal arguments of the
called function. This means by accessing the addresses of actual arguments we can alter them within
from the called function.

In call by reference, to pass a variable n as a reference parameter, the programmer must pass a pointer
to n instead of n itself. The formal parameter will be a pointer to the value of interest. The calling
function will need to use & to compute the pointer of actual parameter. The called function will need to
dereference the pointer with * where appropriate to access the value of interest.

IT/SVCE 5
IT18101 PROGRAMMING FOR PROBLEM SOLVING
#include<stdio.h>

void main()
{
int A=10,B=20;

printf("\nValues before calling %d, %d",A,B);

fun(&A,&B); //Statement 1

printf("\nValues after calling %d, %d",A,B);

void fun(int *X,int *Y) //Statement 2


{
*X=11;
*Y=22;
}

Output :

Values before calling 10, 20


Values after calling 11, 22

SWAP TWO VALUES USING CALL BY VALUE


#include <stdio.h>

void swapByValue(int, int); /* Prototype */

int main() /* Main function */


{
int n1 = 10, n2 = 20;

/* actual arguments will be as it is */


swapByValue(n1, n2);
printf("n1: %d, n2: %d\n", n1, n2);
}
IT/SVCE 6
IT18101 PROGRAMMING FOR PROBLEM SOLVING

void swapByValue(int a, int b)


{
int t;
t = a;
a = b;
b = t;
}

OUTPUT
======
n1: 10, n2: 20

SWAP TWO VALUES USING CALL BY REFERENCE


#include <stdio.h>

void swapByReference(int*, int*); /* Prototype */

int main() /* Main function */


{
int n1 = 10, n2 = 20;

/* actual arguments will be altered */


swapByReference(&n1, &n2);
printf("n1: %d, n2: %d\n", n1, n2);
}

void swapByReference(int *a, int *b)


{
int t;
t = *a;
*a = *b;
*b = t;
}

OUTPUT
======
n1: 20, n2: 10

3 RECURSION :

The process of calling a function by itself is called recursion and the function which calls itself is called
recursive function. Recursion is used to solve various mathematical problems by dividing it into
smaller problems.

Syntax
returntype recursive_func ([argument list])
{
IT/SVCE 7
IT18101 PROGRAMMING FOR PROBLEM SOLVING
statements;
... ... ...
recursive_func ([actual argument]);
... ... ...
}

Note: In order to prevent infinite recursive call, we need to define proper exit condition in a recursive
function.

Recursive function to find the factorial of a number


int fact(int n)
{
if (n < = 1) // base case or terminating condition
return 1;
else
return n*fact(n-1);
}

Program for computing the Fibonacci number sequence using recursion:


#include<stdio.h>
int fib(int);
int main()
{
int n,j;
printf(“\n Enter the number of terms: ”);
IT/SVCE 8
IT18101 PROGRAMMING FOR PROBLEM SOLVING
scanf(“%d”,&n);
printf(“\n Fibonacci sequence for %d terms is:”,i);
for( j=1; j<=n; j++)
printf(“ %d”,fib(j));
return 0;
}
int fib(int val)
{
if(val == 1)
return 0;
else if(val==2)
return 1;
else
return(fib(val - 1) + fib(val - 2));
}

4 STRUCTURES
 A structure is a collection of variables under a single name.
 These variables can be of different types, and each has a name which is used to select it from
the structure.
 A structure is a userdefined data type.

4.1 Defining Structures :


 A structure is declared by using the keyword struct followed by an optional structure tag
followed by the body of the structure.
 The variables or members of the structure are declared within the body.
Syntax
struct <Structure_tag_name>
{
<data_type member_name1>;
<data_type member_name2>;
};

 The structure_tag_name is the name of the structure.


 Each member_name declared within the braces is called a member or structure element.

EXAMPLE:
struct coordinate
{
int x;
int y;
};

4.2 Declaring Structure Variables


The structure variable can be defined by specifying the following statement.
struct structure_tag_name structure_variable1, structure_variable2, …;

IT/SVCE 9
IT18101 PROGRAMMING FOR PROBLEM SOLVING
 The structure_variables are the list of variable names separated by commas.
 Each of these structure_variable names is a structure of type structure_tag_name.
 The structure_variable is also known as an instance variable of the structure.

Instances of structures can be declared at the same time the structure is defined.
Example
struct coordinate s1, s2;

4.3 Accessing the Members of a Structure :


 using the „.‟, which is known as the „dot operator‟.
 The members are accessed by relating them to the structure variable with a dot operator.
Syntax
<structure_variable >.< member_name > ;

 The first member can be accessed by the construct s1.x


 For assigning a value of 12, say, to the member y of the structure identified by the variable s2:
s2.y = 12;
 To print this value assigned to the member on the screen
printf(“%d”, s2.y);

4.4 Initialization of Structures :

 A structure can be initialized in much the same way as any other data type.
 This consists of assigning some constants to the members of the structure.
 Structures that are not explicitly initialized by the programmer are, by default, initialized by the
system.
 For integer and fl oat data type members, the default value is zero.
 For char and string type members the default value is „\0‟.

Syntax
struct <struct tagname> <structure_variable> = {constant1,constant2,..};

Example
struct tablets
{
int count;
float average_weight;
int date,month,year;

};
struct tablets batch1={2000,25.3,07,11,2004};

5 ARRAYS OF STRUCTURES
The structure variable would be an array of objects, each of which contains the member
elements declared within the structure construct.
IT/SVCE 10
IT18101 PROGRAMMING FOR PROBLEM SOLVING
Syntax
struct <structure_tag_name> <structure_variable>[index];
Example
struct tablets
{
int count;
float average_weight;
int date,month,year;

};
struct tablets t[50];

5.1 Initializing Arrays of Structures

Syntax
struct <structure_tag_name> <structure_variable>[N]=
{
{constant01,constant02,……………………….constant0n},
{constant11,constant12,……………………….constant1n},
.
.
{constantN1,constantN2,…constantNn}
};

PROGRAM TO PRINT THE MARKSHEET OF THE STUDENTS IN A CLASS


#include <stdio.h>
struct student
{
char name[50];
int roll;
float m1,m2m3,m4,m5;
float tot;
};

int main()
{
struct student S[100];
int i,n;
printf("Enter information of students:\n");
printf(“Enter the number of students in a class”);
scanf(“%d”,&n);
// storing information
for(i=0;i<n;i++)
{
s[i].roll = i+1;
printf("\nFor roll number%d,\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
IT/SVCE 11
IT18101 PROGRAMMING FOR PROBLEM SOLVING
printf("Enter marks of 1st subject: ");
scanf("%f",&s[i].m1);
printf("Enter marks of 2nd subject: ");
scanf("%f",&s[i].m2);
printf("Enter marks of 3rd subject: ");
scanf("%f",&s[i].m3);
printf("Enter marks of 4th subject: ");
scanf("%f",&s[i].m4);
printf("Enter marks of 5th subject: ");
scanf("%f",&s[i].m5);
printf("\n");
}
printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<n; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Mark1: %.1f\n",s[i].m1);
printf("Mark2: %.1f\n",s[i].m2);
printf("Mark3: %.1f\n",s[i].m3);
printf("Mark4: %.1f\n",s[i].m4);
printf("Mark5: %.1f\n",s[i].m5);
s[i].tot=s[i].m1+s[i].m2+s[i].m3+s[i].m4+s[i].m5;
printf("Total: %.1f\n",s[i].tot);
}

PROGRAM TO CALCULATE GROSS PAY AND NETPAY OF EMPLOYEES USING


STRUCTURE AND ARRAYS

#include <stdio.h>
struct employee
{
char ename[50];
char desgn[50];
float bp;
float hra;
float da;
float pf;
float gp;
float np;
};

int main()
{
int n,i;
IT/SVCE 12
IT18101 PROGRAMMING FOR PROBLEM SOLVING
struct employee emp[100]; // Array of structure objects
printf(“Enter the number of employees: ”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf("%s",emp[i].ename);
scanf("%s", emp[i].desgn );
scanf("%f",&emp[i].bp );
scanf("%f",&emp[i].hra );
scanf(“%f”,&emp[i].da);
scanf(“%f”,&emp[i].pf);
}
for (i = 0; i < n; i++)
{
emp[i].gp=emp[i].bp+emp[i].hra+emp[i].da;
emp[i].np=emp[i].gp-emp[i].pf;
}
for (i = 0; i < n; i++)
{
printf("Name: %s",emp[i].ename);
printf("Designation: %s", emp[i].desgn );
printf("Grosspay: %f",emp[i].gp );
printf("Netpay: %f",emp[i].np );
}
}

6 STRUCTURES AND FUNCTIONS


 An entire structure can be passed as a function argument just like any other variable.
 When a structure is passed as an argument, each member of the structure is copied.
 Each member is passed by value.
 In case the member is an array, a copy of this array is also passed.

SYNTAX
struct structure_tag function_name(struct structure_tag structure_variable);

PROGRAM TO MANUPULATE COMPLEX NUMBERS USING STRUCTURES AND


FUNCTIONS

#include <stdio.h>
struct complex
{
float real;
float imag;
};
struct complex readcomplex();
void display(struct complex c);
struct complex add(struct complex c1, struct complex c2);

IT/SVCE 13
IT18101 PROGRAMMING FOR PROBLEM SOLVING
struct complex sub(struct complex c1, struct complex c2);
int main()
{
struct complex n1,n2,res;
printf("For 1st complex number \n");
n1=readcomplex();
printf("\nFor 2nd complex number \n");
n2=readcomplex();
res = add(n1,n2);
printf(“Sum=”);
display(res);
printf(“Sub=”);
res = sub(n1,n2);
display(res);
return 0;
}
struct complex readcomplex()
{
struct complex c;
printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &c.real, &c.imag);
return c;
}
void display(struct complex c)
{
printf("%f+i%f",c.real,c.imag);
}

struct complex add(struct complex c1, struct complex c2)


{
struct complex temp;

temp.real = c1.real + c2.real;


temp.imag = c1.imag + c2.imag;

return temp;
}
struct complex sub(struct complex c1, struct complex c2)
{
struct complex temp;

temp.real = c1.real - c2.real;


temp.imag = c1.imag - c2.imag;

return temp;
}

OUTPUT

IT/SVCE 14
IT18101 PROGRAMMING FOR PROBLEM SOLVING
For 1st complex number
Enter real and imaginary part respectively:
2
3
For 2nd complex number
Enter real and imaginary part respectively:
1
4
Sum = 3+i7
sub = 1-i1

7 UNION
 A union is a structure all of whose members share the same storage.
 The amount of storage allocated to a union is sufficient to hold its largest member.
 At any given time, only one member of the union may actually reside in that storage.
 The way in which a union‟s storage is accessed depends, then, on the member name that is
employed during the access.
 A union is identified in C through the use of the keyword union in place of the keyword struct.

7.1 Declaring a Union and its Members


Syntax
union tag_name
{
<data_type member_name1>;
<data_type member_name2>;
};

Similar to structure, the union also has a tag name, members, and variable names.

7.2 Declaring the union variables


Syntax
union tag_name variable1,variable2,…,variableX;

Example
union mixed
{
char letter;
float radian;
int number;
};
union mixed all;
 The first declaration consists of a union of type mixed, which consists of a char, float, or int
variable as a member.
 At a time only one member belonging to any one of the data types, that is either char or int or
float, can exist. This is due to the provision of a single memory address that is used to store the

IT/SVCE 15
IT18101 PROGRAMMING FOR PROBLEM SOLVING
largest variable, unlike the arrangement used for structures.

7.3 Accessing and Initializing the Members of a Union

Syntax
variable1.member1
variable1.member2
.. .
Variable1.memberN

Only one member that exists at the particular instance in storage should be accessed.

The general construct for individual initialization of a union member is


variableX.memberN = constant;

PROGRAM TO FIND THE AREA OF CIRCLE AND SQUARE USING UNION

#include<stdio.h>
union geometry
{
int side;
int radius;
float area;
};

main()
{
union geometry g;
printf (“Enter the radius:”);
scanf(“%d”,&g.radius);
g.area=3.14*g.radius*g.radius;
printf(“Area of circle is %f\n”,g.area);
printf (“Enter the side:”);
scanf(“%d”,&g.side);
g.area=g.side*g.side;
printf(“Area of square is %f\n”,g.area);
}

8 DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:

C Structure C Union

Union allocates one common storage space for all its members.
Structure allocates storage space for
Union finds that which of its member needs high storage space
all its members separately.
over other members and allocates that much space

Structure occupies more memory


Union occupies less memory space over structure.
space.

IT/SVCE 16
IT18101 PROGRAMMING FOR PROBLEM SOLVING
We can access all members of
We can access only one member of union at a time.
structure at a time.

Structure example: Union example:


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

For above structure, memory


allocation will be like below.
For above union, only 8 bytes of memory will be allocated since
int mark – 2B
double data type will occupy maximum space of memory over
char name[6] – 6B
other data types.
double average – 8B
Total memory allocation = 8 Bytes
Total memory allocation = 2+6+8 =
16 Bytes

9 ENUMERATION DATA TYPES

 Data items whose values may be any member of a symbolically declared set of values.
 The symbolically declared members are integer constants.
 The keyword enum is used to declare an enumeration type.

Syntax
enum tag_name {member1, member2,…, memberN};

 The enum tag_name specifies the user-defined type.


 The members are integer constants.
 By default, the first member, that is, member1, is given the value 0.
 The second member, member2, is given the value 1.
 Members within the braces may be initialized, in which case, the next member is given a value
one more than the preceding member.
 So, each member is given the value of the previous member plus 1.

The general form of the construct for declaring variables of enum type separately is
enum tag_name variable1,...,variableX;

The variables can take on as values only the members in the member list.
Therefore,
variable1 = member2;
assigns the value represented by member2 to variable1.

A typical declaration would be


enum days {Mon, Tues, Wed, Thurs, Fri, Sat, Sun};
 The above declaration means that the values „Mon,...,Sun‟ may be assigned to a variable of type
enum days.
IT/SVCE 17
IT18101 PROGRAMMING FOR PROBLEM SOLVING
 The actual values are 0,...,6 in this example and it is these values that must be associated with
any input or output operations.

PROGRAM:
#include <stdio.h>
enum days{sun,mon,tues,wed,thurs,fri,sat};

int main()
{
enum days d;
for(d=sun;d<=sat;d++)
{
switch(d)
{
case sun:
printf("sunday");
break;
case mon:
printf("monday");
break;
case tue:
printf("tuesday");
break;
case wed:
printf("wednes");
break;
case thu:
printf("thurday");
break;
case fri:
printf("friday");
break;
case sat:
printf("saturday");
break;
}
}
}

IT/SVCE 18
IT18101 PROGRAMMING FOR PROBLEM SOLVING

UNIT - V

Syllabus

Macros - storage classes - Pointers- Definition – Initialization – Pointers arithmetic – Double Pointers, Basic file
operations-Example problems.

1.PREPROCESSOR DIRECTIVES

 A program which processes the source code before it passes through the compiler is
known as preprocessor.
 The commands of the preprocessor are known as preprocessor directives.
 It is placed before the main().
 It begins with a # symbol.
 They are never terminated with a semicolon.

The preprocessor directives are divided into four different categories which are as follows:

1.1 Macro expansion

 There are two types of macros - one which takes the argument and another which
does not take any argument.
 Values are passed so that we can use the same macro for a wide range of values.

Syntax:
#define name replacement-text

Where,
name – it is known as the micro template.
replacement-text – it is known as the macro expansion.

 A macro name is generally written in capital letters.


 If suitable and relevant names are given macros increase the readability.
 If a macro is used in any program and we need to make some changes throughout the
program we can just change the macro and the changes will be reflected everywhere
in the program.

Example : Calculate area of circle using #define preprocessor


#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area of circle=%.2f",area);
IT/SVCE 1
IT18101 PROGRAMMING FOR PROBLEM SOLVING

return 0;
}
Example : To find the square of a number using function macro
#include<stdio.h>
#define SQUARE(x) x * x
int main()
{
inta,result;
printf("Enter the number: ");
scanf("%d",&a);
result=SQUARE(a);
printf(“The square of given number= %d",result);
return0;
}

Example : To print the greatest of two numbers using macro

#include<stdio.h>
#define MAX(a,b) a>b?a:b
void main()
{
int n1,n2;
printf(“Enter the two numbers”);
scanf(“%d%d”,&n1,&n2);
printf("%d is greater",MAX(n1,n2);
}

Output :

Enter the two numbers: 2 4


4 is greater

Example : Converting a number to its string literal using function macro

#include<stdio.h>
#define CONVERT(x) INTTOSTR(x)
int main()
{
int a;
char *p;
printf("Enter the number: ");
scanf("%d",&a);
p=CONVERT(a);
printf(“The equivalent string of given number= %s",*p);
return 0;
}

IT/SVCE 2
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Output:
Enter the number: 70
The equivalent string of given number= F

1.2. File inclusion

 The file inclusion uses the #include.

Syntax:
#include filename

 The content that is included in the filename will be replaced at the point where the
directive is written.
 By using the file inclusive directive, we can include the header files in the programs.
 Macros, function declarations, declaration of the external variables can all be
combined in the header file instead of repeating them in each of the program.
 The stdio.h header file contains the function declarations and all the information
regarding the input and output.

There are two ways of the file inclusion statement:


i) #include “file-name”
ii) #include <file-name>

 If the first way is used, the file and then the filename in the current working directory
and the specified list of directories would be searched.
 If the second way, is used the file and then the filename in the specified list of
directories would be searched.

1.3. Conditional compilation

 The conditional compilation is used when we want certain lines of code to be


compiled or not.
 It uses directives like #if, #elif, #else, #endif

Syntax

#if TEST <= 5


statement 1;
statement 2;
#else
statement 3;
statement 4;
#endif

If there are a number of conditions to be checked we can use the #elif instead of #else and #if.

IT/SVCE 3
IT18101 PROGRAMMING FOR PROBLEM SOLVING

1.4. Miscellaneous directive


There are some directives which do not fall in any of the above mentioned categories.

There are two directives:

i) #undef : This directive is used in relation to the #define directive. It is used to undefine a
defined macro.
ii) #pragma : It is a specialized and rarely used directive. They are used for turning on and off
certain features.

2.SCOPE AND EXTENT


The region of the program over which the declaration of an identifi er is visible is
called the scope of the identifi er. The scope relates to the accessibility, the period of
existence, and the boundary of usage of variables declared in a statement block or a function.

2.1Concept of Global and Local Variables


There are two common terms related to the visibility or accessibility of a variable.
They are global and local variables. Actually global and local are the terms related with
lifetime. Lifetime is the period during execution of a program in which a variable or function
exists.
Variables declared within the function body are called local variables. They have
local scope. Local variables are automatically created at the point of their declaration within
the function body and are usable inside the function body. These variables only exist inside
the specific function that creates them. They are unknown to other functions and to the main
program. The existence of the local variables ends when the function completes its specific
task and returns to the calling point. They are recreated each time a function is executed or
called.
Variables declared outside of all the functions of a program and accessible by any of
these functions are called global variables. The existence and region of usage of these
variables are not confined to any specific function body. They are implemented by
associating memory locations with variable names. Global variables are created at the
beginning of program execution and remain in existence all through the period of the
execution of the program. These variables are known to all functions in the program and can
be used by these functions as many times as may be required.

Example :Usage of Local and Global variables


#include <stdio.h>
void exchange(void);
int a, b; /* declaration of global variables */
int main()
{
a = 5;
b = 7;
printf(“ In main: a = %d, b = %d\n”, a, b);
exchange();
printf(“\n Back in main:”);
printf(“a = %d, b = %d\n”, a, b);
return 0;

IT/SVCE 4
IT18101 PROGRAMMING FOR PROBLEM SOLVING

}
void exchange(void)
{
int temp; /* decl. of local variable in function*/
printf(“\n a=%d and b=%d”,a,b);
temp = a;
a = b;
b = temp; /* interchange over */
printf(“\n In function exchange() after change:”);
printf(“a = %d, b = %d\n”, a, b);
}
3. STORAGE CLASSES IN C
A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C Program. They precede the type that they modify. There are four different storage
classes in a C program −
 auto
 register
 static
 extern

Storage Classes are used to describe about the features of a variable/function. These
features basically include the scope, visibility and life-time which help us to trace the
existence of a particular variable during the runtime of a program.

3.1. Storage class:auto

Scope: Variable defined with auto storage class are local to the function block inside which
they are defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of the function/method block where the variable is defined.

A variable declared inside a function without any storage class specification, is by default
an automatic variable. They are created when a function is called and are
destroyed automatically when the function's execution is completed. Automatic variables can
also be called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.
Syntax
auto datatype var;

The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be
used within functions, i.e., local variables.

IT/SVCE 5
IT18101 PROGRAMMING FOR PROBLEM SOLVING

3.2. Storage class:extern

Scope: Global i.e everywhere in the program. These variables are not bound by any function,
they are available everywhere.
Default initial value: 0(zero).
Lifetime: Till the program doesn't finish its execution, you can access global variables.

Syntax
extern datatype var;

A variable that is declared outside any function is a Global Variable. Global variables
remain available throughout the program execution. By default, initial value of the Global
variable is 0(zero). One important thing to remember about global variable is that their values
can be changed by any function in the program.

The extern storage class is used to give a reference of a global variable that is visible
to ALL the program files. When you use 'extern', the variable cannot be initialized however,
it points the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will
also be used in other files, then extern will be used in another file to provide the reference of
defined variable or function. Just for understanding, extern is used to declare a global
variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.

First File: main.c

#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}

Second File: support.c

#include <stdio.h>
extern int count;
voidwrite_extern(void) {
printf("count is %d\n", count);
}

Here, extern is being used to declare count in the second file, where as it has its
definition in the first file, main.c. Now, compile these two files as follows −

IT/SVCE 6
IT18101 PROGRAMMING FOR PROBLEM SOLVING

$gcc main.c support.c

It will produce the executable program a.out. When this program is executed, it
produces the following result −

count is 5

3.3. Storage class:static

Scope: Local to the block in which the variable is defined


Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.

A static variable tells the compiler to persist/save the variable until the end of
program. Instead of creating and destroying a variable every time when it comes into and
goes out of scope, staticvariable is initialized only once and remains into existence till the end
of the program. A staticvariable can either be internal or external depending upon the place of
declaration. Scope of internal static variable remains inside the function in which it is
defined. External static variables remain restricted to scope of file in which they are declared.
They are assigned 0 (zero) as default value by the compiler.

Syntax
static datatype varname=initialvalue;

Example:
#include<stdio.h>
void test(); //Function declaration
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //a static variable
a = a + 1;
printf("%d\t",a);
}
Output:
123

3.1. Storage class:register

Scope: Local to the function in which it is declared.

IT/SVCE 7
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Default initial value: Any random value i.e garbage value


Lifetime: Till the end of function/method block, in which the variable is defined.

Register variables inform the compiler to store the variable in CPU register instead of
memory. Register variables have faster accessibility than a normal variable. Generally, the
frequently used variables are kept in registers. But only a few variables can be placed inside
registers. One application of register storage class can be in using loops, where the variable
gets used a number of times in the program, in a very short span of time. Only integer and
char data can be stored inside a register variable

Syntax :
register int number;

4. FILE HANDLING
A fi le is a repository of data that is stored in a permanent storage media, mainly in
secondary memory. So far, data was entered into the programs through the computer‟s
keyboard. This is somewhat laborious if there is a lot of data to process. The solution is to
combine all the input data into a fi le and let the C program read the information from the f le
when it is required.

Four essential actions carried out to use a file


 Declare a file pointer variable.
 Open a fi le using the fopen() function.
 Process the fi le using suitable functions.
 Close the fi le using the fclose() function.
IT/SVCE 8
IT18101 PROGRAMMING FOR PROBLEM SOLVING

4.1Declaration of File Pointer


Because a number of different files may be used in a program, when reading or writing, the
type of file that is to be used must be specified. This is accomplished by using a variable
called a file pointer, a pointer variable that points to a structure FILE. FILE is a structure
declared in stdio.h.

Syntax
FILE *fi le_pointer_name,…;

For example,
FILE *ifp;
FILE *ofp;

4.2 Opening a File


To open a file and associate it with a stream, the fopen() function is used.

Syntax
FILE *fopen(const char *fname, const char *mode);

fopen() takes two string arguments. The first of these is the filename; the second is an option
that conveys to C what processing is to be done with the file: read it, write to it, append to it,
etc. Table lists the options available with fopen().

Mode Description
r Open a text file for reading

w Create a text file for writing

a Append to a text file

r+ Open a text file for read/write

w+ Create a text file for read/write

a+ Append or create a text file for read/write

Example

FILE *fp;
fp = fopen(“data.txt”,“w”);

The data.txt is created and opened for writing into the file.
The fopen() function returns a FILE *, which is a pointer to structure FILE, that can then be
used to access the fi le.When the fi le cannot be opened due to reasons described below,
fopen() will return NULL. The reasons include the following.
IT/SVCE 9
IT18101 PROGRAMMING FOR PROBLEM SOLVING

 Use of an invalid fi lename


 Attempt to open a fi le on a disk that is not ready; for example, the drive door is not
closed or the disk is not formatted.
 Attempt to open a fi le in a non-existent directory or on a non-existent disk drive
 Attempt to open a non-existent fi le in mode r

One may check to see whether fopen() succeeds or fails by writing the following set of
statements.

fp = fopen(“data.dat”,“r”);//attempts to open the fi le named “data.dat” in read mode


if(fp == NULL)
{
printf(“Can not open data.dat\n”);
exit(1);
}

4.3 Closing the file

After completing the processing on the file, the file must be closed using the fclose()
function.

Syntax
int fclose(FILE *fp);

Example
fclose(fp);

4.4 Input/Output operation on File


C provides a number of functions that helps to perform basic file operations.
Following are the functions to read from and write into the file.
Function Description Syntax
getc reads a character from a file Var=getc(fp);

putc writes a character to a file putc(char,fp);


fgetc reads a character from a file Var=fgetc(fp);

fputc writes a character to a file fputc(char,fp);


fscanf reads a set of data from a file fscanf(fp,”type
specifier”,var);
fprintf writes a set of data to a file fprintf(fp,”type
specifier”,var);
fgets Reads a line of text from a fgets(buffer,length,fp);
file
fputs Writes a line of text from a fputs(buffer,fp);
file
feof Checks whether end of file is feof(fp)
reached

IT/SVCE 10
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Basic workflow of a file program in C


int main()
{
FILE *fp; // declare file pointer variable
fp = fopen("somefile.txt", "w"); // fopen() function called

/*
do something here
*/

fclose(fp); // close the file


}

Program to read char by char from file and display it on screen

#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp =fopen("one.txt", "r");
while(!feof(fp))
{
ch = fgetc(fp);
printf("%c",ch);
}
fclose(fp);
}

Program to get char by char from the user and write it into a file

#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp =fopen("one.txt", "w");
do
{
ch = getc();
fputc(ch;
} while(ch!=‟\n‟);
fclose(fp);
}

Reading from File using fscanf()


IT/SVCE 11
IT18101 PROGRAMMING FOR PROBLEM SOLVING

#include <stdio.h>
#include <stdlib.h>

int main()
{
int rollno;
char name[50];
FILE *fptr;

fptr = fopen("program.txt","r");
fscanf(fptr,"%d %s", &rollno,name);

printf("Roll no: %d\n",rollno);


printf(“Name: %s”,name);
fclose(fptr);

return 0;
}

Writing into File using fprintf()

#include <stdio.h>
#include <stdlib.h>

int main()
{
int rollno;
char name[50];
FILE *fptr;

fptr = fopen("program.txt","w");
printf(“enter the rollno and name”);
scanf("%d %s",&rollno,name);

fprintf(fptr,"%d %s",rollno,name);

fclose(fptr);

return 0;
}

Reading from file using fgets and fputs

#include <stdio.h>
#include <stdlib.h>

int main()
{

IT/SVCE 12
IT18101 PROGRAMMING FOR PROBLEM SOLVING

char name[50]=”This is a example file program”;


FILE *fp1,*fp2;

fptr = fopen("program.txt","w");
fputs(name,fp1);
fclose(fp1);
fp2 = fopen("program.txt","r");
fputs(name,fp2);
puts(name);
fclose(fp2);

}
Output:
This is a example file program

Program to read a file , encrypt it using formula c=c+2 and copy it to another file

#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1 =fopen("original.txt", "r");
fp2 =fopen("encryptfile.txt", "w");

while(!feof(fp1))
{
ch = fgetc(fp1);
ch=ch+2;
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
}

5.POINTERS

A pointer is a variable that store memory address or that contains address of another variable
where addresses are the location number always contains whole number. So, pointer contain
always the whole number. It is called pointer because it points to a particular location in
memory by storing address of that location.

5.1 Declaring a Pointer Variable

During declaration * before variable indicate the compiler that variable declared is a pointer.

Syntax-
Data type *pointer name;

IT/SVCE 13
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Example
int *p1; //pointer to integer type
float *p2; //pointer to float type
char *p3; //pointer to character type

5.2 Assigning a Pointer Variable

Pointer variable must be assigned the address of another variable before using the pointer
variable. The address of the variable can be found using the operator &.

Syntax
Ptrvar=&var;

Example:
int i;
int *p;
p=&i;

5.3 Accessing the value through pointer variable

The primary use of a pointer is to access and, if appropriate, change the value of the variable
that the pointer is pointing to. The other pointer operator available in C is „*‟, called the
„value at address‟ operator. It returns the value stored at a particular address. The value at
address operator is also called indirection operator or dereference operator.

Example:

int i;
int *p;
p=&i;
*p=5;

Consider the following declarations.

int a; /*integer variable */


int *p; /*pointer to integer */
int **q; /*pointer to pointer to integer */
a = 5; /*assign value to a */
p = &a; /*address of a is stored in p */
q = &p; /*address of pa is stored in q */

The memory picture is depicted in the table for the above declaration

IT/SVCE 14
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Example: To display the number and the address where the number is stored using
pointers

#include<stdio.h>
main()
{
int a=2;
int *p;
p=&a;
printf(“The value of a = %d”,a);
printf(“The address of a =%p”,p)
}
Output
The value of a = 2
The address of a = 0xFF00FF00

Example: To find the area of a circle using pointers


#include<stdio.h>
main()
{
float r, area, pi=3.14159;
float *pr,*pa;
pr=&r;
pa=&area;
printf("Give the radius of Circle : ");
scanf("%f", pr);
*pa = pi * *pr * *pr;
printf("\n\n The Area of Circle is : %f",*pa);
}

Sample Output:
Give the radius of Circle : 5
The Area of Circle is : 78.539749

5.4 Arrays and pointers

Pointers are used for storing address of dynamically allocated arrays and for arrays which are
passed as arguments to functions.

IT/SVCE 15
IT18101 PROGRAMMING FOR PROBLEM SOLVING

Array name gives address of first element of array.

int a[ ]={20,30,105,82,97,72,66,102};
int *p;
p=a;

Array members are accessed using pointer arithmetic.

Compiler uses pointer arithmetic to access array element. *(p + i) is used to access the ith
element of an array.

Example: To display the array elements using pointers

#include <stdio.h>
main()
{
int a[]={10, 20, 30, 40, 50};
int i;
int *p;
for(i=0;i<5;++i)
printf(“%d ”, *(p+i));

}
Output:
10 20 30 40 50

5.5 Structures and Pointers

Pointers can be declared for structure variable as in any other variable.

Syntax:
struct tagname *ptr;

Example

struct example // defing structure


{
int x;
int y;
};
struct example e; // declaring structure variables
struct example *p; // declaring pointer var for structure
p=&e //assign address of structure var to pointer
p->x=10;
p->y=20;
printf(“%d %d”,p->x,p->y); // accessing members through pointer

IT/SVCE 16
IT18101 PROGRAMMING FOR PROBLEM SOLVING

6. Double pointer

Pointer within another pointer is called pointer to pointer or double pointer

Syntax:-
data type **p;

int x=22;
int *p=&x;
int **p1=&p;
printf(“value of x=%d”,x);
printf(“value of x=%d”,*p);
printf(“value of x=%d”,*&x);
printf(“value of x=%d”,**p1);
printf(“value of p=%u”,&p);
printf(“address of p=%u”,p1);
printf(“address of x=%u”,p);
printf(“address of p1=%u”,&p1);
printf(“value of p=%u”,p);
printf(“value of p=%u”,&x);

Output
p1
P 2000
x 1000
22
3000

Example To find the mean of n numbers

# include <stdio.h>
int main( )
{
int a[20], n, i, sum=0 ;
float mean ;
int *p;
p=a;

printf(" How many Number you want to enter: ") ;


scanf("%d ",& n) ;
printf("\n Enter the number : \n") ;

for (i = 0; i< n ; i++ )


{
scanf("%d ",p+i) ;
ptr++ ;

IT/SVCE 17
IT18101 PROGRAMMING FOR PROBLEM SOLVING

}
for (i = 0; i< n ; i++ )
{
sum = sum + *(p+i) ;

}
mean = sum / n ;
printf("\n Mean of %d Numbers is : %f ",n, mean) ;
return ( 0 );
}
Output

How many Number you want to enter:5


Enter the number :1 2 3 4 5
Mean of 5 Numbers is :5

IT/SVCE 18

You might also like