Programming For Problem Solving
Programming For Problem Solving
Unit I
Introduction
Syllabus
1. COMPUTER
An automatic electronic apparatus for making calculations or controlling operations that are
expressible in numerical or logical terms.
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.
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.
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.
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.
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.
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
Communication is the process of transferring messsages from one point to another. The three
basic elements of a communication system are:
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:
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.
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
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.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.
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.
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.
Advantages:
High Bandwidth
Better noise Immunity
Easy to install and expand
Inexpensive
Disadvantages:
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
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
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.
SVCE Page 9
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING
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
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.
SVCE Page 10
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING
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.
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
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.
SVCE Page 11
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING
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
Fully connected.
Robust.
Not flexible.
4.1.5TREE Topology
It has a root node and all other nodes are connected to it forming a hierarchy. It is also called
SVCE Page 13
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING
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).
SVCE Page 14
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING
Complex in design.
Costly.
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.
SVCE Page 16
UNIT 1 IT18101 PROGRAMMING FOR PROBLEM SOLVING
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
Characteristics of MAN
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.
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
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.
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
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.
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
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:
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)
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.
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.
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.
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.
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
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 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:
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.
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.
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
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.
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.
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
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
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.
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
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
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.
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.
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
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.
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.
Removing errors from a program is called debugging. Any type of error in your program is
known as bug.
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;
}
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.
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
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;
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;
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.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.
SVCE Page 10
Unit 2 - IT18101 Programming for Problem Solving
Different operators in C
SVCE Page 11
Unit 2 - IT18101 Programming for Problem Solving
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.
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 */
SVCE Page 12
Unit 2 - IT18101 Programming for Problem Solving
Pre and post variations of ++ and -- operators:
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.
SVCE Page 14
Unit 2 - IT18101 Programming for Problem Solving
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 */
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.
#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
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)
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.
These can handle one character at a time. For output functions, it prints a single character on
the console.
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.
getche() This input function reads, with echo on the screen, a single character from the
keyboard and immediately returns that character to the program.
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.
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.
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
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 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.
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.
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
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.
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 {}.
SVCE Page 23
Unit 2 - IT18101 Programming for Problem Solving
Example:
#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
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;
}
SVCE Page 24
Unit 2 - IT18101 Programming for Problem Solving
Example:
#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
Syntax
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
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;
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”);
}
}
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
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
Syntax
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.
Example
#include<stdio.h>
main()
{
int i;
for(i = 0; i < 10; i++)
{
printf(“%d ”,i);
}
}
Output
0123456789
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
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.
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
#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;
}
There are certain control statements, which terminate either a loop or a function. There are
three such statements namely: return, break, and continue.
Syntax
return;
return expression;
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.
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
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 */
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.
#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.
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];
Example
a) int x[7];
This statement declares a one-dimensional array named x having 7 elements, each of type int.
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.
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
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.
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
int mark[5];
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.
(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.
(g) Printing an array The following code segment prints the elements of an array, a[10].
#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]);
}
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);
}
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.
Declaration of 2D array
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.
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.
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
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
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("\nDisplaying values:\n");
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
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.
Strings can be displayed on screen using different ways as described in the below table:
IT/SVCE Page 1
IT18101 PROGRAMMING FOR PROBLEM SOLVING
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
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
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
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
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
}
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
#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
}
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
#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
#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.
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:
A function that has no parameters and does not return a value would have the following header.
void function_name(void)
Syntax:
return <expression>;
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.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;
fun(A,B); //Statement 1
Output :
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;
fun(&A,&B); //Statement 1
Output :
OUTPUT
======
n1: 10, n2: 20
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.
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.
EXAMPLE:
struct coordinate
{
int x;
int y;
};
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;
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];
Syntax
struct <structure_tag_name> <structure_variable>[N]=
{
{constant01,constant02,……………………….constant0n},
{constant11,constant12,……………………….constant1n},
.
.
{constantN1,constantN2,…constantNn}
};
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);
}
#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 );
}
}
SYNTAX
struct structure_tag function_name(struct structure_tag structure_variable);
#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);
}
return temp;
}
struct complex sub(struct complex c1, struct complex c2)
{
struct complex temp;
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.
Similar to structure, the union also has a tag name, members, and variable names.
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.
Syntax
variable1.member1
variable1.member2
.. .
Variable1.memberN
Only one member that exists at the particular instance in storage should be accessed.
#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);
}
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
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.
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 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.
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:
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.
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;
}
#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 :
#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
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.
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.
Syntax
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
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.
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.
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
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.
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
#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
It will produce the executable program a.out. When this program is executed, it
produces the following result −
count is 5
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
IT/SVCE 7
IT18101 PROGRAMMING FOR PROBLEM SOLVING
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.
Syntax
FILE *fi le_pointer_name,…;
For example,
FILE *ifp;
FILE *ofp;
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
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
One may check to see whether fopen() succeeds or fails by writing the following set of
statements.
After completing the processing on the file, the file must be closed using the fclose()
function.
Syntax
int fclose(FILE *fp);
Example
fclose(fp);
IT/SVCE 10
IT18101 PROGRAMMING FOR PROBLEM SOLVING
/*
do something here
*/
#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);
}
#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);
return 0;
}
#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;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
IT/SVCE 12
IT18101 PROGRAMMING FOR PROBLEM SOLVING
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.
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
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;
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;
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
Sample Output:
Give the radius of Circle : 5
The Area of Circle is : 78.539749
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
int a[ ]={20,30,105,82,97,72,66,102};
int *p;
p=a;
Compiler uses pointer arithmetic to access array element. *(p + i) is used to access the ith
element of an array.
#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
Syntax:
struct tagname *ptr;
Example
IT/SVCE 16
IT18101 PROGRAMMING FOR PROBLEM SOLVING
6. 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
# include <stdio.h>
int main( )
{
int a[20], n, i, sum=0 ;
float mean ;
int *p;
p=a;
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
IT/SVCE 18