chapter 1 problem solving - wordpress.com · problem solving 3 problem is more clearly defines....

261
Problem solving 1 Chapter 1 PROBLEM SOLVING LEARNING OBJECTIVES After going through this chapter, the readers will be able to: apply problem solving techniques; define an algorithm and its features; describe the analysis of the algorithm efficiency; discuss the analysis of algorithm complexity; and design flowchart 1.1 INTRODUCTION In our daily life, we routinely encounter and solve problems. We pose problems that we need or want to solve. For this, we make use of available resources, and solve them. Some categories of resources include: the time and efforts of yours and others; tools; information; and money. Some of the problems that you encounter and solve are quite simple. But some others may be very complex. In this unit we introduce you to the concepts of problem-solving, especially as they pertain to computer programming. The problem-solving is a skill and there are no universal approaches one can take to solving problems. Basically one must explore possible avenues to a solution one by one until she/he comes across a right path to a solution. In general, as one gains experience in solving problems, one develop one’s own techniques and strategies, though they are often intangible. Problem-solving skills are recognized as an integral component of computer programming. It is a demand and intricate process which is equally important throughout the project life cycle especially study, designing, development, testing and implementation stages. The computer problem solving process requires: i) Problem anticipation ii) Careful planning iii) Proper thought process iv) Logical precision v) Problem analysis vi) Persistence and attention. At the same time it requires personal creativity, analytic ability and expressions. The chances of success are amplified when the problem solving is approached in a systematic way and satisfaction is achieved once the problem is satisfactorily solved. The problem should be anticipated as far as possible and properly defined to help the algorithm defined and development process. Computer is a very powerful tool for solving problems. It is a symbol-manipulating machine that follows a set of stored instructions called a program. It performs these manipulations very quickly and stores the input, all commands and output. A computer can’t think like human so that when solving any problem we have to specify the needed initial data, the operations which to be performed. And the result you wanted as output. Any of the instructions missing you will get either no result or invalid result. In either case your problem has not yet been solved. Therefore e several step need to be considered before writing a program. These steps may free you from hours of finding and removing errors in your program (a process called debugging).It should also make the act of problem solving with a computer a much simpler task. All types of computer programs are collectively referred to as software. Programming languages are also part of it. Physical computer equipment such as electronic circuitry, input output devices, storage media etc. comes under hard ware. Software governs the functioning of hardware. Operations performed by software may be built in to the hardware, while instructions executed by the hardware may be generated in software .

Upload: others

Post on 25-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 1

Chapter 1

PROBLEM SOLVING

LEARNING OBJECTIVES

After going through this chapter, the readers will be able to:

apply problem solving techniques;

define an algorithm and its features;

describe the analysis of the algorithm efficiency;

discuss the analysis of algorithm complexity; and

design flowchart

1.1 INTRODUCTION

In our daily life, we routinely encounter and solve problems. We pose problems that we need or

want to solve. For this, we make use of available resources, and solve them. Some categories of resources

include: the time and efforts of yours and others; tools; information; and money. Some of the problems

that you encounter and solve are quite simple. But some others may be very complex.

In this unit we introduce you to the concepts of problem-solving, especially as they pertain to computer

programming.

The problem-solving is a skill and there are no universal approaches one can take to solving

problems. Basically one must explore possible avenues to a solution one by one until she/he comes across

a right path to a solution. In general, as one gains experience in solving problems, one develop one’s own

techniques and strategies, though they are often intangible. Problem-solving skills are recognized as an

integral component of computer programming. It is a demand and intricate process which is equally

important throughout the project life cycle especially – study, designing, development, testing and

implementation stages. The computer problem solving process requires:

i) Problem anticipation

ii) Careful planning

iii) Proper thought process

iv) Logical precision

v) Problem analysis

vi) Persistence and attention.

At the same time it requires personal creativity, analytic ability and expressions. The chances of

success are amplified when the problem solving is approached in a systematic way and satisfaction is

achieved once the problem is satisfactorily solved. The problem should be anticipated as far as possible

and properly defined to help the algorithm defined and development process.

Computer is a very powerful tool for solving problems. It is a symbol-manipulating machine that

follows a set of stored instructions called a program. It performs these manipulations very quickly and

stores the input, all commands and output. A computer can’t think like human so that when solving any

problem we have to specify the needed initial data, the operations which to be performed. And the result

you wanted as output. Any of the instructions missing you will get either no result or invalid result. In

either case your problem has not yet been solved. Therefore e several step need to be considered before

writing a program. These steps may free you from hours of finding and removing errors in your program

(a process called debugging).It should also make the act of problem solving with a computer a much

simpler task.

All types of computer programs are collectively referred to as software. Programming languages

are also part of it. Physical computer equipment such as electronic circuitry, input output devices, storage

media etc. comes under hard ware. Software governs the functioning of hardware. Operations performed

by software may be built in to the hardware, while instructions executed by the hardware may be

generated in software .

Page 2: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 2

The decision to incorporate certain functions in the hardware and others in the software is made

by the manufacturer and designer of the software and hardware. Normal considerations for this are: cost,

speed, memory required, adoptability and reliability of the system. Set of instructions of the high-level

language used to code a problem to find its solution is referred to as source program. A translator

program called a compiler or interpreted, translate the source program in to the object program. This is

the compilation or interpretation phase. All the testing of the source programs as regards the correct

format of instructions is performed at this stage and the errors, is any, and is printed. If there is no error

the source program is transformed in to the machine language program called object program. The object

program is executed to perform calculations this stage is the execution phase. Data, if required by the

program are supplied now and the result is obtained on the output device.

1.2 PROBLEM SOVING THECHNIQUES

Problem solving is a process which defines systematization and mechanization. There are a

number of steps that can be taken to raise the level of one’s performance in problem solving.

Steps for problem solving

A problem solving technique follows certain steps in finding the solution to a problem. Let us

look in to the steps one by one.

1.2.1 Problem definition phase

The success in solving any problem is possible only after the problem has been fully understood.

That is we cannot hope to solve problem, which we do not understand .So, the problem understanding is

the first step towards the solution of the problem. In the problem definition phase, we must emphasize

what must be done rather than how is is to be done. That is we try to extract precisely defined set of tasks

from the problem statement. In experienced problem solvers too often gallop a head with the task of

problem solving only to find that they are either solving the wrong problem or solving just one particular

problem.

1.2.2 Getting started on a problem

There are many ways of solving a problem and there may be several solutions. So it is difficult t

to recognize immediately which path could be more protective. Sometimes you do not have any idea

where to begin solving a problem, even if the problem has been defined .Such block sometimes occurs

because you are overly concerned with the details of the implementation even before you have

completely understood or worked out a solution. The best advice is not to get concerned with the details.

Those can come later when the intricacies of the problem has been understood.

1.2.3 The use of specific examples.

To get started on a problem, we can make use of heuristics that is the rule of thumb. This

approach will allow us to start on the problem by picking a specific problem we wish to solve and try to

work out the mechanism that will allow solving this particular problem. It is usually much easier to work

out the details of a solution to a specific problem because the relationship between the mechanism and the

Source

program

Computer

System

Object

Program

Data if

required

Results

Page 3: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 3

problem is more clearly defines. This approach of focusing on a particular problem can give us the

foothold we need for making a star on the solution to the general problem.

1.2.4 Similarities among problems

One way to make a start is by considering a specific example .Another approach is to bring the

experience to bear on the current problem. So it is important to see if there are any similarities between

the current problem and the past problems which we have solved. He more experience one has the more

tools and techniques one can bring to bear in tackling the given problem. But some time it blocks us from

discovering desirable or better solution to the problem. A skill that is important to try to develop in

problem solving is the ability to view a problem from a variety of angles. One must be able to

metaphorically turn a problem upside down, Inside out, sideways, backwards, forwards and so on. Once

one has developed this skill it should be possible to get started on any problem.

1.2.5 Working backwards from the solution

In some cases we can assume that we already have the solution to the problem and then try to

work backwards to the starting point. Even a guess at the solution to the problem may be enough to give

us a foothold to start on the problem. We can systematize the investigation and avoid duplicate efforts by

writing down the various steps taken and explorations made. Another practice that helps to develop the

problem solving skills is , once we has solved problem , to consciously reflect back on the way we went

about discovering the solution.

1.3 USING COMPUTER AS A PROBLEM-SOLVING TOOL

The computer is a resource-a versatile tool-that can help you solve some of the problems that you

encounter. A computer is a very powerful general-purpose tool. Computers can solve or help to solve

many types of problems. There are also many ways in which a computer can enhance the effectiveness of

the time and effort that you are willing to devote to solving a problem. Thus it will prove to be well worth

the time and effort you spend to learn how to make effective use of this tool.

In this section, we discuss the steps involved in developing a program. Program development is a

multi-step process that requires you to understand the problem, develop a solution, write the program, and

then test is. This critical process determines the overall quality and success of your program. If you

carefully design each program using good structured development techniques our programs will be

efficient, error free, and easy to maintain. The following are the steps in detail:

i) Develop an Algorithm and a Flowchart

ii) Write the program in a computer language (for example say C programming language)

iii) Enter the program sing some editor.

iv) Test and debug the program.

v) Run the program, input data, and get the results.

1.4 DESIGN OF ALGORITHMS

The first step in the program development is to devise and describe a precise plan of what you

want the computer to do. This plan, expressed as a sequence of operation, is called an algorithm. An

algorithm is just an outline or idea behind a program..

1.4.1 Definition

An algorithm is a finite set of steps defining the solution of a particular problem. An algorithm is

expressed in pseudo code-something resembling C language or Pascal, but with some statements in

English rather than within the programming language. Developing an efficient algorithms one which is

capable of giving the solution to the problem by using minimum resources of the system such as memory

and processor’s time. Algorithm is a language independent, well structured and detailed. It will enable the

programmer to translate into a computer program using any high-level language.

Page 4: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 4

1.4.2 Features of Algorithm

Following features should be present in an algorithm:

Proper understanding of the problem

For designing an efficient algorithm, the expectations from the algorithm should be clearly

defined so that the person developing the algorithm can understand the expectations from is. This

is normally the outcome of the problem definition phase.

Use of procedures/functions to emphasize modularity

To assist the development, implementation and readability of the program, it is usually helpful to

modularize (section) the program. Independent functions perform specific and well defined tasks.

In applying modularization, is is important to watch that the process is not taken so far to a point

at which the implementation becomes difficult to read because of fragmentation. The program

then can be implemented as calls to the various procedures that will be needed in the final

implementations.

Choice of variable names

Proper variable names and constant names can make the program more meaningful and easier to

understand. This practice tends to make the program more self-documenting. A clear definition of

all variables and constants at the start of the procedure/algorithm can also be helpful. For

example, it is better to use variable day for the day of the weeks, instead of the variable A or

something else.

Documentation of the program

Brief information about the segment of the code can be included in the program to facilitate

debugging and providing information. A related p art of the documentation is the information that

the programmer presents to the user during the execution of the program. Since the program is

often to be used by persons who are unfamiliar with the working and input requirements of the

program, proper documentation must be provided. That is, the program must specify what

responses are required from the user. Care should also be taken to avoid ambiguities in these

specifications also the program should “catch” incorrect responses to its requests and inform the

user in an appropriate manner.

1.4.3 Criteria to be followed by an algorithm

The following is the criteria to be followed by an algorithm:

i) Input: There should be zero or more values which are to be supplied.

ii) Output: At least one result is to be produced.

iii) Definiteness: Each step must be clear and unambiguous.

iv) Finiteness: Each step must be sufficiently a basic that a person using only paper and

pencil canin principle carry it out. In addition, not only each step isdefinite, it must

also be feasible.

Example 1.1: An algorithm to find the area of a Circle of radius r.

Inputs to the algorithm:

Radius r of the Circle.

Expected output:

Area of the Circle

Algorithm:

Step1: Read\input the Radius r of the Circle

Step2: Area= PI*r*r // calculation of area

Step3: Print Area

Example 1.2: An algorithm to compute and display the sum of two numbers

Inputs to the algorithm:

Two numbers

Expected output:

Sum of two numbers

Page 5: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 5

Algorithm:

Step1: Read two numbers a and b

Step2: Calculate the sum of a and b and store it is sum

Step3: Print sum

Example 1.3: Ravi has to attend at least 70% of Practical Classes for C programming to be eligible to

appear in the external examination. Maximum no. of practical classes allotted for the course is 50. He

has attended 20 out of 30 classes held so far. Find at least how many more classes to be attended by Ravi

to be eligible for appearing in Practical Examination.

Inputs to the algorithm:

Minimum Percentage of Attendance required appearing for the external exams.

Maximum Number of practical classes

Number of Classes held so far.

Number of classes attended by Ravi so far.

Expected output:

Number of classes to be attended by Ravi to get eligibility for appearing the external examination

Algorithm:

Step1: Read Minimum percentage of attendance required.

Step2: Read Maximum no. of practical classes in the course (P)

Step3: Read Classes already attended (Ca)

Step4: Read No. of classes conducted so far.(CT)

Step5: Find the no. of Classes to be attended byRavi (Ct= C*P/100)

Step6: Print CM.

Example 1.4: An algorithm to convert temperature from Fahrenheit to Celsius

Inputs to the algorithm:

Temperature in Fahrenheit

Expected output:

Temperature in Celsius

Algorithm:

Step 1: Read Temperature in Fahrenheit F

Step 2: C= 5/9*(F=32)

Step 3: Print Temperature in Celsius: C

Step 4: Stop.

Example 1.5: An algorithm to compute and print the average of a set of data values.

Inputs to the algorithm:

List of data values

Expected Output:

Average of the data values

Step1: Set the sum of the data values and the count to zero

Step2: As long as the data values exist, add the next data value to the sum andadd

1 to the count.

Step3: To compute the average, divide the sum by the count.

Step4: Print average.

Example 1.6: An algorithm to calculate the factorial of a given number.

Inputs to the algorithm:

An integer number

Page 6: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 6

Expected Output:

Factorial of the integer

step1: Read the number n

step2: [initialize] i 1, fact 1

step3: Repeat steps 4 through 5 until i = n

step4: fact fact*i

step5: i i +1

step6: Print fact

Example 1.7: An algorithm to check a given integer is prime or not

Inputs to the algorithm:

An integer number

Expected Output:

Prime or not

step1: Read the number n

step2: [initialize] i 2, flag 1

step3: Repeat steps 4 through 5 until i < num or flag = 0

step4: rem num mod i

step5: if rem = 0 then flag 0 else i i + 1

step6: If flag = 0 then Print number is not prime else print number is prime

Example 1.8: Ramshewar goes to market for buying some fruits and vegetables. He is having a currency

of Rs 500 with him for marketing. From a shop he purchases 2.0 kg Apple priced Rs. 50.0 per kg, 1.5 kg

Mango priced Rs.35.0 per kg, 2.5 kg Potato priced Rs.10.0 per kg, and 1.0 kg Tomato priced Rs.15 per

kg. He gives the currency of Rs. 500 to the shopkeeper. Find out the amount shopkeeper will return to

Ramshewar and also tell the total item purchased.

Before we write algorithm for solving above problem let we find out what the inputs to the

algorithm are and what expected output is.

Inputs to the algorithm are:

Quantity of different items purchased.

Unit Price of each item.

Total amount given to the shopkeeper.

Expected output:

Amount to be returned by shopkeeper after deducting total price of the purchased

vegetables and fruits.

Algorithm:

Step1: Total Cost=0;

Step2: Read Number of units of ith item purchased;

Spet3: Read unit price of ith item

Step4: cost of ith item (CI) = number of units * unit price of i

th item.

Step5: total cost = total cost +CI.

Step6: i= i+1;

Step7: if i<=4 goto step 2.

Step7: RefundAmount = GivenAmount-Total Cost

Step8: Print RefundAmount

Example 1.9: Print the Multiplication Table of N.

Inputs to the algorithm are:

• Number N

Expected output:

Page 7: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 7

Table of N

Algorithm:

Step 1: I=1

Step 2: Read N

Step 3: If I <= 10 then print I*N otherwise goto Step 6

Step 4: I =I+1

Step 5: repeat step3 and 4

Step 6: stop

1.4.4 Top down Design

Once we define a problem and have an idea of how to solve it, we can then use the powerful

techniques for designing algorithms. Most of the problems are complex or large problems and to solve

them we have to focus on to comprehend at one time, a very limited span of logic or instructions. A

technique for algorithm design that tries to accommodate this human limitation is known as top-down

design or stepwise refinement.

Top down design provides the way of handling the logical complexity and detail encountered in

computer algorithm. It allows building solutions to problems in step by step. In this war specific complex

details of the implementation are encountered only at the stage when sufficient ground work on the

overall structure and relationship among the various parts of the problem.

Before the top down design can be applied to any problem, we must at least have the outlines of a

solution. Sometimes this might demand a lengthy and creative investigation in to the problem while

another time the problem description may in itself provide the necessary starting point for the top down

design.

Top down design suggests taking the general statements about the solution one at a time, and then

breaking them in to a more precise subtask/sub-problem. This sub-problem should more accurately

describe how the final goal can be reached. The process of repeatedly breaking a task down in to sub task

in the smaller sub tasks must continue until the sub-problem can be implemented as the program

statement .With each splitting it is essential to define how sub problem interact with each other. In this

way the overall structure of the solution problem can be maintained. Preservation of the overall structure

is important for making the algorithm comprehensible and also for making it possible to prove the

correctness of the solution.

Complex or

largeproblem

Sub Task

N

Sub Task 3 Sub Task

2

Sub Task 1

Complex

solution

Solution 1

Function

…1( )

Solution 2

Function

…2( )

Solution 3

Function

…3( )

Solution 4

Function

…4( )

Fig 1.1. Schematic break down of problem into subtasks as employed in top down

designs

Page 8: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 8

1.5 FLOW CHARTS

“Flow charts are pictorial representation of an algorithm”. It shows the flow of operations

in pictorial form.

1.5.1 Flowchart Symbols

For drawing flow chart standard symbols are used. These symbols are given in table.

Symbols Meaning/Used for

Start or end of the program

Used for writing steps of operations/action or

processing function of a program

Input or output operation

Decision making and branching operations

Connector or joining of two parts in a flowchart

Flow line used for showing flow of data

Magnetic Tape used for secondary

storage/Backup

Magnetic Disk used for secondary

storage/Backup

Fig1.2.Flow chart Symbols

1.5.2 Significance of flowchart

i) A flowchart is a diagrammatic representation of algorithm.

ii) A flow chart clearly illustrates the sequence of operations to be performed for getting

the solution of a problem.

iii)For simple problems flow charts may not be very useful but for complex and large

problems flow charts are very helpful in understanding the logic of the problem.

iv) Flowcharts are used as a link of communication between programmers and clients for

whomthe program to be developed.

v) If you are having a flowchart for your program then you can use it in explaining the

programto others.

vi) Once the flowchart is drawn, it becomes easy to write the computer program.

Page 9: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 9

Flowchartscan be used for preparing a better documentation of a complex problem.

1.5.3 Guidelines for drawing a flowchart

i) Flow charts are drawn using slandered flowchart symbols.

ii) While drawing flowchart some guideline to be followed.

Below are some guidelines for drawing flowchart: i) First of all list all necessary requirements in a logical order.

ii) The flowchart should be clear and easy to understand. There should not beany

ambiguity in understanding the flowchart. For doing this it is necessary to have all the

steps and operation very simple.

iii)Usually direction of the flow of data /procedure in the system should be from left to

right or top to bottom.

iv) Only one flow line should come out from a process symbol.

v) When decision symbol is used only one flow line should enter toit (decision symbol),

but there may be two or three flow lines coming out of the decision symbol, one for

each possible answer.

vi) In a flowchart only one flow line should come to the end symbol.

vii) While writing steps inside the processing symbol, steps should be brief and if

necessary, you can use the annotation symbol to describe data or processing steps

more clearly.

Where P = Price, A = Amount, and R = Rate

viii) In the case of complex flowchart connector symbols to be used for reducing the

number of flow lines in the flowchart.

ix) Intersection of flow lines should be avoided to make a flowchart more effective and

A=B

Compare

A& B

A < B

A>B

END

P=A*R

Page 10: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 10

for better way of communication.

x) A flowchart must have a logical start and end.

xi) Once a flowchart is drawn its validity should be tested by passing through it with a

simple set of test data.

Example1.10: Draw a flowchart to find the simple interest

Example1.11: Draw a flowchart to find the sum of first 50 natural numbers

start

accept p,t,r

i=ptr/100;

print i;

stop

start

Sum=0

N=0

N=N+1

sum=sum+N

is

N=50?

print sum

stop

yes

Page 11: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 11

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

Example1.13: Draw a flowchart for computing factorial N (N!) Where N! = 1? 2? 3...N.

Yes

start

Read A B C

is

A>B?

is

A>C?

is

B>C?

B>C

No

print A print C print B

No

Yes

stop

print c

No

Yes

start

Read N

M=1

F=1

F=F*M

Is M=N?

Print F

stop

YES

M=M+1 NO

Page 12: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 12

Example1.14: Draw a flow chart to find the roots of a quadratic equation

start

Read A B

C

D=B*B-4*A*C

IS

D>0

IS

D>0

ROOT1=(-B+sqrt(D))/(2*A)

ROOT2=(-B+sqrt(D))/(2*A

ROOT1=-B/2*A

ROOT2=-B/2*A

PRINT “ IMAGINARY

ROOTS”

PRINT “REAL

AND EQUAL”

PRINT “REAL

AND

DISTINCT”

STOP

RP=-B/2*A

IP=SQRT(-D)/2*A

PRINT RP,IP PRINT

ROOT1,ROOT2

PRINT

ROOT1,ROOT2

False True

True False

Page 13: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 13

Example1.15: Draw a flowchart to print biggest number from given list of numbers

start

Read N,X

BIG=X

COUNT=1

IF

COUNT<N

Read X

IF X>BIG

BIG=X

Print BIG

COUNT=COUNT+1

Page 14: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 14

Example1.16: Draw a flowchart to display the given number is prime or not

IS

R=0

I=I+1

IS I<=K

FLAG=0

IS

FLAG=

0

PRINT PRIME

PRINT NOT PRIME

START

READ N

K=√N

I=2; FLAG=1

R=remainder of(N/I)

Page 15: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 15

Example1.17: Draw a flowchart to generate first n elements of Fibonacci series.

No

1.5.4 Advantages of using Flowcharts

As we discussed flow chart is used for representing algorithm in pictorial form. This pictorial

representation of a solution/system is having many advantages. These advantages are as follows:

i) Communication: A Flowchart can be used as a better way of communication of the

logic of a system and steps involve in the Solution, to all concerned

particularly to the client of system.

ii) Effective analysis: A flowchart of a problem can be used for effective analysis of the

problem.

iii) Documentation of Program/System: Program flowcharts are a vital part of good

program documentation. Program document is used for various purposes like

knowing the components in the program, complexity of the program etc.

START

READ N

FIB1=1

FIB2=1

PRINT FIB1, FIB2

COUNT=2

FIB3=FIB1=+FIB2

PRINT FIB3

COUNT=COUNT+1

IS COUNT<N

FIB1=FIB2

FIB2=FIB3

STOP

yes

Page 16: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 16

iv) Efficient Program Maintenance: Once a program is developed and becomes

operational it needs time to time maintenance. With help of flowchart maintenance

become easier.

v) Coding of the Program: Any design of solution of a problem is finally converted into

computer program. Writing code referring the flowchart of the solution become easy.

1.5.5 Limitations of using Flowcharts

• Complexity of Logic: If program logic is complex then flowchart of the program becomes

complicated.

• Alterations and Modifications in Logic: any alterations in the program logic may require

redrawing of flowchart completely.

• Reuse is Not Possible: As the flowchart symbols cannot be typed, always reproduction of

flowchart symbols is required.

1.6 LAUNGAGE

A language is a mode of communication between two people. It is necessary for those two

people to understand the language in order to communicate. But even if the two people do not understand

the same language, a translator can help to convert one language to the other. Similarly we need a

language to communicate with the computer. A translator is also needed to convert from user’s form to

computers form. Like other language, a computer language also follows a particular grammar known as

the syntax.

1.7 PROGRAM AND A PROGRAMMING LANGUAGE

To perform any task using a computer it is necessary to give a set of instructions to it. This set of

instructions arranged in a logical sequence is called a Program. In practice it is necessary to express a

program using a programming language. A procedure expressed in a Programming language is known as

a Computer Program.

Programming languages can be divided into three categories.

1.7.1 Machine level Language

i) The language whose design is governed by the circuitry and the structure of the

machine is known as machine language.

ii) This language is difficult to learn and use.

iii) It is specific to a given computer and is different for different computers

i.e this languageis machine-dependent.

iv)This language has been designed to give a better machine efficiency, i.e. faster

program execution.

v) Machine language is also known as low level language.

1.7.2 Assembly language

i) We code the assembly language program in the form of mnemonics.

ii) Every machine provides a different set of mnemonics to be used for that only

depending upon the processor that the machine is using. Hence, this language is also

machine-dependent.

iii) Machine language is also known as low level language.

1.7.3 High level language

i) These languages have been designed to give a better programming efficiency, i.e

faster program development.

ii) Every high level language follows a precise set of rules. They are developed to

Page 17: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 17

allow application programs to be run in a variety of computers.

iii) These languages are machine independent.

iv) Languages falling in this category are FORTRAN, BASIC, and PASCAL etc.

v) These languages are easy to learn and programs may be written in these languages

with much less effort.

vi) However, the computer cannot understand them and they need to be translated into

machine language with the help of other programs known as compilers or interpreters.

SUMMARY

EXERCISES

Multiple Choice Questions

1.1 C is --------- language

a) machine language b) assembly language c) high level language d) fourth generation language

1.2 Which of the following language is also called binary language?

a)high level language b)assembly language c)machine language d)none of these

1.3 Which of the following language is machine independent?

a)high level language b)assembly language c)machine language d)none of these

1.4 Which of the following is not high level language?

a) java b)Pascal c)COBOL d)oracle

Compressive Questions

Computer is a powerful problem solving tool. Problem-solving skills are recognized as an integral

component of computer programming. A problem solving technique follows certain steps in finding

the solution to a problem. An algorithm is a finite set of steps defining the solution of a particular

problem. Flow chart is pictorial representation of an algorithm. It shows the flow of operations in

pictorial form. For drawing flow chart standard symbols are used. The START and STOP are

represented by an ellipse like figure , decision by the rhombus like figure the

process by rectangle and input/ output by parallelograms . . Lines and arrows

connect these blocks. A program is sequence of instructions and the process of writing program is

called programming. Programming languages can be divided into three categories: machine

language, assembly language and high level language. High level languages are easy to use while

machine and assembly languages are complex. Therefore, writing programs in machine and

assembly languages is difficult and time consuming.

Page 18: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Problem solving 18

1.1 What is algorithm and explain it briefly?

1.2 What is flowchart? What are different symbols used for design of flow chart?

1.3 Design an algorithm and draw flowchart to find area and circumference of a circle

1.4 Design an algorithm and draw flowchart to find area and circumference of a rectangle

1.5 Design an algorithm and draw flowchart to check the given character is vowel or not

1.6 Given the marks obtained by the students, maximum marks and pass marks in three subjects, design

an algorithm and draw flowchart to find whether the student passed or not, if the student passes

determine the percentage marks and grade.

The grade is determined as follows:

i) percentage marks >=80 grade is A

ii) percentage marks >=70 and <80 grade is B

iii) percentage marks >=60 and <70 grade is C

iv) percentage marks >=50 and <60 grade is D

v) percentage marks <50 grade is F

1.7 Design an algorithm and draw flowchart for converting temperature from Fahrenheit to centigrade

and vice-versa

1.8 Design an algorithm and draw flowchart to find roots of a quadratic equation

1.9 Design an algorithm and draw flowchart to find the nature of the triangle when sides are given

1.10 Design an algorithm and draw flowchart to find sum of n numbers.

1.11 Design an algorithm and draw flowchart to check given number is prime or not

1.12 Design an algorithm and draw flowchart to check given number is strong or not

1.13 Design an algorithm and draw flowchart to check given number is palindrome or not

1.14 Design an algorithm and draw flowchart to check given number is perfect or not

1.15 Design an algorithm and draw flowchart to check given number is Armstrong or not

1.16 Design an algorithm and draw flowchart to find the smallest number in a given list of numbers

1.17 Design an algorithm and draw flowchart to find first and second largest numbers in a given list

Page 19: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 19

Chapter 2

BASICS OF C

LEARNING OBJECTIVES

After going through this chapter, the readers will be able to:

features of C programming language

Understand the main components of a C Program.

compile a C Program, identify the errors and run a C Program

learn the use of variables ,constants, data types, operators

learn the usage of scanf() and printf() for data input and output

precedence and Associativity of operators

write simple C programs

2.1 OVERVIEW OF C

Before writing C program, we will find out what really is C language, how it came into

existence and where does it stand with respect to other computer language. We will briefly outline these issues in the following section.

2.1.1 History of C

C is a programming language developed at AT&T‟s bell laboratories of USA in 1972. It was designed and written by a man named DENNISRITCHIE. In the late seventies c began to replace the

more familiar languages of that time like PL\I, ALGOL etc.

By 1960,many programming languages came into existence, almost each for a specific purpose for example COBOL was being used for commercial or business applications, FORTRAN for

scientific applications and so on .so, people started thinking why could not there be a one general purpose

language .Therefore ,an international committee was set up to develop such a language ,which came out

with the invention of ALGOL60,but this language never became popular because it was too abstract and too general. To improve this, new language called combined programming language (CPL) was

developed at Cambridge University. But this language was very complex in the sense that it has too many

features and it was very difficult to learn. Matrin Richards at Cambridge University reduced the features of CPL and developed a new language (BCPL). But unfortunately it turned out to be much less powerful

and too specific. Ken Thompson at AT & T‟s bell labs, developed a language called B, but like BCPL

this was also too specific. Ritchie inherited the features of B and BCPL and added some features on his own and developed a language called C. C proved to be quite compact and coherent.

2.1.2 Features of C i) Middle Level Language: Among the two types of programming languages discussed earlier, C lies in

between these two categories. That‟s why it is often called a middle level language, since it was designed to have both: relatively good programming efficiency and relatively good machine efficiency.

ii) Portability: C code is very portable, that it allows the same C program to be run on the machines with

different hardware configurations. iii) Flexibility: The flexibility of C allows it to be used for systems programming as well as for

application programming.

iv) Structured Language: C is commonly called a structured language because of structural similarities

of ALGOL and PASCAL. Structured language is one that divides the entire program into the modules using top-down approach where each module executes one job or task.

It is easy for debugging, testing and maintenance if a language is structured one.

Page 20: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 20

2.2 STRUCTURE OF A C PROGRAM

To solve a problem there are three main things to be considered .firstly what should be the output?

Secondly what should be the input that will be

required to produce this output and thirdly the steps of instructions which use these inputs to produce the

required output .every programming language

follows a set of rules known as syntax . C is a case

sensitive language. All cprograms consist of one or more functions. One function that must be present in

every C program is main(). This is the first function

called up when the program execution begins. Basically main () outlines what a program does.

The structure of a c program is illustrated in flowing figure1.1.Where functions fun1 (),

fun2 () represent user defined functions.

2.2.1 A sample C program From the above section you have become familiar with a programming language and structure of a

program .It is now time to write a simple C program .The program will illustrate how to print out the

message “This is a C program”. Program 2.1: write a program to print to a message on the screen

/*program to print a message*/

#include<stdio.h> /*header file*/

main () /* main function*

{

printf(“This is a program”); /*output statement*/

}

Though the program is very simple, a few points must be noted.

Every C program contains a function called main (). This is the starting point of the program. This is the point from where the execution begins. It will usually call other function to help perform its job, some

that we write and others from the standard libraries provided.

#include<stdio.h> is a reference to a special file called stdio.h which contains information that must be included in the program when it is compiled. The inclusion of this required information will be

handled automatically by the compiler. You will find it at the beginning of almost every C program.

Basically all the statements starting with „# „ in C program are called preprocessor directives .These will be considered in the later units just remember that this statement allows you to use some predefined

functions such as printf() and scanf().

main() declares the start of the function while the two curly{ } shows the start and finish of the

function. Curly brackets in C are used to group statements together as a function or in the body of a

Preprocessor directives Global data declarations main() /* main function */ { Declaration part ; Program statements; } /* user defined functions */ fun1() { ------- ------- } fun2() { ------ }

Fig1.1.structure of a C program

Page 21: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 21

loop .Such a grouping is known as a compound statement or a block every statement within a function

ends with a terminator semicolon(;). printf(“this is a C program”); prints the words on the screen .The text to be printed is enclosed

in double quotes.

Comments may appear anywhere within a program as long as they are placed with in the delimiters /* and*/ .Such comments are helpful in identifying the program principal features or in

explaining the underlying logic of various program features.

2.2.2 Compiling a C program After writing the program the next step is to save the program in a file with extension .C.

This program is in high level language but the language is not understood by the computer. So the next

step is to convert high level language to machine language. This task is performed by the software or program known as compiler. Every language has its own compiler that converts source code to object

code. The compiler will compile the program successfully if the program is syntactically correct.

If the program contains syntax errors they will be displayed on the screen with the corresponding line numbers and the object file will not be produced .The errors need to be removed before compiling the

program. This process of removing the errors from the program is called as debugging. This translation

process is called compilation.

2.2.3. Link and Run the C program

After compilation, the next step is linking the program. Compilation produces a file with an extension

.obj. Now this .obj file cannot be executed since it contains calls to function defined in the standard library of C language. These functions have to be linked with the code you wrote, C remembers its name.

Later the linker combines the code you wrote with the object code already found in the standard library.

This process is called linking. In other words linker is a program that links separately compiled functions

together into one program. It combines the functions in the standard C library with the code that you wrote. The output of the linker is an executable program. i.e, a file with an extension .exe.

2.3 CHARACTER SET, IDENTIFIERS AND KEYWORDS

As every natural languages has a basic character set, computer languages also have a character set,

rules to define words. Words are used to form statements; these in turn are used to write the

programs.The basic elements used to construct simple C program statements are C character set, identifiers, keywords, data types, constants, variables, declaration and naming conventions of variables.

2.3.1 Character set A character denotes any alphabet, digit or special symbol used to represent information. Following

table shows the valid alphabets numbers and special symbols allowed in C:

Alphabets A,….Z, a….z

Digits 0,1,2,3,4,5,6,7,8,9

Special symbols ~‟!@#$%^&*()_+|<>{}[]:;”‟?

Source code Compiler Object code

Object code Linker Executable code

Page 22: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 22

2.3.2 Identifiers Identifiers refer to the names of variables, functions and array. These are user defined names and consist of a sequence of letters and digits, with a letter as a first character. Both upper case and lower

cases letters are permitted, although lower case letters are commonly used. The underscore character is

also permitted.

Rules for identifiers

1. First character must be an alphabet or underscore.

2. Must consists of only letters, digits or underscore 3. Only first 31 characters are significant

4. Cannot use a keyword

5. Must not contain white space.

Variable

A variable is an identifier for a memory location in which data can be stored and subsequently recalled.

2.3.3 Keywords

Keywords are reserved words which have standard, predefined meaning in C. keywords serve as

basic building blocks for program statements. They cannot be used as program defined identifiers. The lists of C keywords are as follows:

char while do typedef auto int if else switch case

printf double struct break static

long enum register extern return

union const float short unsigned continue for signed void default

goto sizeof volatile

2.4 CONSTANTS A constant is a quantity that can be stored in a location of the memory of a computer. It refers to a fixed

value that does not change during the execution of the program. For example the memory structure of a

variable X whose value is 13 at the location number 3540 can be shown as follows:

3540 Address of memory location

Value at that memory location (CONSTANT)

X Name of the memory location (VARIABLE)

A constant differs from a variable in the following ways:

A constant is the value to be stored in a memory location whereas the variable is a name given

to a memory location.

The value of a constant does not change whereas the value of a variable can change

during the execution of a program. For example in the statement X=17; as the value of

17 cannot change it is a constant whereas the quantity X can vary or change. Hence it is called variable.

A constant cannot have a direct memory location whereas a variable can have.

C language supports several types of constants as illustrated below:

13

Page 23: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 23

2.4.1 Integer Constants An integer constant refers to a sequence of digits preceded by an optional + (or) – sign. There are

three types of integers, namely, decimal integer, octal integer and hexadecimal integer.

i) Decimal Integer constant: A decimal integer constant can consist of any combination of digits taken from the set 0 through

9. If the constant contains more than one digit, the first digit must be something other than zero

(0). The format that specifiers decimal integer constants is %d (where„d‟ is called conversion

character). Embedded spaces, commas, and non-digit characters are not permitted between digits.

ii)Octal Integer constant: An octal integer constant can consist of any combination of digits taken

from the set 0 through 7 preceded by zero(0). The format that specifies octal integer constant is

%o(where „o‟ is called conversion character).

Valid examples Invalid examples(with reasons)

0143

0175 015

00

0154

12244(0 should precede the number)

03.43(dot is not allowed) $143(special symbol is not allowed)

08943(invalid digits 8 and 9)

01,43(comma is not allowed)

Valid examples Invalid examples(with reasons)

143

-631

537

0

+1584

12,244(comma is not allowed)

3.43(dot is not allowed)

$143(special symbol is not allowed)

8 143(white space characters are not allowed)

0143(the first digit should not be 0)

Constants

Numeric

Integer

Real

Decimal Octa

l

Hexadecima

l

Single character String

Fractional

form

Exponential form

Page 24: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 24

iii) Hexadecimal Integer constant:

A hexadecimal integer constant can consist of any combination of digits taken from the set 0 through 9 and A through F (or) a through f preceded by 0x (or) 0X. The format that specifies hexadecimal integer

constant is %x (or) %X(where „x‟ or „X‟ is called conversion character).

An unsigned integer constant represented by suffix “U” , suffix “L” indicates long integer constant, suffix “LL” indicates long long integer constants.

Example2.1: 3462U an unsigned integer constant. 877325L is a long integer.

999928844LL is a long long Integer constant.

2.4.2 Real Constants Integer numbers are inadequate to represent quantities that vary continuously, such as

distance, height, temperature, price and so on. These quantities are represented by numbers containing

fractional parts like 17.543. The format that specifies this type of constants is %f(where „f‟ is called

conversion character). Real constants expressed in two forms

i) Fractional Form

ii) Exponent Form

Fractional Form

In this notation, the integer part and decimal part are separated by a period operator(.). It is possible to

omit digits before the decimal point or digits after the decimal points

Example2.2: 0.99 -0.85 243.124 215.0 0 .95 -0.71 .5

Valid examples Invalid examples(with reasons)

+1.43 -6.31

5.37

0.05

12,2.44(comma is not allowed) 343(decimal point must be present)

$14.3(special symbol is not allowed)

3.8 143(white space characters are not allowed)

Exponent Form

This form of representing a floating point constant is generally used if the value of the constant is either

too small (or) too large. This is also called scientific notation. The format that specifies this type of constants is %e (or) %E(where „e‟ (or) „E‟ is called conversion character). The general form for

representing this type of floating point value is:

The mantissa is either a real number expressed in fractional form (or) an integer with an optional + (or) –

sign. The exponent should be a decimal integer constant with an optional + (or) – sign. The mantissa and exponent can be separated by either „e‟ (or) „E‟. Since the exponent causes the decimal point to “float”,

this notation is said to represent a real number in floating point form.

Valid examples Invalid examples(with reasons)

0xa43

0Xabcd

0X9Ad5 0xe04

0124(0x should precede the number)

0x3.43(dot is not allowed)

143(not a hexadecimal integer) $0xaaa(special symbols are not allowed)

Mantissa E exponent

Page 25: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 25

Valid examples Invalid examples(with reasons)

+17.4e3 -6E-1

-0.03e+7

5e-5

5.32E-32

12,2e4(comma is not allowed) 17.6e-2.3(exponent should be an integer)

343(exponent should present)

$14.3E+56(special symbol is not allowed)

3.8 e-3(white space characters are not allowed)

2.4.3 Character Constants

i) Single character constants

ii) String constants

Single character constants

A single character constant contains a single character enclosed in a pair of single quotation marks. These character constants have integer values known as ASCII values. For example: „A‟ has an

ASCII value of 65. Since each single character constant represents an integer value, it is possible to

perform arithmetic operations on single character constants. The format that specifies this type of constants is %c(where „c‟ is called conversion character).

Valid examples Invalid examples(with reasons)

„a‟ „3‟

„<‟

„ „

„ab‟ (only one character is allowed) „‟ (at least one character should be specified)

„x (the character constant x should be enclosed in a pair of single

quotation marks)

Example2.3: printf( „%d‟,‟a‟);

would print the number 97, the ASCII value of the letter a. Example2.4: printf (“%c”, „97‟);

would output the letter „a‟

Since each character constant represent an integer value, it is also possible to perform arithmetic

operations on character constants. Example2.5: int i =10+‟a‟; would assign 107 to i.

String Constants

A string constant is a sequence of characters enclosed in double quotes .The characters may be letters, number, special characters and blank space. The format that specifies this type of constants is

%s(where „s‟ is called conversion character).

Example2.6: “Hello!” “1987” “WELLDONE” “! ---? +”.

Valid examples Invalid examples(with reasons)

”hello” ”143”

”1+43”

”a”

”7”

”A‟ (the string constant A should be enclosed in a pair of double quotation marks)

NOTE: 7 is a decimal integer constant

‟7‟ is a single character constant

”7” is a string constant

Remember that a character constant (eg „x‟) is not equivalent to the single character string constant

(eg, “x”). Further, a single character string constant does not have an equivalent integer value while a

character constant has an integer value, character strings are often used in programs to build meaningful

programs.

Rules for constructing constants

Page 26: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 26

i) An integer constant or a floating point constant must have at least one digit.

ii) Integer constant should not have a decimal point. iii) No commas (or) blank spaces (or) non-digit characters are allowed within an integer

constants (or) within a floating-point constant.

iv) An integer constant could be either +ve (or) –ve (+ve is default). v) While representing floating-point constants it is possible to omit digits before (or)

after the decimal point.

vi) In scientific notation of a floating-point constant, the exponent should be either +ve

integer (or) –ve integer. vii) The mantissa part and exponent part of a floating-point constant should be separated

by either „e‟ (or) „E‟.

viii)Mantissa can be either integer type (or) floating-point type with an optional + (or) – sign.

ix) The exponent must have at least one digit.

x) Single character constant should be enclosed in a pair of single quotation marks whereas string constant in double quotation marks.

xi) Only one character should be written within a pair of single quotes to represent single

character constant.

xii) A single character constant can be either a single alphabet (or) a single digit (or) a single special symbol enclosed in a pair of single quotes.

xiii)A string constant may contain any number of characters.

xiv) The letters, digits, special symbols or blank spaces are allowed in string constants. xv) A single character enclosed in a pair of single quotes is different from the same when

enclosed in pair of double quotes.

2.4.4 Backslash character constants C supports some special backlash character constants that are used in output functions.For

example the Symbol “/n” stands for new line character. A list of such backlash character constants is

given in the below table. Note that each one of them represents one character.

Character Constant Meaning

\n New line (Line break)

\b Backspace

\t Horizontal Tab

\f Form feed

\a Alert (alerts a bell)

\r Carriage Return

\v Vertical Tab

\? Question Mark

\' Single Quote

\'' Double Quote

\\ Backslash

\0 Null

2.5 DATA TYPES OF C The data type of a variable determines a set of values that a variable might take and a set of expressions

that can be applied to those values. Data types can be broadly classified as

i) Primary data types ii) Derived data types

iii) User defined data types.

Page 27: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 27

i) Primary data types

These are also called basic data types or fundamental data types. All C compilers support five fundamental data types.

Data type Keyword

Integer int

floating point float

double precession double

Character char

Void Void

These data types can have the

1. Size qualifier eg: short ,long and long long

2. Sign qualifier eg: signed and unsigned

NOTE: C99 support three more data types, namely bool, complex, imaginary

2.5.1 Integer data type Integers are whole numbers with a range of values supported by a particular machine. If a system

allocates 16 bits, to an integer, one size of integer value is limited to one range 32,768 to 32,767 (i.e-215

to 215

-1).

In order to provide some control over the range of numbers and storage space, C has four classes of integer storage, namely short int, long int, and long long int, in both signed and the unsigned forms.

Size and range of values of integer data types for 16 bit machine

Data type Size(bits) Range Default type

Int 16 -215

to 215

-1 signed int

unsigned int 16 0to 216

-1 unsigned

signed int 16 -215

to 215

-1 int

short int 16 -215

to 215

-1 short

unsigned short int 16 0to 216

-1 unsigned short

signed short int 16 -215

to 215

-1 short,signed short,short int

long int 32 -231

to 231

-1 long,signed long,signed

long int

unsigned long int 32 0to 232

-1 unsigned long

signed long int 32 -231

to 231

-1 long int,long signed

long

Declaration of integer variables will be as follows :

Example2.7: int l, m;

short a, b; same as short int a,b; long int p; same as long p;

unsigned int x; same as unsigned x;

2.5.2 Floating point data type Floating point numbers are stored in 32 bits (on all 16 bit machines),with 7 digit precision. Floating

point numbers are defined by the keyword float .When the accuracy provided by a float number is not

sufficient , the type double can be used to define the number . A double data type number uses 64 bits giving a precision of 15 significant digits .To extend the precision we may use long double which uses 80

bits.

Page 28: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 28

Size and range values of floating data types on 16 bit machine.

Data type Size(bits) Range Precision

float 32 3.4e-38 to 3.4e38 7 digits

double 64 1.7e-308 to 1.7 e 308 15 digits

long bouble 80 3.4e-4931 to 3.4 e 4932 20 digits

Floating point variables declaration is as follows: Example2.8: float a,b;

long float l,m;

double p,q; long double x,y;

2.5.3 Character data type A single character can be defined as a character type of data. Characters are stored on 8 bits of

space. The qualifier signed or unsigned may be applied to char .signed char have values between -128 to

127 and unsigned char have values between 0 to 255.

Character type variable declaration is as follows: char ch;

2.5.4 Void data type The void type has no value. This is usually used to specify the type of a function that does not

return any value to the calling function.

Example2.9: void main()

Also it is used to indicate the no data is passed from the calling function to called function through

arguments. The header of the called function will be of the form Return data type name(void);

Example2.10: void clear(void);

2.5.5 Complex data type

The variables of complex types can be declared by the type specifiers float complex, or double

complex , and long double complex. The type specifier complex and the macro I for representing

imaginary part and defined in the header file complex.h. the size of complex number of type float complex is 8 bytes and double complex is 16 bytes.

Example2.11: float complex z1; double complex z2;

complex z3;

z1=2+i3

2.5.6 Boolean data type

This data type is represented by the keywprd bool defined in stdbool.h this data type is used for

relational comparisons in logical operational. Boolean variable can take two values :1 for true and 0 for false , are defined in stdio.h

Example2.12: bool b; b=1;

B=x>y;

Page 29: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 29

2.5.7 Pointer type

A variable of pointer type can be declared similar to variables of other data types. At declaration pointer type can be distinguished by an asterisk „*‟ preceding the variable name

Example2.13: int x,*p;

float y,*q; p=&x;

q=&y;

A pointer can be printed out using the function printf() with the format specifier “%p”. Such as

printf(“the values of p is %p\n”,p);

2.6 DECLARATION OF VARIABLES

After designing suitable variable names, we must declare them to the computer. Declaration does two things

It tells the computer what the variable name is.

It specifies what type of data the variable will hold.

The declaration of variables must be done before they are used in the program.

The syntax for declaring a variable is as follows:

where v1,v2,v3….. are names of the variables. Variables are separated by commas.A declaration statement must end with a semicolon. valid declarations are

Example2.14: int count; char ch;

float rate,price;

double ratio; Program2.2 The program segment illustrates declaration of variables.

main()

{

/* declaration */ float x,y;

int code;

short count; long amount;

double deviation;

unsigned n; chat ch;

/* computation */

………….

………….. }

main() indicates beginning of the program

Declaration of variable is done at the beginning part.

2.7 ASSIGNING VALUES TO THE VARIABLES The values can be assigned to variables using assignment operator( = ) as follows:

Examples2.15: count=0; code=100;

data-type v1,v2,v3….vn

variable_name=constant;

Page 30: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 30

balance=87.96;

ch=‟y‟; C also permits multiple assignments in one line such as:

x= 3.5, y=78.4;are valid statements.

An assignment statement implies that the value of the variable on the left of the „equal‟ sign is set equal to the value of the quantity /expression on the right side. The statement

count=count+3;

means that the new value of count is equal to the old value of count plus 3. During assignment operation

C converts the type of value on right hand side to the type of value on the left. This may involve truncation when real value is converted to an integer.

Initialization:

It is also possible to assign a value to a variable at the time of the variable is declared. This takes the following form:

data-type variable_name=constant;

Example2.16: int final_value=100;

char yes=‟x‟; double balance=754.84;

The process of giving initial values to variables is called initialization. C permits more than one variable

initialization in one statement using multiple assignment operators. For example the statements

p=q=s=0; x=y= 45;

are valid.

Program2.3 /* assignment examples*/ main()

{

/*declarations*/

float x,p; double y,q;

unsigned k;

int m=54321; /*declarations& assignments */

long int n=1234567890;

/*assignments */ x=1.234567890000;

y=9.87654321;

k=54321

p=q=1.0; /*printing*/

printf(“m=%d\n”,m);

printf(“n=%ld\n”,n); printf(“x=%.12lf\n”,x);

printf(“x=%f\n”,x);

printf(“y=%.12lf\n”,y); printf(“y=%lf\n”,y);

printf(“k=%u p=%f q=.12lf\n”,k.p,q);

}

Output:

m=-11215

n=1234567890 x=1.234567880630

x=1.234568

y=9.876543210000

y=9.856743 k=54321 p=1.0000000 q=1.000000000000

Page 31: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 31

Here the variable m that has been declared as int is not able to store the value 54321 correctly instead it

contains some garbage value. Because maximum value that an int variable can store is 32767,if the program is executed on 16-bit machine.

The Variable k declared as unsigned has stored the value correctly.Unless specified otherwise printf()

function always display float or double values to six decimal places .

2.8 INPUT FUNCTION- scanf()

We can assign values to variable through assignment statements such as x = 5 a = 0 ; and so on.

Another method is to use scanf() function which can be used to read data from a key board. It is the general input function available in C Language. The general format of scanf() is as follows:

The control string contains format of the data being received. The ampersand symbol & before each

variable name is the operator that specifies variable name‟s address. The use of & is must in scanf() function.

Example2.17: scanf(”%d”,&x);

When this statement is encountered, the execution of program stops and waits for the value of the

variable x to be typed in .The format %d specifies that an integer value is to be read from the terminal, we have to type in the value in integer form. Once number typed and return key pressed, the next statement

in the program is executed.

Commonly used format specifications: %c – read a single character.

%d – read a decimal Integer.

%e – read a floating point value in exponential form.

%f – read a floating point value.

%i – read a decimal, hexadecimal or octal Integer.

%h– read a short integer.

%x – read a hexadecimal integer (unsigned) using lower case a – f.

%X – read hexadecimal integer (unsigned) using upper case A – F.

%o – read an octal integer.

%s – read a string

%u –read unsigned decimal integer.

%[ character set] –reads only the characters specified with in brackets when inputting string.

%[^character set] –The characters specified after ^(circumflex) are not permitted in the input .

2.9OUTPUT FUNCTION-printf()

printf() function in „C‟ allows you to display information required to the user and also prints the

values of variables. Output data can be written from computer to standard output device.

scanf(“control string”,&variable1,&variable2,….);

Page 32: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 32

Program2.4

#include < stdio.h > main ( )

{

printf (“Hello!”); printf (“Welcome to the world of Engineering!”);

}

Both the messages appear in the output as if a single line. If you wish to print the second message to the

beginning of next line, a new line character must be placed inside the quotation marks.

Program2.5

main()

{

printf(“Hello!\nWelcome to the world of Engineering”);

}

General format of printf() is as follows :

printf(“control string”,exp1,exp2,exp3,……);

The control string contains format of the data to be displayed and exp1,exp2,exp3…are output expressions. The function accepts a series of arguments, each applying to a conversion specifier in the

given control string , printf() prints the formatted information to the standard output device, usually the

display screen

Program2.6

#include<stdio,h>

main()

{

int a;

a=100;

printf(“value of a is %d”,a);

}

Here control string contains format specifier %d indicates a decimal integer to be displayed .a is the name

of the variable. If value of a is 100 the value 100 will be displayed on screen.

Program2.7 Program to read and print integer,float and character values

#include<stdio.h>

main()

{ int a;

float x;

char ch;

printf(“Enter value of a”);

Output: Hello!Welcome to the world of

Engineering.

Output:

Hello!

Welcome to the world of Engineering

Output:

value of a is 100

Page 33: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 33

scanf(“%d”,&a);

printf(“Enter value of x”);

scanf(“%f”,&x);

printf(“Enter any character ”);

scanf(“%c”,&ch);

printf(“ \n a is %d”,a);

printf(“\n x is %f”,x);

printf(“\n ch is %c”,ch);

}

Program2.8 Program to read and display octal &hexadecimal integers

#include <stdio.h>

main()

{

int i ,j;

printf("Enter any octal integer");

scanf(" %o",&i);

printf("Enter any Hexadecimal integer");

scanf(" %x",&j);

printf("\nOutput values\n");

printf("\n octal integer i is %o ", i);

printf("\n octal integer i equivalent decimal value %d ", i);

printf("\n hexadecimal integer is %x", j);

printf("\n hexadecimal integer j equivalent decimal value %d ", j);

}

Program2.9 Using printf() to display numerical values.

#include <stdio.h>

main()

{

int a = 2, b = 10, c = 50;

float f = 1.05, g = 25.5, h = -0.1;

printf("\nDecimal values without tabs: %d %d %d", a, b, c);

printf("\nDecimal values with tabs: \t%d \t%d \t%d", a, b, c);

printf("\nThree floats on 1 line: \t%f\t%f\t%f", f, g, h);

Output:

Enter any octal integer

34

Enter any Hexadecimal integer

E

Output values

octal integer i is 34

octal integer i equivalent decimal value 28

hexadecimal integer is E

hexadecimal integer j equivalent decimal value 14

56 65.8 ‘y’

a x ch

Output: Enter value of a 56 Enter value of x 65.8 Enter any character y a is 56 x is 65.800000 ch is y

Page 34: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 34

printf("\nThree floats on 3 lines: \n\t%f\n\t%f\n\t%f", f, g, h);

printf("\nThe rate is %f%%", f);

printf("\nThe result of %f/%f = %f\n", g, f, g / f);

}

Output: Decimal values without tabs: 2 10 50

Decimal values with tabs: 2 10 50

Three floats on 1 line: 1.050000 25.500000 -0.100000

Three floats on 3 lines:

1.050000

25.500000

-0.100000

The rate is 1.050000%

The result of 25.500000/1.050000 = 24.285715

Program2.10 C program for simple interest calculation

#include<stdio.h> main()

{

int p,n,; float r,si;

printf("\n Enter values of p,n,and r");

scanf("%d %d %f",&p, &n, &r);

si=(p * n * r )/ 100; printf("simple interest =rs. %f",si);

}

Program2.11 C program to add two integers

#include<stdio.h>

main()

{ int a,b,c;

printf("\n Enter value of a");

scanf("%d ",&a);

printf("\n Enter value of b"); scanf("%d ",&b);

c=a+b;

printf("sum is %d ",c); }

2.10 OPERATORS AND EXPRESSIONS C supports a rich set of built in operators. C Operators can be classified into the following categories.

i) Arithmetic operators

ii) Relational operators

iii) Logical operators

Output:

Enter values of p,n,and r

200 2 2

simple interest =rs. 8.000000

Output:

Enter value of a 5

Enter value of b 6

sum is 11

Page 35: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 35

iv) Assignment operators

v) Increment and Decrement operators vi) Conditional operators (Ternary operator)

vii) Bitwise operator

viii) Special operator

Expression Variables and constants connected by operator is called expression.

2.10.1 Arithmetic operators

Arithmetic operations involve negation, addition, subtraction, multiplication and division as shown in the

following table.

Operator Operation Description

- -x Negation

+ +x Unary plus

+ x+y Addition

- x-y Subtraction

* x*y Multiplication

/ x/y Division

% x%y modulus

i) The expression i % j would result in the remainder of i divided by j.

Example2.18: int i= 10, j=3, k;

k=i%j; 1 is assigned to the variable k.

ii) The modulus operator can be used only with integer operands.

Example2.19: float x, y, z;

z=x % y; is not valid.

iii) All other operators can be applied to operands of the arithmetic type, which consists of integer,

floating point or complex types.

iv) When both the operands in an expression are integers, the expression is called integer expression. Integer arithmetic leads an integer value.

Example2.20: 25/7=3, 3/4=0, 4/3=1

v) When both operands are floating point type the expression is called floating point type expression.

Example2.21: x=5.2, y=1.42;

z=x/y;

vi) When one of the operand is real and the other is integer the expression is called a mixed mode

expression. The result is floating point type value. Example2.22: 23/5.0=4.6

vii) If an expression contains more than one arithmetic operator than they are executed from left to right

in the following order i) unary minus and unary plus

ii) *, / , %

iii) + , -

Page 36: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 36

Example2.23: 3+5/2*4-10+17%6 is evaluated as 3+((5/2)*4)-10+(17%6)

The result of the expression is 6

2.10.2 Relational Operators Relational Operators are used to compare the values of two expressions. An expression such as

a < b, n! =0, p>q

containing a relational operator is termed as a relational expression .The value of a relational expression

is either one or zero. It is one if the specified relation is true and zero if the relation is false.

Relational Operators

Operator Operation Description

< x < y less than comparison

< = x < = y lesser or equal comparison

= = x = = y equal comparison

>= x >= y grater or equal comparison

> x > y greater comparison

!= x != y not equal comparison

Example2.24: int i=5,j=3,k;

k= (i<j); 0 is assigned to k

k= (i==j); 0 is assigned to k

k= (i>=j); 1 is assigned to k

2.10.3 Logical Operators

There are three logical operators

Operator Operation Description

! ! x logical negative operation

&& x && y logical AND operation

|| x || y logical OR operation

i) ! (NOT) If the operand of the unary logical negative operator ! is nonzero, the result is true otherwise,

the result is false The truth table for the NOT operator is

exp !exp

1 0

0 1

Example2.25: !0=1

!3.7=0 ! (20)=0

Example2.26: int a=5, b=6, c;

c=! (a>b);

The value 1 is assigned to the variable c.

ii) && (AND) is used to check whether both the expressions are non-zero or not.

The truth table for AND operator is

Page 37: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 37

exp1 exp2 exp1&&exp2

1 1 1

1 0 0

0 1 0

0 0 0

Example2.27: To check whether the values of three variables a,b,c form the sides of an equilateral triangle the following code may written

if(a==b && b==c )

printf(“The values of a,b,c form an equilateral triangle”);

else printf(“ The values of a,b,c don‟t form an equilateral triangle”);

Consider the expression exp1&&exp2.

exp2 is evaluated only when exp1 is non-zero.

Example 2.28: int i=6,j=3,k;

K=(i>5)&&(j=i+3); printf(“k=%d j=%d\,n”,k,j);

output: k=1 j=9

Example2.29: i=6,j=3,k;

k=(i<5)&&(j=5+10); printf(“k=%d,j=%d”,k,j);

output: k=0,j=3

iii) || (OR) operator is used to check any one of the values of two expression is non-zero. The truth table for OR operator is

exp1 exp2 exp1||exp2

1 1 1

1 0 1

0 1 1

0 0 0

Example2.30: To check whether the values of three variables a,b,c form the sides of an isosceles triangle the following code may written

if(a==b || b==c || a==c)

printf(“The values of a,b,c form an isosceles triangle”);

else printf(“ The values of a,b,c don‟t form an isosceles triangle”);

Consider the expression exp1||exp2. If exp1 is true then exp2 is not evaluated.

Example2.31: Result always true

int i=6,j=3,k;

k=(i>5)||(j=i+3); printf(“k=%d j=%d\,n”,k,j);

output: k=1 j=3

Example2.32: i=6,j=3,k; k=(i<5)||(j=5+10);

printf(“k=%d,j=%d”,k,j)

output : k=1,j=13

Page 38: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 38

2.10.4 Increment and decrement operators(++ and--)

These two operators are unary operators. They exists in two forms i.e. pre and post(prefix and postfix)

i) Increment operator(++)

Increment operator is used to increment the value of its operand by 1.General form for pre incrimination is

and post incrimination is

where the operand must be a variable but cannot be constant or expression.++operand is called pre increment or prefix increment and operand++ is called post increment or postfix increment

Example2.33: pre incrementation

int i=20; ++i;

printf(“i=%d”,i);

output: i=21

Example2.34: post incrementation int i=20;

i++;

printf(i=%d”,i); output:i=21;

In the above example prefix and postfix operation results in the same output. The prefix and postfix

operations differ in the value used for the operand when it is embedded inside expressions Example2.35: int x=10,y;

y=++x;

printf(“x=%d,y=%d”,x,y);

output: x=11,y=11 Here x value is incremented before it is assigned to y. So the expression y = ++x is equivalent to the two

expressions x=x+1 and y=x

Example2.36: int a=5,b; b=++a*4;

printf(“a=%d,b=%d”,a,b)

output: a=6,b=24

Example2.37: int x=10,y; y=x++;

printf(“x=%d,y=%d”);

output: x=11,y=10 Here value of x is incremented after it is assigned to y, thus the expression y=x++ is equivalent to the

expressions y=x and x=x+1;

Example2.38: int a=5,b; b=a++*4;

printf(“a=%d,b=%d”,a,b);

output: a=6,b=20

Note: ++4 and ++(x+y) are invalid expressions.

ii) Decrement operator ( - - ) This operator is used to decrement the value of the operand by 1.

++ operand

operand ++

Page 39: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 39

General form is

--operand

or

operand--

where the operand must be a variable but cannot be constant or expression.--operand is called pre

decrement or prefix decrement and operand-- is called post decrement or postfix decrement

Example2.39: int i=10;

--i; printf(“i=%d”,i ) ;

output: i=9

Example2.40: int i=10; i--;

printf(“i=%d”,i);

output: i=9; In the above example both the prefix and postfix operations results in the same value.

Example2.41: int a=10,b;

b= -- a*3; printf(“a=%d,b=%d\n”,a,b);

output: a=9,b=27

Example2.42: int a=10,b; b=a--*3;

printf(“a=%d,b=%d\n”,a,b);

output: a=9,b=30

2.10.5. Assignment Operators

There are three forms of assignment: simple assignment, multiple assignment and compound

(short hand) assignment.

i) Simple assignment

The operator used is „=‟.

The general form is

The value of the expression is evaluated first and is assigned to the variable. The evaluation of the expression is right to left.

Example2.43:

x=10 a=10 && 5 y=12.5 a=x>y

a=”A”

area=0.5*b*h.

Note:

= is the assignment operator used to assign right side expression value to the left hand side variable.

= = is comparison operator to compare the value of left hand and right hand side expression.

a=b will assign b value to a a==b will compare the values of a and b for equality.

ii) Multiple assignment This is used to assign the value of an expression to two or more variables.

Variable name=expression;

Page 40: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 40

The general form is

The value of the expression is assigned to the variables v1, v2, v3 etc. the evaluation is right to left. Example2.44: a=b=0.

a=b=x+y

The value of x+y is assigned to b and then the value of b is assigned to a.

iii) Compound assignment Compound assignment is a short hand notation for a simple assignment.

The compound assignment operators are

+ =, - =, * =, / =, % =. To evaluate a compound assignment expression, first change it to a simple expression.

Compound assignment Equivalent simple expression

x+=expression x=x+expression

x-=expression x=x-expression

x*=expression x=x*expression

x/=expression x=x/expression

x%=expression x=x%expression

Example2.45: a*=b+3 is evaluated as a=a*(b+3)

sum+=x is evaluated as sum=sum+x

a%=10 is evaluated as a=a%10.

2.10.6. Conditional operator

The operator symbol is ?.This is also called ternary operator. The conditional operator has three

expressions. The general form is

This is called conditional expression.

First, expression1 is evaluated, if the result is non-zero, the expression2 is evaluated and its value is the

final result. Otherwise, expression3 is evaluated and its value is the final result.

Example2.46: To find the biggest of two numbers

big= (a>b)? a: b; This is equivalent to the if –else statement

if (a>b)

big=a; else

big=b;

Example2.47: To check an integer is even or odd

(n%2)? printf (“Given integer is odd\n”): printf(“Given integer is even\n”); This is equivalent to the statement

if(x%2)

printf(“given integer is odd\x”); else

printf(“given integer is even\x”);

v1=v2=v3=expression;

expression1?expression2:expresssion3

Page 41: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 41

Example2.48:To find absolute value of an expression y=(x>=0)? x: -x;

Example2.49: To evaluate the function defined by

F(x)= x2-x+1 of x>=0

x2+x+1 of x<0

fx=(x>=0)?(x*x-x+1):(x*x+x+1);

Note:Conditional expression may be nested

Example2.50: To find the biggest of three numbers

big=(a>b)?((a>c)?a:c):((b>c)?b:c);

Although conditional expression is nested, it is not recommended.

2.10.7 Special operators

The special operators are i) comma operator(,)

ii) sizeof operator

iii) address operator(&),

iv)indirection operator(*) v) cast operator

i) Comma operator The comma operator is used to combine two more expressions into a single expression. The general form is

The expression are evaluated from left to right and the value of the right most expression is the result of

the overall expression.

Example2.51: int i=10,j; j= ( i+=5, --i , i+20);

j is assigned the value 34.

Example2.52: int m=5,n;

n=(m+=5,m%3);

n is assigned the value1.

Example2.53: swapping of two integer variable using the comma operator temp=a , a=b , b=temp;

The comma operator is most often used in for statement expressions to combine two or more expressions

in initial expression. And to combine increment or decrement in the third expression

Example2.54: for(i=1 , j=10 ; i<j ; ++i , --j)

{ statements;

}

ii) size of operator

This operator is used to determine the number of bytes required to store a particular data type item in the memory.

General form is

where the operand may be name of the data type or constant or variable or expression.

expression1,expression2,---

,expressionN

sizeof(operand)

Page 42: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 42

Example2.55: printf(“char size is %d bytes\n” , sizeof (char)); printf(“long int size is %dbytes\n” , sizeof(double));

printf(“double size is %dbyte\n”,sizeof(double));

Example2.56: sizeof(13.56)

sizeof(239462l)

sizeof(896254ll)

sizeof(„*‟) sizeof(a+b)

iii) address operator

General form is

Where the operand must be a variable name.This operator is used to determine the address of the memory location allotted to a variable.

Example2.57: int x=10,*p;

p=&x; &x represent the address of the memory location allotted to the variable x and it is assigned to

the pointer p.

iv) Indirection operator

General form is

Where the operand must be a pointer.This operator is used to get the value at the address represented by the pointer. This operator is also called de-referencing operator or value at address operator.

Example2.58: int x=10,y,*p;

p=&x;

y=*p; The value 10 of x is assigned to the variable y.

The expression y=*p is equivalent to the expression y=x.

v) Cast operators These operators are used to convert the data type of operand explicitly to another type.

The general form is

Where datatype is int, double, char , pointer etc.

Example2.59:(int)9.3 ,(double)15,(float)327,3/(int)7.2,(int)8.5/(int)4.3

Example2.60: int a=10,b=6; float x;

x=(float)a / (float)b;

The values of a and b are substituted in the right side expression in floating point mode and the value assigned to x is1.6666666

p

3472 10

x

3472

&operand

*operand

(data type name)expression

Page 43: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 43

2.11 OPERATOR PRECEDENCE AND ASSOCIATIVITY Precedence is used to determine the order in which different operators in a complex expression

are evaluated.

Associativityisused to determine the order in which operators with the same precedence are evaluated in a complex expression.

The precedence and associativity of different categories operators is presented in the following table:

Operators Associativity

1 ( ),[ ], . , -> L to R

2 ( ++ prefix), ( -- prefix), unary +, unary -,

& (address), *(indirection), cast, !(negation)

R to L

3 *, /, % L to R

4 +, - L to R

5 <, <=, >, >= L to R

6 = =, != L to R

7 && L to R

8 | | L to R

9 ? : R to L

10 =, +=, *=, -=, /=, %= R to L

11 , (comma operator) L to R

Example2.61: 2+3*4 is evaluated as 2+(3*4) and the result of the expression is 14 Example2.62: 3*8/4%5*2

Here we have four operators of the same precedence (* / % *). As the associativity of arithmetic operators

is left to right. The expression 3*8/4%5*2 is evaluated as

(((3*8)/4)%5)*2 and the result of the expression is 2. Example2.63: a+=b*=c - =5

As the associativity of assignment operators is right to left, the above expression is evaluated as

(a +=(b*=(c - =5))) Which is expanded to (a=a+(b=b*(c=c-5))).

Example2.64: -b++

Here postfix increment has higher precedence than unary -. Thus the above expression is evaluated as (-(b++)).

If b is 6, then the result of the expression is -6. After the expression is complete 6 becomes 7.

Example2.65: int a =5,b=6,c;

c=a!=b; The expression contains the assignment operator (=) and the relational operator (!=).As the relational

operator has higher precedence over assignment operator the expression a!=b is evaluated first and the

result 1 is assigned to c.

2.12 TYPE CONVERSION

There are two types of type conversions in expressions.

i) Implicit type conversion. ii) Explicit type conversion.

i) Implicit type conversion

C permits mixing of constants and variables of different types. A data type that occupies less memory will be converted automatically to a data type that occupies more memory space without losing

any information.

Example2.66: If one operand is int and the other is float, int is converted to float. If one operand is double and the other is long double, double is converted to long double.

Page 44: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 44

If a char and double are combined, char is converted to double.

The hierarchy of type conversion is summarized in the following table:

Data type Order

long double complex high

double complex float complex

long double

double

float unsigned long long

long long

unsigned long long

unsigned int

int unsigned short int

short int

unsigned char

char low

ii) Explicit type conversion

For explicit type conversion type casting is used. The general form of a cast is:

(data type name) expression

Where data type name is one of the basic data types.

Example Action

x= (int) 3.7 3.7 is converted to integer by truncation

x= (int) 13.7/ (int) 4.3 Evaluated as 13/4 and the result would be 3 x= (float) (a + b) the result of the expression a + b is converted to float

p= cos( (double) x) converts x value to double before using it.

SUMMARY

C is a high level programming language. C language has 32 keywords and each of them has a fixed

meaning and form the building blocks for the programming statements. There are five basic data types in

ANSI C ,namely int, float, double, char and void .C99 has three more data types, namely complex, bool and pointer. Except void other data types has qualifiers signed and unsigned, long, short and long long.

System will allocate three different size of space for each variable. Constants in C have fixed values. C

language is rich in operators and it contains 8 categories of operators: arithmetic, relational, logical, increment and decrement, assignment, condition, bitwise and special operators. Expressions are formed

with variables, constants and operators. These operators certain precedence and associativity. If an

expression contains operands belonging to different data types automatic type conversion takes place according to the predefined rules. Forced type conversion is also possible through cast operator.

EXERCISES

Multiple Choice Questions

2.1 Which of the following is not a keyword in C? a)const b)main c)case d)void

2.2 An identifier cannot start with

Page 45: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 45

a) underscore b)uppercase alphabet c)lower case alphabet d)#

2.3 Which of the following is not a basic data type in C? a) int b)double c)void d)printf

2.4 Which of the following is not a library function in C?

a) clrscr() b)exit() c)goto() d)getch() 2.5 What is the output of the following code?

char ch=‟A‟;

printf(“%d”,ch+10);

a)10 b)75 c)74 d)65 2.6 Regarding real values in C, which of the following is true?

i) A float occupies less memory than a double.

ii) The range of real numbers that can be represented by a double is less than those represented by a float

a) only option i b)only option ii c)both i and ii d)neither i nor ii

2.7 Which of the following statements is/are true? i)A char data type variable always occupies 1 byte independent of system

architecture.

ii)sizeof is a key word

iii)include is a key word. iv)double is not a keyword.

a) both i&ii b) i only c)ii only d)neither i nor ii

2.8 The operator %d yields a) Quotient value b)Remainder value

c)percentage value d)fractional part of the division.

2.9 What is the wrong assignment expression in the following? float a ,b, x=8.2 , y=6.3;

a) a=x%6 b)b=x>y c)a=x+y/3.5 d)x-y*3.6

2.10 The modulus operator can be applied only to _____ types

2.11 What is the value assigned to x when the following statement is executed? x = 2*8*6/ 15%13;

a) 96 b) 0 c) 13 d) 6

2.12 What is the output when the following program is executed? #include<stdio.h>

main()

{

int x = 10; printf(“ %d , %d, %d “, x < = 20, x= 25, x >= 5);

}

a) 1,25,1 b) 1, 1, 1 c) 0, 1, 1 d) 0,25,1

2.13 What value is assigned to x?

x=8&&9; a) 8 b) 9 c) 0 d) 1

2.14 What value is assigned to a?

a=5&&0; a) 5 b) 50 c) 0 d) 1

2.15 Expression (x<5||a>b) is true only if ____ a) both x<5 and a>b are true b) x<5 is true c) a>b is true d) any one of x<5 and a>b are true

2.16 Which of the following represents true statement either x is in the range of 10 and 50 or y is 0?

Page 46: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 46

a) x>=10&&x<=50||y==0 b)x<50 c)y!=10 d) x>=10|| x<=50||y==0

2.17 Write the C expression for the following mathematical expression .

1<x≤20 or 3≥y≥1

a) 1<x<=20 || 3>=y>=1 b) 1<x<=20 || 1<=y<=3 c) (1<x && x<=20) ||(3>=y && y<=1) d) (1<x &&<=20) ||(3>=y &&<=1)

2.18 What is the output of the following code?

int x=20,y=16,z;

z=(x<y)&&(y+=2); printf(“y=%d,z=%d”,y,z);

a) y=16,z=0 b) y=18,z=0 c) y=16,z=1 d) y=18,z=1

2.19 What will be output of the following program? #include<stdio.h>

int main()

{ int a=2,b=7,c=10;

c=a==b;

printf("%d",c);

return 0; }

a) 2 b)0 c)1 d)10

2.20 What is the value assigned to a? int x = 5, y = 3, z = 4, a;

a = x = y ==z;

a) 5 b)3 c)4 d)0 2.21 What is the output of the following program?

#include<stdio.h>

main()

{ int x=3, y=5, z=7, a;

a = x += y%= z -= 6;

printf( “a = %d”, a); }

a) 0 b) 8 c) 4 d)3

2.22 What is the value assigned to k when the following statements are executed?

int k,a=5,b=3,c=10; k=(a+=b*=c-=6);

a)17 b)12 c)10 d)5

2.23 What is the output when the following code is executed? #include<stdio.h>

main()

{ int x=10,y=15,a,b;

a=x++;

b=++y;

printf(“%d , %d ”,a,b); }

a)10,16 b)11,15 c)11,16 d)10,15

2.24 Which is not a valid expression? a)-p++ b)++p-- c)++6 d)+x++

2.25 What is the value assigned to C?

Page 47: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 47

int a=10,b=6,c;

c=a++*b; a)66 b)60 c) 16 d) 70

2.26 What is the value assigned to a?

int a, x=2; a = x + 3 *++ x;

a) 11 b) 9 c) 12 d) 15

2.27 What is the output of the following program? #include<stdio.h>

main()

{ int x= 5;

printf(“ %d , %d , %d”, ++x, x , x ++);

} a) 7,6,6 b) 6,6,6 c)6,6,7 d)7,6,5

2.28 What is the output of the following code?

int a=10;

printf(“a=%d”,a++); a)a=10 b)a=11 c) 10 d)11

2.29 What value is assigned to k when the following statements are executed?

int i=8,j=20,k; k=(++i, j--, i+j );

a) 171 b)180 c)168 d)16

2.30 What value is assigned to c? int a = 3, b = 2, c=5;

c = a * b > = c;

a) 1 b) 0 c) 6 d) 5

2.31 What value is assigned to the integer variable a? a = ½ + ½ == 0;

a) a b)0 c) 2 d) none of these

2.32 What is the output when the following program is executed? #include<stdio.h>

main()

{

int a = 5, b = 0, c ; c = a || b ++ ;

printf (“b = % d, c = %d”, b, c);

} a) b=1,c=5 b) b=0,c=5 c) b=1,c=1 d)b=0,c=1

2.33 What is the output when the following program is executed?

#include<stdio.h> main()

{

int a = 5, b = 0, c ;

c = a && b ++; printf ( “ b = %d, c = %d \n”, b, c);

}

a)b=0, c=5 b) b=0, c=6 c) b=1, c=0 d) b = 1, c = 1 2.34 What is the output when the following program is executed?

Page 48: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 48

#include<stdio.h>

main() {

int i = -3, j=2, k=0, m;

m= ++i && ++j || ++k; printf(“ i = %d, j = %d, k = %d, m=%d\n”, i, j, k, m );

}

a)i= -2 , j=3 , k= 1 , m= 1 b) i= -2 , j= 3 , k=0 , m= 1

c) i= -2 , j=3 , k=0 , m= 1 d) i= -2 , j=3 , k= 1 , m= 0 2.35 What is the output when the following program is executed?

#include<stdio.h>

main() {

int a = 0, b = 0, c;

c = (a+=2) && (b - = 1); printf ( “ a = %d, b = % d, c= %d \n “, a, b, c);

}

a) a= 2 , b= 1 , c=0 b) a= 2 , b=-1 , c=1 c) a= 0 , b=0 , c=1 d) a=2 , b=-1 , c=0

2.36 What is the output when the following program is executed? #include<stdio.h>

main()

{ int a=5,b,c;

b=++a;

c=a++; printf(“a=%d,b=%d,c=%d”,a,b,c);

}

a) a=6 , b= 6 ,c=6 b) a=6 , b=6 ,c=7 c) a= 7 , b=6 ,c=6 d) a=7 , b= 6 ,c=7

2.37 What is the value of i and j #include<stdio.h>

void main()

{ int i=3,j;

j= i++ + ++i;

printf("%d, %d",i,j);

} a)8,7 b)5,9 c)5,8 d)5,7

2.38 What will be the output of the following program?

#include<stdio.h> int main()

{

int i=5; i=2+2++*i;

printf("%d",i);

return 0;

} a)17 b)12 c)20 d)syntax error in the program

2.39 What are the values of k and i?

#include<stdio.h> void main()

{

Page 49: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 49

int i=5,k;

k= ++i + --i; printf(“k=d, i=%d”,k,i );

}

a) k= 10 , i=5 b) k= 10 ,i=6 c) k=9, i=5 d)k=8,i=5 2.40 What is the output when the following code is executed?

main()

{

int a=20,b; b=(a==1)?2:3;

printf(“\n a=%d,b=%d\n”,a,b);

} a)a=20,b=2 b)a=1,b=2 c)a=20,b=3 d)a=1,b=3

2.41 What is the output when the following code is executed?

int a=5,b=6,c; c=(a+b>a-b)?a*b : a%b ;

a)30 b)5 c)0 d)6

2.42 Whch of the following is a ternary operator?

a) ?: b)* c)sizeof d)&& 2.43 What is the output of the following program?

#include<stdio.h>

main() {

int a = 5, b = 6, c ;

c = a < b ? a : a > b ? b : -1; printf ( “ c = %d \n”, c );

}

a)c= -1 b) c= 6 c)c=5 d)c=0

2.44 What will be output of the following program? #include<stdio.h>

void main()

{ int x;

x=(10,20,30);

printf("%d",x);

return 0; }

a)10 b)30 c)20 d)none of these

2.45 Which of the operator is having highest precedence? a) ,(comma) b)++ c)= d)&&

2.46 What is the output when the following program is executed?

#include<stdio.h> void main()

{

float a= 7.8, b= 3.95, c, d;

c = (int) (a/b) ; d = (int) a / (int) b;

printf( “ c = %d, d = %d \n”, c, d );

} a) c=1 ,d= 2 b) c=2,d=2 c) c=1 ,d=1 d)c=1,d=0

Page 50: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Basics of C 50

Comprehensive Questions

2.1 What is the character set in C? write the syntax to declare and initialize int, float, character and double type.

2.2 Discuss different built in data types available in C and give their size and range.

2.3 What are the different types of variables used in C programming? How do you assign values to them?

2.4 Describe the format, width and search set for a scanf() statement in C with examples.

2.5 Explain the increment and decrement operators with suitable examples.

2.6 Explain the conditional operator with examples. 2.7 Explain the relational and logical operators with examples.

2.8 Explain the assignment operators, comma operator and sizeof operator with examples.

2.9 Explain arithmetic and relational operators with examples. 2.10 Explain the arithmetic and logical operators with examples.

2.11 What is conditional operator? Using conditional operator write a program to check whether a

number is even or odd. 2.12 Explain operator precedence and associativity rules followed in C through examples.

2.13 Discuss the implicit and explicit type conversion during expression evaluation.

2.14 Area of a triangle is given by the formula A = √s(s-a)(s-b)(s-c) where a,b,c are the sides of the

triangle and s= (a+b+c)/2. Write a program to compute area of triangle given the values of a,b and c.

2.15 The solution to system of equation a1x + b1y =c1 and a2x + b2y = c2 is given by

x= (c1b2 –c2b1)/(a1b2 – a2b1) y=(a1c2 –a2c1)/(a1b2 – a2b1)

Write a program to calculate and print the values of x and y.

2.16 A student appeared for an examination in 3 subjects. He will pass the examination if he secures at least 40% marks in each subject. Write a program to accept the percentage marks in three subjects

from keyboard and check whether the student passed or failed the examination using conditional

operator.

2.17 Suppose that an automobile starts from rest and has constant acceleration „f‟ for „t‟ seconds. The final velocity „v‟ and the distance travelled „d‟ by the automobile is given by the formula

v = u+ft and d = ut+1/2ft2

Write a program that reads f and t and prints t, d and v. 2.18 Write a program to read three numbers x1, x2 and x3 and compute their average „x‟ standard

deviation „sd‟ and the relative percentage „rp‟ for each number where

x= (x1+x2+x3)/3 sd2 = (x1

2 + x2

2 + x3

2- 3x

2)/3

rp1= (( x1+ x2 + x3)/x1) * 100 and similarly for rp2 and rp3. Output the average standard deviation and the three relative percentages.

2.19 Distance between two points (x1,y1) and (x2,y2) is governed by the formula D2=(x2-x1)

2+(y2-y1)

2

Write a program to compute D given the coordinates of the points 2.20 The straight-line method of computing the yearly depreciation of the value of an item is given by

Depreciation=(Purchase Price-Salvage Value)/Years of Service

Page 51: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 51

Chapter 3

CONTROL STATEMENTS

LEARNING OBJECTIVES

After going through this chapter, the readers will be able to:

Learn different types of statements in C.

Develop algorithms and flow charts for simple engineering and mathematical problem

solving.

Write programs using if, if-else, nested if, nested if-else and else-if ladder.

Write programs using the looping structures while, do-while & for.

Learn usage of Jumping Statements: break, continue & goto in the programs.

3.1 INTRODUCTION

Control Statements determine the “flow of control” in a program and enable to specify the order in which the various instructions in a program are to be executed by the computer. Normally high level

procedural programming languages require three basic control instructions.

Sequential control instructions

Decision and Selection control instructions

Repetition or Loop or Iterative control instructions

Jumping statements

The common thing shared by all the programs written so far is that in each of the programs, all the

statements from the first statement till the last statement get executed without fail in a serial manner. That

is, one after the other. This kind of execution of statements in a program is called Sequential Execution.

The programming circumstances require selecting some statements for execution if some condition

is satisfied; and skipping the block of statements if the condition is not satisfied, thereby, resulting in a change in the order of execution of statements. To be precise, selection of some statements for execution

depends on whether a condition is true or false. This kind of execution of statements is called

Conditional Execution or Selection.

Suppose, if there is a need for a group of statements to be executed repeatedly until some logical

condition is satisfied, then looping is required in the program. This can be carried out using various Loop

or Repetitive or Iterative control statements.

The Jumping statements are used to exit from loop or to go to the next repetition of the loop after

skipping the remaining statements of the loop or to transfer control from one part of the program to another part of the program unconditionally.

The sequential control instruction ensures that the instructions are executed in the same order in

which they appear in the program. Decision and selection control instructions allow the computer to take decision as to which instruction is to be executed next. The loop control instruction helps computer to

execute a group of statements repeatedly.

Decision and Selection control instructions allows a program to take different courses of action

depending on different conditions. C provides two selection structures.

if

switch

Page 52: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 52

Repetition or loop control instruction allows a program to execute the same section of code more

than once. A section of code may either be executed a fixed number of times, or while some condition is true. C provides three looping statements.

while

for

do-while

C provides three jumping statements

break

continue

goto

3.2 SIMPLE & COMPUND STATEMENTS

3.2.1 Simple statements

A single statement is called a simple statement.

Assignment: A = A + 1;

Input: scanf(“%d”,&x); goto: goto begin;

The C language uses semicolons as statement terminators. A semicolon follows every simple (non-

compound) statement.

Example3.1: if(x==y)

printf(“x and y are equal”);

If the values of the variables x and y are same, then only the printf() statement gets executed. Otherwise, it is skipped.

3.2.2 Compound statements

A set of simple or compound statements enclosed within a pair of opening and closing braces is

called a Compound Statement.

The terms compound statement and block both refer to a collection of statements that are enclosed in

braces to form a single unit. Compound statements have the form

Example3.2: {

printf(“….”);

scanf(“%d”,&a); if(a>max)

max=a;

}

Example3.3: if(flag==1) {

printf(“…”);

scanf(“%d”,&b); }

Page 53: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 53

3.3 NULL & EXPRESSIONS STATEMENTS

3.3.1 Null Statement

A "null statement" is an executable statement containing only a semicolon; it can appear wherever a statement is expected. Nothing happens when a null statement is executed. The null statement is:

Statements such as do, for, if, and while require that an executable statement appear as the statement body. The null statement satisfies the syntax requirement in cases that do not need a substantial statement

body.

This example illustrates the null statement:

Example3.4: for(i=0;i<10;line[i++]=0) ;

In this example, the loop expression of the for statement line[i++] = 0 initializes the first 10 elements of line to 0.

3.3.2 Expression-statement

All side effects from the expression evaluation are completed before the next statement is executed.

The following are the expression statements.

Example3.5: x=(y+3) /* x is assigned the value of y+3 */

x++; /* x is incremented */

x=y=0; /* both a and y are initialized to 0 */

proc(arg1,arg2); /* function call returning void */

y=z=(f(x)+3); /* a function-call expression */

3.4 DECISION-MAKING AND BRANCHING (SELECTION)

i) if-statement

ii) switch-statement

3.4.1 if-statements

The different forms of if- Statements are

i) The simple-if statement. ii) The if-else Statement.

iii) The Nested if- else Statement.

iv) The else-if Ladder.

3.4.1.1 The Simple if statement

It is used to execute an instruction or block of instructions only if a condition is fulfilled.

;

expression;

Page 54: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 54

The syntax is as follows:

The above flow chart reflects the logical flow of the if statement. Where condition is the expression that

is to be evaluated .If this condition is true (non-zero), statement is executed. If it is false(zero), statement is not executed and the program continues to the next instruction after the conditional statement.

Example3.6: if(a==b)

printf(“a and b are equal”);

if the values a and b are equal, then only the printf() statement gets executed. Otherwise, it is skipped.

Example3.7: if((a>b)&&(a>c))

printf(“a is the largest”);

If the value of the variable a is greater than the values of both b & c, then only the printf () statement gets

executed. Otherwise, the statement is skipped.

Example3.8: if(n%2)

printf(“n is odd”);

If the value of the variable n is not divisible by 2, i.e. if the remainder after division of n by 2 is 1, then

only printf () statement gets executed. Otherwise, the statement gets skipped.

Example3.9: if(a>b)

{ t=a;

a=b;

b=t;

} Only when the value of a is greater than the value of b the statements within the pair of braces gets

executed. Otherwise, the statements are skipped.

3.4.1.2 The if-else statement

If-else structure acts as a selector of one block of statements out of two blocks.

The syntax of the if-else statement is as follows:

True

False

Exit

Statement

Condition

? if(condition)

statement;

Page 55: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 55

True

The above flow chart reflects the logical flow of the if-else statement.

If test-expression evaluates to true, statement 1 will be executed, otherwise, statement2 will be executed.

Then the control is transferred to statement x.

The statement1 is called if-block and the statement2 flowing else is called else-block statement.

Example3.10: if(a>b)

printf(“a is larger than b”);

else

printf(“b is larger than a”);

Here if a is greater than b the message “a is larger than b“is displayed on the screen. Otherwise,” b is larger than a” is displayed.

Example3.11: if(basic>5000)

{ da=basic*65;

hra=basic*15;

cca=200; }

else

{ da=basic*57;

hra=basic*12;

cca=100;

} Here, if the basic is greater than Rs.5000 then da and hra are calculated to be 65% and 15% of basic

respectively and the cca is assigned Rs.200. otherwise, i.e. the basic is less than or equal to 5000 than da

and hra are calculated to be 57% and 12% of basic respectively and cca is assigned Rs.150.

Program3.1Program to illustrate if-else statement.

#include<stdio.h>

#include<conio.h>

int main(void)

{ int year, r4, r100,r400;

printf (“Enter a year\n”);

scanf (“%d”,&year);

if ( test-expression)

statement 1;

else

statement 2;

statement x;

Test-

Expression

Statement1 Statement2

False True

Statements

Page 56: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 56

r4=year % 4;

r100=year % 100; r400=year % 400;

if (( r4 == 0) && (r100!=0) || (r400 == 0))

printf (“%d is a leap year” ,year); else

printf (“%d is not a leap year” ,year);

}

3.4.1.3 The Nested if-else Statement

We know that if execution of a block of statements is conditional, we can use one if statement. What if the conditional execution of the block of statements is itself conditional? Here, we need to enclose one

if statement within another if statement. On the similar lines, we can even enclose an if-else within

another if-else. If one if-else is enclosed within another if-else, the resulting structure is called nested if –else.

The syntax of nested if-else is as follows.

Here, one if-else is enclosed within another if-else. The if structure, which encloses another is called

outer-if. The if structure, which is enclosed within another is called inner-if. Statement-1, statement-2 and statement-3 may be simple or block of statements. First, test-expression1 is checked. If it evaluates to

true, test-expression2 is checked. If test-expression2 also evaluates to true, then else-block of the inner-if,

statement-1 would get executed otherwise, statement-2 would be evaluated. If test-expression1 itself evaluates to false, then else-block of the outer-if, statement-3 would get executed. Thus, this variation

acts as a selector of one out of three blocks of statements.

Example3.12:The following program segment compares a and b.

if(a>=b)

{

if(a>b)

Input-Output:

Enter a year

4000

4000 is a leap year

Enter a year

2011

2011 is not a leap year

if (test-expression 1 )

{

if(test-expression 2) {

statement-1;

} else

{

statement-2;

} }

else

{ statement -3;

}

Test-expr

Statement Test- Expression

Statement Statement

True False

True False

Page 57: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 57

printf(“a is larger than b”);

else printf(“a and b are equal”);

}

else printf(“a is less than b”);

Example3.13: The following segment compares three values a ,b and c and collects the largest of them in

the variable largest.

if( a>=b)

{

if(a>c) largest = a;

else

largest = c; }

else

{

if(b>c) largest = b;

else

largest = c; }

3.4.1.4 The else-if Ladder

The else-if ladder helps select one out of many alternatives blocks of statements for execution depending

on the mutually exclusive conditions. The syntax of the else-if ladder is as follows.

T - Test expression

Here test-expression1, test-expression2… test-expression-n are mutually exclusive. That is only one test-

expression of all will be true. There are n+1 of statements. Initially, test-expression1 is checked. If it is

True False

if(test-expression 1)

Statement-1;

else if (test-expression2)

Statement-2;

else if(test-expression3)

Statement-3;

:

:

else if (test-expression n)

Statement -n;

else

Statement-

n+1;

statement x

T

T

T

statements

statements

statements

statements

True

True

False

False

Page 58: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 58

true, then statement-1 would get executed; all the other blocks of statements would be skipped; then the

statement x gets executed. If test-expression1 is false, test-expression2 is checked. If it is true, then statements-2 would be executed; all the other statements would be skipped. If test-expressions 2 is false,

test-expression3 is checked. If it is true, statements-3 would get executed; all the other statements would

be skipped. This is continued. In general, ith

test-expressions is checked only when the first i-1 test-expressions evaluate to false. If none of the expressions is found to be true, the last statement would get

executed. Thus, else-if ladder act as a selector of one out of n+1 blocks of statement.

Example3.14: printf (“Enter a number\n”);

scanf(“%d”,&n);

if(n<=10)

printf(“ n is less than or equal to 10”); else if (n <=20)

printf(“ n lies between 11 and 20”);

else if (n<=30) printf (“ n lies between 21 and 30”);

else

printf(“ n is greater than30”);

Program3.2 To find whether a number is positive ,negative or 0.

void main()

{ int n;

printf (“Enter a number\n‟);

scanf (“%d”,&n); if(n>0)

printf (“%d is positive”,n);

else if (number >0)

printf (“%d is negative”,n); else

printf (“Zero”);

getch(); }

3.4.2 The Switch Statement

Switch statements provide a non-iterative choice between any numbers of paths based on specified

conditions. They compare an expression to a set of constant values. Selected statements are then executed

depending on which value, if any, matches the expression. Switch statements have the form

Here, expression is an integer or character expression. It evaluates to either integer or a character.Value1, value 2…. Value N is the case values. The expression of the switch statement can take

any of the values. If it matches with value1, statement-1 will get executed and the break statement

following it causes the skipping of the switch structure. If the expression matches with value2, then statement2 will get executed. If the value of expression matches with none of the case values then default

option will get executed.

Input-Output

Enter a number

78

78 is positive number.

Page 59: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 59

Points to Remember:

i) The case values should not be float values or Boolean expression. ii) The case values value1,value2,… value n should be distinct.

iii) The order of their presence is immaterial.

iv) default case is optional. Example 3.15: scanf (“%d”,&n);

switch (n)

{

case 1:printf (“one”); break;

case 2:printf (“two”);

break; default : printf (“Other than one or two \n”);

}

If the value of n is 1, then the string “one” is displayed. If the value of n is 2,then the string “two” is displayed.

Program3.3 Program to accept a digit and display it in words.

void main() {

int digit;

printf (“Enter a number\n”); scanf (“%d”,&digit);

switch (digit)

{ case 0 : Printf( “Zero”); break;

case 1 : Printf( “One”); break;

case 2 : Printf( “Two”); break;

case 3 : Printf( “Three”); break; case 4 : Printf( “Four”); break;

case 5 : Printf( “Five”); break;

case 6 : Printf( “Six”); break; case 7 : Printf( “seven”); break;

case 8 : Printf( “Eight”); break;

Input-Output

Enter a digit

7

seven

switch ( expression)

{

case value1:statement-1;

break;

case value2:statement -2;

break;

.

.

case value n:statement -n;

break;

default :default statement;

break;

}

Test-expr

Statements1 Case1

Statements1 Case2

Statements1 Case3

Statements1 default

Page 60: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 60

case 9 : Printf( “Nine”); break;

default : Printf( “Not a digit ”); break; }

getch();

} 3.5 Looping or Iterative or Repetitive Statements in C

The repetition of execution of a block of statements as long as some condition is true is called Looping. Looping is also called as Iteration.

There are three kinds of iterative statements.

i) while-loop

ii) for-loop

iii) do-while loop

3.5.1 The while-loop

When in a program a single statement or a certain group of statements are to be executed repeatedly

depending upon certain test condition, then while statement is used

The general form ofwhile loop is as follows:

The statement may be simple or compound statement. The keyword “while” is followed by expression enclosed within a pair of parenthesis. The expression can be an arithmetic expression, relational

expression or a logical expression. The expression is then followed by a set of one or more statements,

which are expected to be repeatedly executed.

The execution sequence effected by while looping construct is best illustrated by the following flow chart

segment.

Example3.16: i=1;

sum =0; while (i<=10)

{

sum+=i; i++;

}

while (expression) Statement;

Initialization

Test-

Expression

Statements

False

True

Page 61: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 61

The purpose of the code is to find the sum of the first 10 natural numbers

Example3.17:while ((ch=getchar())!=‟\n‟) {

printf (“%c\n”,toupper(ch));

} The segment code enables us to accept characters of a line, one at a time till the new line character is

entered. Each character entered is converted to upper case and displayed.

After getting familiarized with the syntax and examples of the usage of the while loop, we will now write

some programs which make use of it.

Program3.4 Program to find the sum of the digits of an integer void main()

{

int rem,sum; long int n,temp;

printf (“Enter an integer”);

scanf (“%ld”,&n); temp=n;

sum=0;

while (n>0)

{ rem =n%10;

sum+=rem;

n/=10; }

printf (“sum of the digits of ld=%d\n”,temp,sum);

getch();

}

3.5.2 The for loop The syntax of for loop is as follows:

The statement may be simple or compound statement:

i) expr1 is initialization expression

ii) expr2 is test-expression or conditional expression iii) expr3 is increment/decrement expression.

Statement is executed repeatedly until the value of expr2 is 0. Before the first iteration, expr1 is evaluated

and then expr2 is evaluated. If expr2 is non-zero then only control enter the loop .expr1 is usually used to initialize variables for the loop. After each iteration of the loop, expr3 is evaluated. This is usually used to

increment a loop counter. In fact, the for-loop is absolutely equivalent to the following sequence of

statements:

Input – Output:

Enter an integer 123 Sum of the digits of 123= 6.

for (expr1; expr2; expr3) statement;

expr1; while (expr2) { statement; expr3; }

Page 62: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 62

That's why expr1 and expr3 must contain side effects, else they are useless.

Example3.18: for (i=0; i<100; i++) printf(“%d\t”,i);

All the expressions are optional. If expr2 is left out, it is assumed to be 1. Statement may be a compound statement as well.

The execution sequence effected by for looping construct is best illustrated by the following flow chart

segment.

The execution sequence effected by for loop is as follows:

i) Initialization expression is executed.

ii) Test-expression is evaluated. iii) If the test-expression evaluates to true, the statements in the body of the loop would get executed.

iv) Control goes to the increment/decrement expression, and it is executed.

v) Test-expression is again evaluated. vi) If it evaluates to true, again the statements in the body of the loop would get executed.

vii) Control once again goes back to the increment/decrement expression, which updates the looping

variable.

viii) If the test-expression evaluates to false execution of the body of the loop is terminated. Example3.19: for (j=1;j<=10;j++)

printf(“%d\n”,j);

here the for loop prints the first 10 natural numbers.

Program3.5 Program to find largest of n numbers

#include<stdio.h>

void main()

{ int n,i;

float x,large;

printf ( “Enter the number of values “); scanf(“%d”,&n);

printf(“Enter the first number”);

TRUE

Expression 1

Expression 2

Statement

Expression 3

False

Page 63: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 63

scanf(“%f”,&x);

large=x; printf(“Enter the reaming numbers”);

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

{ scanf(“%f”,&x);

if(x>large)

large=x;

} printf(“Largest of given numbers =%f\n”,large);

getch();

} Program3.6: Program to generate multiplication table of a number

#include<stdio.h>

#include<conio.h> void main()

{

int num,i,product;

printf( “\n Enter a number:”); scanf(“%d”,&num);

printf(“The multiplication table of %d is:”,num);

for( i=1;i<=10; i++) {

product= num*i;

printf( “%d * %d = %d \n”,num,i,product); }

getch();

}

As mentioned earlier a for loop can be written without any one of the expressions or two expressions or all the three.

Example3.20: for(sum=0;n>0;) {

digit=n/10;

sum+=digit; n/=10;

}

Here the segment is to find the sum of digits of a given integer. The loop is written without expression3.

Program3.7 Program to find gcd of two integers using Euclidian algorithm

#include<stdio.h> void main()

{

int a,b,rem,temp1,temp2; printf(“Enter two integers”);

scanf(“%d%d”,&a,&b);

temp1=a; temp2=b;

for(;(r=a%b)>0;) {

a=b;

Input-output:

Enter the number of values 6

Enter the first number 10

Enter the reaming numbers

-3

23

78

-220

5

Largest of given numbers=78

Input –Output: Enter a number: 6

The multiplication of 6 is:

6 * 1 =6

6 * 2=12

.

.

.

6 * 10 = 60

Input-output:

Enter two integers 36 24

gcd(36,24)=12

Page 64: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 64

b=r;

} printf(“gcd(%d,%d)=%d\n”,temp1,temp2,b);

}

In the above program the loop is written without expression1 and expression3.

The for loop can be written without any expressions as like

Would cause that statement block to be executed indefinitely.

3.5.3 do-while Loop

The while and for loops test the termination condition at the top. By contrast, the third loop in C, the

do-while, tests at the end after making each pass through the loop body. Hence the body is always

executed at least once.

Thus while & for loops are entry-controlled loops, whereas do-while is exit controlled loop.

The general form of do-while loop:

the statement block is executed, and then expression is evaluated. If it is true, statement block is evaluated

again, and so on. When the expression becomes false, the loop terminates.

Example3.21: i=1;

sum=0;

do {

sum+=i;

i++; }while ( i<= 10);

for( ; ; )

{

statements block;

}

do {

statements;

}while (expression); false

True

Initialization

Test- Expression

Statements

Page 65: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 65

The statements in the body of the loop get repeatedly executed as long as i< =10 and it finds the sum of

the first 10 natural numbers.

Example3.22: do

{ scanf(“%d”, &n);

printf(“Do you want to continue? Enter Y or N”);

ch = getchar(); } while ( ch ==‟Y‟);

The above segment of code enables us to keep accepting integer value into the variable n as long as we

enter „Y‟ to the variable ch. Once we input „n‟ response to the statement ch = getchar (); the loop is

exited.

Program3.8 Program to print first 5 natural numbers using do-while.

#include<stdio.h> void main()

{

int x=5; int i=0;

//using do while loop statement

do{

i++; printf (“%d\n”,i);

}while(i<x);}

Comparison of the three loops

while for do - - while

n=1;

while (n<=10)

{

- - -

- - -

n++;

}

for(n=1; n<=10; n++)

{

- - -

- - -

}

n=1;

do

{

- - -

- - -

n++;

}

while (n<=10);

3.6 Nested control structures

Like the method of if-else structures, loops also can be nested. In nested loops one loop should be

completely embedded within the other. There can be no overlap. The inner and outer loop structures can

be different.

Output:

1

2

3

4

5

Page 66: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 66

Program 3.9 Program to print all prime numbers between two limits.

#include<stdio.h>

#include<math.h> void main()

{

int ll,ul,k,n,r; printf(“Enter the lower and upper limits\n”);

scanf (“%d%d”,&ll,&ul);

printf (“The prime number between %d and %d are\n”,ll,ul); for( n=ll;n<=ul;++n)

{

k=sqrt (n);

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

r=n%i;

if(r==0) break;

}//end of inner for loop

if (i>k) printf (“%d\n”,n);

}//end of outer loop

}// end of main

Inner for loop is written to check n is prime or not. Outer loop is written to execute this loop repeatedly for n=ll to ul.

3.7 JUMP STATEMENTS

Jump statements transfer control unconditionally from one part of the program to another part of the

program.

i) goto identifier

ii) continue

iii) break

3.7.1 goto statement

So far we have discussed ways of controlling the flow of execution based on certain specified

conditions. Like many other languages, C supports goto statement to branch unconditionally from one

point to another in the program. Although it may not be essential to use goto statement in a highly structured language like C, there may be occasions when the use of goto might be desirable.

Input-output:

Enter the lower and upper

limits10 20

The prime numbers between 10

and 20 are

11

13

17

19

for(i=1;i<n;++i) {

. . . . . . .

. . . . . . .

for(j=1;j<n;j++) {

. . . . .

. . . . . }

. . . .

}

for(i=1;i<n;++i) {

. . . . .

. . . . .

while( expression) {

…….. ………. }

Page 67: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 67

The goto require a label in order to identify the place where the branch is to be made. A label is

any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label statements are

shown below.

Forward jump Backward jump

The label can be anywhere in the program either before or after the goto label; statement. During running of a program when a statement like

goto begin;

is met, the flow of control will jump to the statement immediately following the label begin:. This

happens unconditionally.

Note that a goto breaks the normal sequential execution of the program. If the label: is before the

statement go to label; a loop will be formed and some statements will be executed repeatedly. Such a

jump is known as a backward jump. On the other hand, if the label: is placed after the go to label; some statements will be skipped and the jump is known as forward jump.

A goto is often used at the end of a program to direct the control to go to the input statement, to read further data.

Example3.23:double x, y; read :

scanf(“%d”, &x);

if (x<0)

goto read; y=sqrt(x);

printf(“%f %f”, x,y);

goto read; The above example evaluates the square root of a series of numbers read from the terminal. The

program uses two goto statements, one at the end, after printing the results to transfer the control back to

the input statement and other to skip any further computation when the number is negative.

Due to the unconditional goto statement at the end, the control is always transferred back to the input

statement. In fact, this program puts the computer in a permanent loop known as an infinite loop. The

goto label;

- - - - - -

- - - - - -

- - - - - -

- - - - - -

label :

statement;

label :

statement;

- - - - - -

- - - - - -

- - - - - -

goto label :

Page 68: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 68

computer goes round and round until we take some special steps to terminate the loop-such infinite loops

should be avoided.

3.7.2 Break Statement

Sometimes, it is required to jump out of a loop irrespective of the conditional test value. Break

statement is used inside any loop to allow the control jump to the immediate statement following the

loop. The syntax is as follows:

When nested loops are used, then break jumps the control from the loop where it has been used. Break

statement can be used inside any loop i.e., while, do-while, for and also in switch statement.

Let us consider a program to illustrate break statement.

Program3.10 Program to calculate the first smallest non-trivial divisor of a number.

#include<stdio.h> void main ( )

{

int div, nun, i; printf (“Enter any number”);

scanf (“%d”, &nun);

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

{ if (nun%i) = = 0)

{

printf (“smallest divisor for the number %d is %d”, nun, i); break;

}

} }

In the above program, we divide the input number with the integer starting from 2 onwards, and print the

smallest divisor as soon as remainder comes out to be zero. Since we are only interested in first smallest

divisor and not all divisors of a given number, so we come out of the for loop using break statement without going further for the next iteration of for loop.

3.7.3 Continue statement

Unlike break statement, which is used to jump the control out of the loop, it is sometimes

required to skip some part of the loop and to continue the execution with next loop iteration. Continue statement used inside the loop helps to bypass the section of a loop and passes the control to the

beginning of the loop to continue the execution with the next loop iteration. The syntax is as follows:

Let us see the Program 3.1 given below to know the working of the continue statement.

Program3.11 Program to print first 20 natural numbers skipping the numbers divisible by 5.

#include<stdio.h>

void main ( ) {

int i ;

continue;

break;

Input-output:

Enter any number:

9

Smallest divisor for the

number 9 is 3

Page 69: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 69

for( i=1, i<=20; i++;

{ if(i%5)= = 0)

continue;

printf(“%d”,i); }

}

Here, the printf statement is by passed each time when value stored in i is divisible by 5.

Program3.12 Program to find sum of all non-negative integers in a list of n integers entered through key

board

void main() {

int i,sum=0,n,x;

printf(“Enter number of values”); scanf(“%d”,&n);

printf(“Enter the values”);

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

{ scanf (“%d”,&x) ;

if( n <0)

continue; sum+ = n;

}

printf(“sm=%d\n”,sum); }

SUMMARY

The program statements in C fall into three general types: assignment, input/output, and control. C has

two types of control structures: selection (decision) and a repetition (loops). The decision control

constructs are of two types: conditional and unconditional. The conditional control constructs are if, if-else, if-else-if and switch. The unconditional control constructs are break, continue and goto. The loop

control constructs are for, while and do-while.

One-way decisions are handled with an if statement that either does some particular thing or does

nothing at all. The decision is based on a test expression that either valuates to true or false. 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 is based on a test expression. Multi-way decision

statements use if-else-if ladder or nested ifs, or switch statements. They are all used to evaluate a test

expression that can have several possible values selecting different actions.

In a program by using loop control statements while, for, do-while you can execute set of statements

repeatedly, while and for are called entry-controlled loop which means that testing a condition is

checked before starting a loop. Do-while is called as exit-controlled loop in which the testing a condition is checked after executing the loop.

Output:

1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19

Input-output:

Enter the number of values 5 Enter the values 2 -12 5 0 -4 sum= 7

Page 70: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 70

Using break statement, we can leave a loop even if the test condition for its end is not fulfilled. It can

be used to end an infinite loop, or to force it to end before its natural end. The continue statement

causes the program to skip the rest of the loop in the present iteration as if the end of the statement block would have reached, causing it to jump to the next jump iteration.

Using goto statement, we can make an absolute jumpto another part of the program. You should use

this feature carefully since its execution ignores any type of nesting limitation.

EXERCISES

Multiple Choice Questions

3.1 What would be the output of each of the following code segments?

i) void main ( )

{ int a=1, b=1;

if(a = = 1)

if(b = = 0) printf(“HI”);

else

printf(“Bye”); }

ii) void main ( )

{

int a,b=0; if(a=b=1)

printf (“hello”);

else printf (“world”);

}

iii) void main() {

int var1,var2=2,num=100,a;

if(var1=var2%2)

num=2; a=2;

printf(“%d %d”,num,var1);

} 3.2 What is the value of y in the following code?

void main()

{

int x=7,y=0; if(x=6)

y=7;

else y=1;

}

a)7 b)0 c)1 d)6 3.3 What is the value of z after the following statements executed?

void main()

{int x=2,y=2,z=1;

if(x=y%2)

Page 71: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 71

z+=10;

else z+=20;

}

a)21 b)11 c)1 d)the expression x=y%2 is not allowed

3.4 Write the following expression using if statement.

x = ( y > 3 ) ? ( x < y ) ? y : x + 10 : ( y < 0 ) ? -y : y + 10;

3.5 What is the output of the following code? main()

{

int a=500,b,c; if(a>400)

{

b=300; c=200;

}

c=100;

printf(“\n b=%d , c=%d \n”,b,c); }

3.6 Which of the following is true?

int a=5,b=7; if(a<b);

a++;

else b++;

printf(“a=%d,b=%d \n”,a,b);

a)a=6,b=8 b)a=6,b=7 c)a=5,b=8 d)syntax error.

3.7 Which of the following is the correct output for the program given bellow?

#include<stdio.h>

int main() {

float a=0.7;

if(0.7>a)

printf(“hi \n”); else

printf(“hello \n”);

return 0; }

a)Hi b) hello c)hi hello d)None of the above

3.8 Which of the following statements are correct about the problem given below? #include<stdio.h>

main()

{

float a = 2.8, b = 2.87 ; if (a = b)

printf(“ a and b are equal \n”);

else printf(“a nd b are not equal \n”);

}

Page 72: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 72

a)The statement if (a = b) results in a compilation error.

b)floats cannot be compared using if c)conditional operator should be used to compare floats

d)switch_case should be used to compare floats.

3.9 What is the output when the following code is executed? #include<stdio.h>

void main()

{

int a=0,b=1; if(a<b || ++b)

a=5;

else b=6;

printf(“a=%d ,b=%d \n” a,b);

} 3.10 What is the output when the following code is executed?

#include<stdio.h>

void main( )

{ int x=1,y=3,z=0;

switch(x)

{ case 0: x=2;

y=3;

break; case 1: x=4;

break;

default : ++x;

} printf (“x=%d,y=%d, z=%d”,x,y,z);

}

3.11 Originally x=4,y=3 and z=0 . What are values of x,y,z after executing the following code?

switch(x)

{

case 0 : x=2;y=3; case 1 : z=4; break;

default : ++x;

} a)x=0,y=3,z=4 b)x=2,y=3,z=4 c)x=1,y=3,z=4 d)x=5,y=3,z=0

3.12 When is default statement executed in switch case construct?

a) When ever there is exactly one match. b)When ever break statement is omitted in all case statements

c)When ever there is no match with case labels.

d)options b and c.

3.13 Consider the following program segment int n sum=1;

switch(n)

{ case 2: sum=sum+2;

case 3: sum*=2;

Page 73: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 73

break;

default : sum=0; }

If n=2 ,What is the value of sum

a)0 b)6 c)3 d)None of these 3.14 What will be printed by the following code?

#include< stdio.h>

main()

{ int x = 5;

switch(x);

{ case 5 : printf (“%d\t”, x * x) ;

case 6 : printf(“%d\t”, x + 1 * x+1);

default : break; }

}

3.15 Omitting the break statement from a particular case in switch case construct

a) leads a syntax error b)causes execution of the program to terminate after the case

c) causes execution to continue all subsequent cases.

d) causes execution to branch to the statement after the switch statement 3.16 How many times of the while loop in the following program will be excuted.

void main()

{ int j=1;

while(j<=255);

{

printf(“%d\n”,j); j++;

}

}

3.17 What is the output when the following code is executed?

void main( )

{ int i=3;

while(i)

{ int x=100;

printf(“\n%d %d”, i, x);

x=x+1; i=i+1;

}

}

3.18 What is the output when the following code is executed? void main()

{

char j=1; while(j<=255)

{

Page 74: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 74

printf(“%d\n”,j);

j=j+1; }

}

3.19 What is the output when the following program is executed? #include<stdio.h>

main()

{

int i; while(i<=10);

{

printf(“%d”,i); ++i;

}

} a) First 10 natural numbers can be displayed b) 11

c) Natural numbers starting from 1 are displayed indefinitely d) no output.

3.20 What is the output when the following program is executed?

#include<stdio.h> main()

{

int a=5; while(a-- >0)

printf(“%d\t”,a);

} 3.21 What is the output when the following program is executed?

#include<stdio.h>

main()

{ int p=5;

while(p<8)

{ printf(“%d”,p);

p=9;

}

} a)5 6 7 b)5 c)5 9 9 9 9 … d) no output

3.22 What is the output when the following program is executed?

#include<stdio.h> main()

{

int x=1; while(1)

{

printf(“%d”,x);

++x; }

}

3.23 What will be the output when the following code is executed? #include<stdio.h>

main()

Page 75: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 75

{

int a = 6; while (a)

{

printf(“%d\t”, a); a == 2;

}

}

3.24 What will be the output when the following code is executed? void main()

{

int i; for(i=0; j<=10; i++, printf(“%d \t”, i));

}

3.25 What will be the output when the following code is executed? void main( )

{

int i;

for(i=0; i<3; i++) printf(“%d\t”, i);

}

3.26 What will be the output when the following code is executed? void main()

{

int a; for(a=1;a<=32767;a++)

printf(“%d”,a);

}

3.27 What will be the output when the following code is executed? void main()

{

int i=0; for(;i++;)

printf(“%d”,i);

}

3.28 Which of the following statement is used to exit from a switch case statement?

a) exit b)continue c)goto d)break

3.29 How many times KLU is printed? for(i=0;i>5;++i)

printf(“KLU\n”);

a)6 b)5 c)0 d)Indefinite no of times. 3.30 Write the syntax of for statement in C?

3.31 Which of the following is a loop construct?

a)if-else b)switch-case c)goto d)while

3.32 What is the output of the following program? main()

{

unsigned int i; for(i=10;i>=0;--i)

printf(“%d”,i);

Page 76: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 76

}

a) prints numbers from 10 to 0 b) prints numbers from 10 to 1 c) prints numbers from 10 to -1 d)An indefinite loop is formed

3.33 How many times x is printed?

for(i=0,j=10;i<j;++i,--j) printf(“x”);;

a)10 b)5 c)4 d)none

3.34 what is the value of a after the following code is executed?

void main() {

int b,a=0;

for (b=0;b<10;b++) {

switch(b)

{ case 0:

case 1:

case 2:

case 5: ++a;

case 3: break;

case 4: break; default: break;

}

} 3.35 What is the output when the following program is executed?

#include<stdio.h>

main()

{ int i;

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

printf(“%d”,i); }

a) First 10 natural numbers can be displayed b) 11

c) Natural numbers starting from 1 are displayed indefinitely d) no output.

3.36 What is the output when the following program is executed? #include<stdio.h>

main()

{ int a=5;

for(a=5;a-- >0; )

printf(“%d\t”,a); }

3.37 What is the output when the following program is executed?

#include<stdio.h>

main() {

int a;

for(a=10;! i;-- i) printf(“%d”,i);

}

Page 77: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 77

a) First 10 natural numbers are printed in reverse order b)11

c) 10 d) no output. What is the output when the following program is executed?

#include<stdio.h>

main() {

int b;

for(b=3;b<10;b=7)

printf(“%d”,b); }

a)3 4 5 6 7 8 9 b)3 7 8 c) 3 7 7 7 7 … d)3

3.38 What is the output when the following program is executed? #include<stdio.h>

main()

{ int i;

for(i=10;++i;i-=5)

printf(“%d”,i);

} 3.39 What would be the output when the following program is executed?

#include<stdio.h>

main() {

int i=5;

for(--i;--i;--i) printf(“%d”,i);

}

3.40 What would be the output when the following program is executed?

#include<stdio.h> main()

{

int i; for(i=0;i--;i--)

printf(“%d”,i);

}

3.41 What would be the output when the following program is executed? #include<stdio.h>

main()

{ int i;

for( ;x>0;d=x%10,sum+=d,d/=10);

printf(“%d”,sum); }

3.42 What is the output when the following code is executed?

#include<stdio.h>

main() {

int p;

for(p=-10 ; !p ; ++p) printf(“\n%d”,--p);

}

Page 78: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 78

3.43 Identify the error in the following program?

#include<stdio.h> main()

{

int x=10,y=0; do{

y+=x;

--x;

}while(x) printf(“\n%d ” , y);

}

3.44 What is the output when the following program is executed? #include<stdio.h>

main()

{ int a=10;

do

{

printf(“%d”,a); --a;

}while(a<=1);

}

3.45 Which of the following is exit control loop?

a)for b)switch case c)while d)do-while 3.46 What is the output when the following program is executed?

void main( )

{

int i = 1; do

{

printf(“%d”, i); }while (i=i-1);

}

3.47 What is the output when the following program is executed?

void main() {

for(x=20;x>=1;x--)

{ for(y=x;y>=1;y--)

printf(“ “);

printf(“%d\n”,x); }

}

3.48 What is the output when the following program is executed?

#include<stdio.h> main()

{

int i,j; for(i=1;i<=3;++i)

{

Page 79: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 79

for(j=1;j<=3;++j)

printf(“%3d ”,i+j); printf(“\n”);

}

} 3.49 What is the output when the following code is executed?

{

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

{ if(i<=4)

break;

printf(“%d”,i); }

}

3.50 What is the output when the following program is executed? void main ( )

{

int num, sum;

for(num=2, sum=0; ;) {

sum=sum+num;

if (num>10) break ;

num = num+1;

} printf(“%d”, sum);

}

3.51 What is the output when the following program is executed?

void main( ) {

int i=5;

while (i) {

i=i-1;

if(i = = 3)

continue; printf(“\n hello”);

}

} 3.52 What is the output when the following program is executed?

#include<stdio.h>

main() {

int a=1;

while(a<=5)

{ if(a==2)

continue;

printf(“%d\t”,a); ++a;

}

Page 80: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 80

}

3.53 How many times KLU is displayed when the following code is executed? #include<stdio.h>

main()

{ int x;

for(x=-1;x<=5;++x)

{

if(x<3) continue;

else

break; printf(“KLU \n”);

}

3.54 What is the output when the following program is executed? void main ()

{

int i,j;

for(i=1;i<=5;i++) {

if(i==3)

continue; for(j=1;j<=i;j++)

{

if(j==3) break;

printf(“%d”,i*j);

printf(“\n”);

} }

}

3.55 What is the output when the following program is executed? #include<stdio.h>

main ()

{

int x=1; for( ; ; )

{

if(x==3) break;

printf(“%d\t”,x);

break; }

}

3.56 What is the output when the following program is executed?

#include<stdio.h> main()

{

int i; for(i=1;i<=5;++i)

{

Page 81: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 81

if(i==3)

continue; printf(“%d\t”,i);

}

} 3.57 What is the output when the following program is executed?

#include<stdio.h>

main()

{ int i;

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

{ if(i==3)

break;

printf(“%d \n”,i); }

}

3.58 What is the output when the following program is executed?

#include<stdio.h> main()

{

int i=1; for( ; ; )

printf(“\n %d”,++i);

if( i>5) break;

}

3.59 Difference between while and do-while?

3.60 Distinguish between break and continue statements?

Comprehensive Questions:

3.1 Compare, in terms of their functions, the following pairs of statements:

while and do---while

while and for break and goto

break and continue

continue and goto

3.2 How would you decide the use of one of three loops in C for a given problem? 3.3 What is a null statement? Explain a typical use of it.

3.4 4.In a mechanical system the applied force p is expressed as a function of t in

p(t) = 20 if x <= 3 4(++2) , if t > 3

3.5 A set of two linear equations with two unknowns x1 and x2 is given below

ax1+bx2=m and cx1+dx2=n The set has a unique solution

cbad

bnmd

cbad

mcna

provided the denominator ad-cb is not equal to zero. Write a program that will read the values of

x1 and x2. An appropriate message should be printed

if ad-cb=0

3.6 A function is defined as follows:

x1= x2=

Page 82: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 82

f(x) = { 10x2 -5x+4, if x<=0

{ 10x2 +5x+4, if x>0

Write a program to find the value of the function for given value of x. 3.7 Write a C program to print the roots of a quadratic equation after reading the value of

its coefficients a, b and c.

3.8 Write a program to convert the temperature from Fahrenheit to Centigrade and vice versa. 3.9 Write a program to accept the sides of a triangle and check whether a triangle is formed

or not. If formed determine the nature of the triangle(scalene, isosceles, equilateral).

3.10 write a menu driven program to compute electricity bill taking different categories

of users for different slabs. 3.11 In Mechanical System the applied force p is expressed as function of t in

{ 20 , if t<=3

p(t)= {4(t+2), if t>3

Calculate and print the force dependent on the time provided by the user

at the prompt.

3.12 A company sells five different products with prices shown in the following table.

Product Number Retail Price Unit (in Rs)

1 15.50

2 19.25 3 14.75

4 25.00

5 12.50 Write a program using switch-case construct that reads the product number and number

of units sold and display the amount to be paid.

3.13 The price for one copy of a software package is Rs 5000/-. The discount for the software depends on the volume as shown in the table below

Number of copies Discount

num < 5 No discount

num<10 10%

num < 50 15%

num >=50 20%

Write a program to calculate the cost with the number of copies of the softwarepackage provided

by the user at the prompt. 3.14 A company sells five different products with prices shown in the following table:

Product Number Retail Price Per unit (in Rs.)

1 15.50

2 19.25 3 14.75

4 25.00

5 12.50

Page 83: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 83

3.15 Write a program using switch-case construct that reads the product number and number of units

sold and display the amount to be paid. 3.16 Write a program that determines a student‟s grade. It reads three tests scores (between 0 to 100)

and calls a function that calculate and returns a student‟s grade based on the following rules:

a)If the average score is 90% or more, the grade is A. b)If the average scores are 70% or more and less than 90%, it checks the third score. If the third

score is more than 90%, the grade is A; otherwise, the grade is B.

c)If the average score is 50% or more and less than 70%, it checks the average of the second and

third scores. If the average of two is greater than 70%, the grade is C; otherwise, it is D. d)If the average score is less than 50%, then the grade F.

3.17 Write a program that accepts 0, 1 or 2. If 0 is entered by the user, accept the necessary parameters

(radius, height etc.,) to calculate the volume of a cylinder. Inputs 1 and 2 correspond to cylinder and cone respectively. The process must go on until the user enters „q‟ to terminate the program.

3.18 Given an integer between 0 and 6, write a program that prints the corresponding day of the week.

Assume that the first day of the week (O) is Sunday. 3.19 Write for loop to find the sum of squares of first N-natural numbers.

3.20 Write a program to find a factorial of a given integer.

3.21 Write a program to display the image of given number.

3.22 Write a program the prompts the user enter an integer ,n and then a floating point number as the numbers are read the program will calculate the average of the positive numbers.

3.23 Euler‟s number,e, is used as the base of natural logarithms. It can be approximated using the

following formula; e=1+1/1! +1/2! +1/3! +1/4! +1/5! +1/6! + . . . +1/ (n-1)! +1/n!

3.24 Write a program that approximates e using a loop that terminates when the difference between two

successive vales of e differ by less than 0.0000001. 3.25 Write a program to evaluate the following investment equation v=P (1+r)

n and print the tables

which would give the value of v for various combinations of the following values of p,r and n.

P: 1000, 2000, 3000. . . , 10000

r: 0.10, 0.11,0.12,. . . ,0.20 n: 1, 2,3,. . . 10

(Hint, P is the principal amount and V is the value of money at the end of n years. The equation

can be recursively written as

V=P(1+r)

P=V

That is, the value of money at the end of first year becomes the principal amount for the next year

and soon.) 3.26 Write a program to print the following triangle

- - - upto nth line

*

* *

* * *

* * * *

Page 84: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 84

- - - upto n

th line

- - - - upto nth line

3.27 The numbers in the sequence

1 2 3 5 8 13 21. . .

are called Fibonacci numbers. Write a program using a do-while loop to calculate and print the first m

numbers.(Hint: After the first two numbers in the series, each numbers is the sum of the two Preceding

numbers.)

3.28 Write a program that calculates and print the average of several integers. Assume that

the last value read with scanf () is sentinel number 9999. 3.29 Caluclate the values of the function

f(x) = 2xsinx +tan-1

(x)+ex

for x in the range of -1<=x<=5 with a step size of 0.25

3.30 Write a program that reads an integer and determines if it is a prime number. If it is not a prime

number, print out the smallest divisor. Otherwise, print out the prime number.

3.31 Write a program to read an integer number between 0 and 25. Print out the character corresponding to the input number of the ASCII value. Give an error message if the

input number is outside the specified range. The program terminates when the input

number is -1. 3.32 The cosine function can be expanded as a Taylor series as follows:

cosx = 1- x2/2! + x

4/4! – x6/6! + ------ . Write a program to find the value of cosx to a given

precision.

3.33 The sin function can be expanded as a Taylor series as follows: sinx = x- x

3/3! + x

5/5! – x7/7! + … . Write a program to find the value of sinx to a given

precision.

3.34 The Taylor series expansion of ex is ex=1+x+x

2/2!+x

3/3!+… Write a program to find the value of ex to a given precision

3.35 Calculate the values of the function

f(x,y)= x2-y

2+5xy for x in the range of -1 ≤ x ≤ 5 with a step of size 1 and for y in the range of

2 ≤ y ≤ 4 with a step of size 0.5.

3.36 Write a program to check given number is prime or not.

3.37 Write a program to display the image of a given number.

3.38 Write a program to print the values of the function

1

1 2

1 2 3

1 2 3 4

*

* *

* * *

* *

*

Page 85: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 85

f(x) = 3ex+ 4 sinx + 0.6 for x=0,0.1,0.2,………….1.0

3.39 Write a program to find maximum among a given list of numbers entered through keyboard Stop reading the data whenever zero is entered.

3.40 Write a program to find the average of a given list of numbers entered through keyboard .Stop

reading the data whenever -1 is entered. 3.41 Write a program to find the sum of the first n terms of the series

Sin x = x – x3/3! + x

5/5! - x

7/7! + ---------

3.42 What are the various looping statements? Explain the syntax giving one example to each.

3.43 Write a program to read a particular number and to check whether it is a perfect number or not. 3.44 Write a program to print first n Fibonacci elements.

3.45 Write a program to check if a given number is an element of Fibonacci sequence.

3.46 Write a program to check if a given number is Armstrong or not. 3.47 Eulers formula e is used as the base of natural logarithm . It can be approximated using:

e = 1 + 1/1! + 1 / 2! + 1/ 3! + ………………………. + 1/n! + …

Write a program that approximates e using a loop that will be terminated when the new term of

the series is less than 0.000001. 3.48 To evaluate ∫ab f(x) dx,by numerical integration , divide the interval [a, b]into n sub-intervals,

taking the equidistant points of subdivision as

x 0, x1, …, xn . The trepizoidal rule is

a∫bf(x) dx = (h/2) [y0 + 2(y1 + y2 + ….. + yn-1) + yn]

where h = (b – a)/n and yi = f(xi) , I = 0, 1, 2, .. , n

Write a program to evaluate 0∫1 exp.(x2) dx with n = 10 by trapezoidal rule.

3.49 Write a program to find the sum of the series sum = 1+ x + x

2 + …………………. x

n.

3.50 Write a program to find the sum of series

Sum = 1+ x + x2/2 + x

3/3 + …………………………. x

n-1/(n-1)

3.51 Write a program to find the sum of digits of a number. 3.52 Write a program to enter integer number and find the largest and smallest digit of the number.

3.53 For a certain electrical circuit with an inductance L and resistance R, the damped natural

frequency is given by

Frequency= 24

21

C

R

LC It is desired to study the variation of this frequency with C(capacitance). Write a program to

calculate the frequency for different values of C starting from 0.01 to 0.1 in steps of 0.01

3.54 Write a program to print the numbers that don‟t appear in the Fibonacci series. The numbers of such terms to be printed should be given by the user

3.55 Write a do-while loop that will display the following sequence of numbers

7,9,11,13 … 67.

3.56 Program to print all multiplication tables between two limits. 3.57 Write a program to display all prime numbers between two given limits.

3.58 Write a program to add all prime numbers between two given limits.

3.59 Write a program to display first n prime numbers. 3.60 Write a program to print all elements of Fibonacci sequence between two limits.

3.61 Write a program to print prime numbers between two limits.

3.62 Write a program to print the first n prime numbers.

3.63 Write a program to print all two digit perfect numbers.

Page 86: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Control Statements 86

3.64 Write a program to print all values of the function f(x,y)= ex+y-2(x+y) for all combinations of

x= -5,-3,-1,1,3,5 and y = 0, 0.5, 1.0,1.5,……………. 10.0. 3.65 Write a program to display each digit of a number as many times as the digit.

3.66 Write a program to check a given number is strong or not.

3.67 Given a set of integer numbers containing positive negative and zero values. Write a program to find average of only positive values using continue statement.

3.68 Create an infinite for loop check each value of the for loop .If the value is odd display it otherwise

continue with iterations. Print even numbers from 1 to 100 use break statement to terminate the program.

Page 87: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 87

Chapter 4

ARRAYS

LEARNING OBJECTIVES

After going through this chapter the reader will be able to

declare and use one-dimensional and two-dimensional arrays

initialize arrays

use subscripts to access individual array elements

write programs involving one-dimensional and two-dimensional arrays

write programs for matrix operations

4.1 INTRODUCTION

Consider the following program

main( )

{ int x ;

x = 10;

x=15;

printf (“x=%d \n “,x); }

This program will print the value of x as 15. Because, when a value 15 is assigned to x, the earlier value

of x, i.e., 10 is lost. Thus ordinary variables are capable of holding only one value at a time (as in the above example). However, there are situations in which we would want to store more than one value at a

time in a single variable.

For example, we wish to arrange the total marks obtained by 100 students in ascending order. To do this,

it is needed to store all 100 values in the memory simultaneously. In this situation an array is used.

What is an array?

An array is a collective name given to a group of related quantities belonging to same data type. These

related quantities can be total marks of 100 students or salaries of 500 employees or heights of 200 students. For example, we can use an array name tmarks to represent a set of total marks of a group of

100 students in a class. We can refer to the individual marks by writing a number called index or

subscript in square brackets after the array name.

Example4.1:

To store the total marks of 100 students an array will be declared as follows,

float tmarks[100];

tmarks [0], tmarks [1], tmarks [2] etc. represents the total marks of 1st, 2

nd, 3

rd etc. students. In general,

tmarks[i], i can take values 0,1,2,3, represent the total marks of (i+1)th student. Here tmarks is the array

name and i is its subscript.

Thus the array tmarks is the collection of 100 memory locations referred as below:

tmarks[0] tmarks[1] tmarks[2] . . . tmarks[99]

3000 3002 3004 3198

Page 88: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 88

In the above figure, it is assumed that integer value occupies 2 bytes. Thus 200 bytes of space will be

allocated to the array tmarks.

We can use arrays to represent not only single lists of values but also tables of data(like matrix, marks of

100 students in 6 subjects, sales of a departmental store in a week) in two, three or more dimensions.

This chapter explain the use of arrays, types of arrays, declaration and initialization of one dimensional

and two dimensional arrays with the help of examples.

4.2 ARRAY DECLARATION

Before discussing an array, first of all let us look at the characteristic features of an array

i) Array is a data structure storing a group of elements, all of which are of the same

data type. ii) All the elements of the array share the same name, and they are distinguished from one another

with the help of an index called subscript

iii) Random access to every element using a numeric index (subscript) is possible iv) A simple data structure which is extremely useful

The declaration of an array is just like any variable declaration with additional size part, indicating the number of elements of the array. Like other variables, arrays must be declared at the beginning of a

function.

The declaration specifies the data type of the array, the name and its size or dimension.

4.2.1 Declaration of one dimensional arrays

data-type refers to the type of elements to store and constant-size is the maximum number of elements.

The following are some examples of array declarations

Example4.2: int x[100]; // x is an array to store maximum 100 integers

float height[50]; //height is an array to store heights of maximum 100 persons

long int city[50]; //city is an array to store population of maximum 50 cities

int fib[15]; //fib is an array to store maximum 15 elements of the fibonacci

sequence

It is convenient to define array size in terms of a symbolic constant rather than a fixed integer quantity.

This makes it easier to modify a program that utilizes an array, since all references to the maximum array size (eg. within for loops as well as in array definitions) can be altered simply by changing the value of

the symbolic constant.

Example4.3: It is convenient to declare

# define SIZE 50;

int a[SIZE];

rather than int a[50];

data-type array-name[constant-size]

[constant-size];

Page 89: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 89

4.3 SUBSCRIPT

To refer the elements of an array subscript is used. In an array a with 50 elements, the individual

elements are referred by a[0], a[1], a[2], . . , a[48], a[49] as shown below:

a[0] a[1] a[2] a[48] a[49]

Here 0,1,2,3…………………….49 are called subscripts.

The sub scripts of an array can be integer constants, integer variables or expressions that yield integers.

Example4.4:

If we want to represent a set of 5 numbers, say {10, 4, 18, 20, 35} by an array variable a, then we declare

the array a as follows:

int a[5];and the computer reserve 5 storage locations as follows:

a[0] a[1] a[2] a[3] a[4]

The values can be assigned to the array elements as follows:

a[0] = 10 ; a[1] = 4 ; a[2] = 18 ; a[3] = 20 ; a[4] = 35 ;

This could cause the array a to store the values as shown below:

10 4 18 20 35

a[0] a[1] a[2] a[3] a[4]

4.4 STORAGE OF ONE-DIMENSIONAL ARRAYS IN MEMORY

When an array is declared, memory is allocated automatically with respect to its type and size.

Array elements are stored in contagious memory locations. For example, a sample layout for the one-dimensional integer array a of size 6 elements declared as

int a ;is shown below.

Address Memory Element number

a[0],a[1],a[2],………… represent the first, second, third etc. elements of the list &a[0],&a[1],&a[2] etc

represent the addresses of the first, second, third etc positions of the array

2000

2002

2004 2006

2008

2010

1

2

3 4

5

6

Page 90: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 90

4.5 INITIALIZATION OF ARRAY

After an array is declared, its elements must be initialized. Otherwise, they will contain

“garbage”. An array can be initialized at either of the following stages.

i) At compile time

ii) At run time

4.5.1 Compile time initialization

Arrays can be initialized at the time of declaration. The initial values must appear in the order in which they will be assigned to the individual array elements, enclosed within the braces and separated by

commas.

Syntax of array initialization is as follows:

val1 is the value for the first array element, val2 is the value for the second array element, and valn is the value for the n

th array element.

Example4.5: int = {10, 5, 8, 6, 2};

initializes integer array a such that

= 10,

= 5,

a[2]=8,

= 6,

= 2.

Example4.6: char color[5]={„G‟,‟R‟,‟O‟,‟B‟,‟\0‟};

initializes character array color such that color[0]=‟G‟,

color[1]=‟R‟,

color[2]=‟O‟, color[3]=‟B‟

color[4]=‟\0‟

If the number of initializers in the list is less than the number of elements then only that array

elements will be initialized. The remaining elements will be set to zero automatically.

Example4.7: int = {10, 5, 8};

will initialize the array a such that

= 10,

= 5,

= 8,

= 0,

= 0.

If the number of initializers is more than the array size, then a syntax error would result.

data type array-name[size]={val1, val2, . . ., valn};

Page 91: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 91

Example4.8: int = {10, 5, 8, 12, 7, 14, 20};

would result in syntax error.

An array can be initialized without specifying the array size. In this case, the number of

initializers is used to determine the size of the array.

Example4.9: int = {10, 5, 8, 12, 7, 14, 20};

would initialize a seven element array of int type.

4.5.2 Run time initialization

An array can be explicitly initialized at run time.

Example4.10: Consider the following segment of a C Program.

for (i=0; i < 20; ++i) { if (i < 5)

= 0.0;

else

= 1.0; }

The first 5 elements of the array a are initialized to zero while the remaining 15 elements are initialized

to 1 at run time.

We can also use scanf function to initialize an array.

Example4.11: The statements

int ;

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

scanf (“%d”, & ;

will initialize the array elements with the values entered through the keyboard.

Program 4.1 Program to store n values in an array and display them in reverse order #define SIZE 50

void main( )

{ int a[SIZE],i,n;

printf(“Enter the number of values: “);

scanf(“%d”,&n);

printf(“Enter the values: “); for(i=0; i<n; ++i)

scanf(“%d”,&a[i]);

printf(“Given values in reverse order is: \n”); for(i=n-1; i>=0; --i)

printf(“%d\n”,a[i]);

}

Page 92: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 92

Program 4.2 Program to find the mean of n values.

#include<stdio.h> #include<conio.h>

#define SIZE 50

main ( ) {

float a[SIZE], sum, mean;

int n,i;

clrscr ( ); printf(“Enter the number of values : ”);

scanf(“%d”, &n);

printf(“Enter the values : ”); for (i=0; i < n; ++i)

scanf(“%f”, & );

/* find sum */ sum = 0 ;

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

sum = sum + ;

mean= sum / (float)n ; printf (“Mean of the n values : = % f \n”, mean);

}

Program 4.3 Program to arrange a list of numbers in increasing order.

To arrange a list of numbers in order is called sorting. Many sorting methods are available in literature.

The present program uses a simple sorting method known as Bubble sort.

If the list contains n elements, this method require (n-1) passes. In the first pass, adjacent pairs of

elements , . . . are compared and the larger element is

pushed down. After the first pass largest element is pushed down to the last location. In the second pass,

the pairs of elements , . . . are compared and the larger

element is pushed down . At the end of second pass, second largest element is pushed down to the last

but one location. Like this at the end of the (n-1)th pass, entire array will be re-arranged in increasing

order.

So, a for loop for the operations in pth pass is as follows:

for (j=0 ; j< n – p ; + + j)

{

if

{

temp = ;

= temp;

}

}

Page 93: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 93

This loop is to be repeated (n-1) times for the values of pass number p=1,2,3,…..,(n-1).

Thus the program which implements the bubble sort is as follows:

#include<stdio.h>

#include<conio.h> #define SIZE 50

void main( )

{ int a[SIZE],n,i,j,temp,p;

clrscr( );

printf("Enter the number of values in the list: ");

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

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

scanf("%d",&a[i]); /*sorting process*/

for(p=1; p<n; ++p)

{

for(j=0; j<n-p; ++j) {

if(a[j]>a[j+1])

{ temp=a[j];

a[j]=a[j+1];

a[j+1]=temp; }

}

}

/*output the sorted list*/ printf("The sorted list is: \n");

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

printf("%d\n",a[i]); }

Program 4.4 Program to search for a specified number in a given list of numbers.

Given a list of n numbers, the program will search for a given number say, key in the list. Compare key

with ,a[n-1], whenever the key match with one of the values of the list stop the

comparisons and display a message that the number is found in the list. If the key does not match with

any element of the list display the message that the number is not found in the list.

# include<stdio.h> # include<conio.h>

# define SIZE 50

void main ( ) {

int i, key, n, flag = 0;

int

clrscr( ); printf(“Enter the number of values in the list: ”);

scanf(“%d”, & n);

Page 94: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 94

printf(“Enter the values : ”);

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

scanf(“%d”, & );

printf(“Enter the number to be searched:”);

scanf(“%d”, &key); for(i=0; i<n; ++i)

{

if(key = = )

{ flag = 1;

break ;

} }

if (flag = = 1)

printf(“%d is in the list at the position %d \n”, key, i+1); else

printf (“%d is not in the list \n”, key); }

Program 4.5 Program to merge two sorted lists

The two input sorted lists are stored in the arrays a and b respectively. Merged list is stored in

array c. Corresponding elements of arrays a and b are compared and the smaller element is copied into

the array c. The process is repeated until one of the lists is exhausted ,If the elements of array are exhausted then the remaining elements of array a are copied into the array c, This is accomplished by the

loop.

while (i<m) {

c[k]=a[i];

++i ; ++k ;

} If the elements of array a are exhausted then the remaining elements of array b are copied into c. This is

accomplished by the loop

while(j<n)

{

c[k]=b[j]; ++j;++k;

}

This procedure is implemented in the following program:

#include<stdio.h>

#include<conio.h>

void main( ) {

int a[10],b[10],c[20],i,j,k,m,n;

printf("Enter the number of elements of the first list: "); scanf("%d",&m);

printf("Enter the elements of the first list: ");

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

scanf("%d",&a[i]); printf("Enter the number of elements of the second list: ");

scanf("%d",&n);

Page 95: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 95

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

scanf("%d",&b[i]); i=j=k=0;

while(i<m&&j<n)

{ if(a[i]<b[j])

{

c[k]=a[i];

++i; }

else

{ c[k]=b[j];

++j;

} ++k;

}

while(i<m)

{ c[k]=a[i];

++i;

++k; }

while(j<n)

{ c[k]=b[j];

++j;

++k;

} printf("the merged list is: \n”);

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

printf("%d",c[i]); }/*end of main*/

Program 4.6 Program to find the binary representation of decimal integer

Divide given decimal integer by 2, remainder is the least significant digit of the binary representation .

Take the quotient and divide it by 2,remainder is the next binary digit . Take the new quotient and divide

it by 2. Repeat this process till the quotient is zero . The remainders obtained in reverse order are the

digits of the binary representation . Since the remainders are to be displayed in reverse order, store them in a one-dimensional array and display them in reverse order. This procedure is implemented in the

following program

#include<stdio.h>

#include<conio.h>

void main( ) {

short int bdigit[[16],nd,num,digit,i=0,j;

clrscr();

printf(“Enter the decimal number :”); scanf(“%d”,&num);

while(n>0)

Page 96: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 96

{

digit=n%2; bdigit[i]=digit;

++i;

n=n/2; }

nd=i; // nd is the number of digits in binary representation

for(j=0;j<nd;++j)

printf(“%d”,bdigit[j]); getch();

}

Program 4.7 Program to insert an element at a given position in a list.

Let the given element be represented by key and the position be represented by „pos‟. Move down all the

elements from the given position to the end by one position. Then assign the given elements to a[pos-1]. If the list contains 7 elements and the position to be inserted is 3,then move a[6] to a[7],a[5] to a[6],

…..a[2] to a[3]. For this , the following code can be used

for(i=7;i>=3;--i)

a[i]=a[i-1];

Since an element will be inserted, the new list contains one extra element. Therefore increment the value

of n by 1. If this increment is done before the moving process, the code for n elements would be

++n;

for(i=n-1;i>=pos;--i)

a[i]=a[i-1];

a[pos]=key;

The program to implement this process is: #include<stdio.h>

#include<conio.h>

void main( )

{ int a[10],n,i,key,pos;

printf(“Enter the number of values in the list:”);

scanf(“%d”,&n); printf(“Enter the values”);

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

scanf(“%d”,&a[i]);

printf(“Enter the number to be inserted:”); scanf(“%d”,&key);

printf(“Enter the position:”);

scanf(“%d”,&pos); ++n;

for(i=n-1;i>=pos;--i)

a[i]=a[i-1]; a[pos-1]=key;

printf(“The new list after insertion is :\n”);

Page 97: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 97

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

printf(“%d\t”,a[i]); getch();

}

Program 4.8 Program to delete an element from the list at a given position.

Let the position of element to be deleted be represented by pos. It is not possible to delete an element

physically from an array , but it can be overwritten by another number. After reading the value of pos move up all elements of the array from pos to the end . If the list contains 7 elements and the value of pos

is 3, the following code can be used to implement this process

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

a[i]=a[i+1];

Since an element is to be deleted , new list contains n-1 elements only. Therefore the value of n should be

decrement by 1. If this decrement is done before the process, the code for n elements would be

--n;

for(i=pos-1;i<n;++i)

a[i]=a[i+1];

The program is

#include<stdio.h>

#include<conio.h>

void main( )

{

int a[10],i,pos,n;

printf(“Enter the number of values in the list:”);

scanf(“%d”,&n);

printf(“Enter the values:”);

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

scanf(“%d”,&a[i]);

printf(“Enter the position:”);

scanf(“%d”,&pos);

if(pos<1 || pos>n)

{

printf(“Invalid position \n”);

Page 98: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 98

exit(0);

}

--n;

for(i=pos-1;i<n;++i)

a[i]=a[i+1];

printf(“The newlist after deletion is :\n”);

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

printf(“%d\t”,a[i]);

getch();

}

4.6 TWO-DIMENSIONAL ARRAYS

Two-dimensional array is defined as a set of one dimensional arrays each of same size. Two-

dimensional array is declared in the same manner as one-dimensional arrays. It will require two pairs of square brackets.

A two-dimensional array declaration can be written as

we have already seen that an n-element, one-dimensional array can be thought of as a list of values.

Similarly, an m×n, two-dimensional array can be thought of as a table of values having m rows and n

columns, as illustrated in the following figure:

Column 0 Column 1 Column 2 Column (n-1)

00a 10a 20a 10 na

Row 0

01a 11a 21a 11 na

Row 1

02a 12a 22a 12 na

Row 2

01ma 12ma 23ma 11 nma

Row (m-1)

data type array-name [constant-size1] [constant-size2];

Page 99: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 99

Some typical two-dimensional array definitions are shown below.

int mat[5][6] ; //mat is an array with 5 rows and 6 columns

float sales[6][4] ; //sales is an array with 6 rows and 4 columns

4.7 INITIALIZATION OF TWO-DIMENSIONAL ARRAYS

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their

declarations with a list of initial values enclosed in braces. For example,

int a[2][3] = {0,0,0,1,1,1};

initializes the elements of the first row to zero and the second row to one. The initialization is done row

by row and is called row major ordering.

The above statement can be equivalently written as

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

by surrounding the elements of each row by braces.

When the array is completely initialized with all values, explicitly, we need not specify the row size.

That is, the statement

int a[ ][3] = {{0,0,0}, {1, 1, 1}}; is permitted.

If the values are missing in an initialization, they are automatically set to zero. For instance, the

statement

int a[ 2 ][3] = {{1,1}, {2}}; is permitted and will initialize the first two elements of the first row to one, the first element of the second row to two, and all other elements to zero, that is

a[0][0]=1 a[1][0]=2

a[0][1]=1 a[1][1]=0

a[0][2]=0 a[1][2]=0

When all the elements are to be initialized to zero, the following short-cut method may be used.

int a[3][4] = {{0}, {0}, {0}};

The first element of each row is explicitly initialized to zero while other elements are automatically

initialized to zero. The following statement also will achieve the same result:

int a[3][4] = {0};

The following initialization of the array will result in syntax error, since the number of values in each

inner pair of braces exceeds the defined size of the array.

int a[2][3]={{1,2,3,4},{9,8,6,4,7}};

Example4.12: To store the elements of a 3x4 matrix in a two-dimensional array a, the array declaration

will be

Page 100: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 100

int a[3][4];

First row elements are stored in a[0][0],a[0][1],a[0][2] and a[0][3],second row elements are stored in

a[1][0], a[1][1], a[1][2] and a[1][3] and third row elements are stored in a[2][0], a[2][1], a[2][2] and

a[2][3].

In general, (i+1)th row elements are to be stored in a[i][0],a[i][1],a[i][2] and a[i][3]

For this the following loop will be used.

for(j=0; j<4; ++j)

scanf("%d",&a[i][j]);

To store the elements of all the rows, repeat this loop for i=0, 1, 2.

Hence the required code is

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

for(j=0; j<4; ++j)

scanf("%d",&a[i][j]);

To display the elements of a 3x4 matrix in the natural form first row elements are to be displayed on the

first line, second row elements are on second line and third row elements on third line. For this the

following code can be used.

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

{

for(j=0; j<4; ++j)

printf("%8d",a[i][j]);

printf(“\n”);

}

Program 4.9 Program to add two matrices

Given two matrices A of order r1×c1 and B of order r2×c2, we write a program to find

their sum with suitable validation.

To find the sum matrix we have to find each element of the sum matrix .In general (i,j)th

element of the sum matrix C is obtained as

C[i][j]= A[i][j] + B[i][j];

for all combinations of i=0,1,2,…,r1-1 and j=0,1,2…,c1-1.

/*Program to find sum of two matrices*/

Page 101: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 101

#include<stdio.h>

#include<conio.h>

#include <stdlib.h>

#define ROWSIZE 5

#define COLSIZE 5

void main ( )

{

int r1, c1, r2, c2, i,j;

int a[ROWSIZE] [COLSIZE], b[ROWSIZE] [COLSIZE],c[ROWSIZE] [COLSIZE];

printf (“Enter the number of rows and columns of first matrix:”);

scanf (“%d %d”, & r1, & c1);

printf (“Enter the number of rows and columns of second matrix:”);

scanf (“%d %d”, & r2, & c2);

if

{

printf (“Given matrices are not of same order and hence addition is not possible \n”);

exit (0);

}

printf (“Enter the elements of the first matrix row wise : \n”);

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

for (j=0 ; j < c1 ; ++j)

scanf (“%d”, & ;

printf (“Enter the elements of the second matrix row wise:\n”);

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

for (j=0; j < c2 ; + + j)

scanf (“%d”, & b ;

/* add the two matrices*/

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

for (j=0 ; j < c1 ; ++j)

Page 102: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 102

{

}

/*output the sum matrix */

printf “The sum matrix is : \n”);

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

{

for (j=0; j< c1 ; ++j)

printf (“%8d”, ;

printf(“\n”);

}

}/*end of main*/

Program 4.10 Program to find the product of two matrices

The following procedure will be used to find the product.

If A is a matrix of order m × p and B is a matrix of order p × n, then the (i, j)th element of the product

matrix is obtained by

jb

jb

jb

jb

aaaac

P

ipiiioiJ

1

2

1

0

121 ....

=[ai0b0j+ai1b1j+ai2b2j+……+aip-1bp-1j]

=

1

0

p

k

kjik ba

Thus, the following loop can be used to find the (i, j)th element

for (k = 0 ; k < p ; ++k)

/*Program to find the product of two matrices*/

#include<stdio.h>

Page 103: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 103

#include<conio.h>

#include<stdlib.h>

#define ROWSIZE 5

#define COLSIZE 5

void main ( )

{

int i, j ,k, r1, c1, r2, c2 ;

int a[ROWSIZE] [COLSIZE], b[ROWSIZE] [COLSIZE],c[ROWSIZE] [COLSIZE];

printf (“Enter the order of the first matrix :”);

scanf (“%d%d”, &r1, &c1);

printf (“Enter the order of the second matrix :”);

scanf (%d%d”, &r2, &c2);

if (c1 ! = r2)

{

printf (“product of given matrices does not exist \n”);

exit (0);

}

printf (“Enter the elements of first matrix row wise : \n”);

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

for (j=0; j < c1; ++j)

scanf(“%d”, &a

printf(“Enter the elements of second matrix column wise:\n”);

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

for (j=0; j< c2; ++j

scanf(“%d”, & b

/*find the elements of product matrix*/

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

for (j=0; j < c2; ++j)

{

Page 104: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 104

c[i][j] = 0;

for(k=0; k<c1; ++k)

c[i][j] + = ;

}

printf (“The product matrix is : \n”);

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

{

for (j=0; j< c2; ++j)

printf (“%8d”, c[i][j]);

printf(“\n”);

}

}/*end of main */

Program4.11 Program to check a given square matrix is symmetric

The matrix A=[aij]n m is symmetric if aij=aji for all combinations of i and j

Hence, check the condition

aij=aji for i=0,1,2,……..n-2 and j=i+1,i+2,…………n-1.

If any one pair of elements is unequal, the matrix is not symmetric

#include<stdio.h>

#include<conio.h>

void main ( )

{

int n,a[5][5],i,j,flag=0;

printf (“Enter the order of the square matrix :”);

scanf (“%d”, &n);

printf (“Enter the elements of first matrix row wise : \n”);

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

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

scanf(“%d”, &a

Page 105: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 105

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

{

for(j=i+1;j<n;++j)

if(a[i][j]!=a[j][i])

{

flag=1;

break;

}

if(flag==1)

break;

}

if(flag)

printf(“\n Given matrix is not symmetric”);

else

printf(“\n Given matrix is symmetric”);

getch();

}

Note that, if any pair of elements are unequal, 1 is assigned to flag and break is executed. Since this break

statement is in the inner loop only that loop execution is terminated. Hence the value of flag must be

compared with 1 in the outer loop.

Program4.12 Programto displayn linesof the Pascal triangle. When n=6, the triangle is as follows

In each row, first and last elements are 1‟s. In general ith row elements are obtained as follows:

a[i][0]=a[i][i]=1

a[i][j]=a[i-1][j-1]+a[i-1][j], j=1,2,……….(i-1)

1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

Page 106: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 106

Repeat this for i=0,1,2…..n-1

The program which implement this procedure is :

#include<stdio.h>

#include<conio.h>

void main ( )

{

int a[10][10],i,j,n;

printf (“Enter the value of n:”);

scanf (“%d”, &n);

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

{

a[i][0]=a[i][i]=1;

for(j=1;j<i;++j)

a[i][j]=a[i-1][j-1]+a[i-1][j];

}

printf(“The pascal triangle is: \n”);

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

{

for(j=0;j<40-3*i;++j) //To leave 40-3i blanks in the line

printf(“ “);

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

printf(“%3d “,a[i][j]);

}

}

Program4.13 Given the roll number and marks in three subjects of 100 students, write a program to determine the following:

i. Total marks obtained by each student

ii. The highest marks in each subject and the roll no, of the student who secured it. iii. The student who obtained the highest total marks.

Store the roll numbers in a one dimensional integer array rno, marks in a two dimensional array „m‟ of

size 100 4, where total marks are stored in 4th column. Find the sum of marks in each row for total

Page 107: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 107

marks, maximum marks in the first three columns for subject wise maximum and maximum marks in

fourth column for highest total marks. Display the output in a tabular form

#include<stdio.h>

#include<conio.h>

void main ( )

{

int rno[100],i,s1_rno,s2_rno,s3_rno,total_rno;

float m[100][4], s1_max,s2_max,s3_max,total_max;

printf(“ Enter the Roll no. and marks in 3 subjects of 100 students: \n”);

for(i=0;i<100,++i)

scanf(“%d%f%f%f”,&rno[i],&m[i][0],&m[i][1],&m[i][2]);

/* To find total marks of each student */

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

m[i][3]=m[i][0]+m[i][1]+m[i][2];

/* To find subject wise maximum marks and the roll numbers of the students who secured

them */

s1_max=m[0][0];

s2_max=m[0][1];

s3_max=m[0][2];

total_max=m[0][3];

s1_rno=rno[0];

s2_rno=rno[0];

s3_rno=rno[0];

total_rno=rno[0];

for(i=1;i<100;++i)

{

if(s1_max<m[i][0])

{

s1_max=m[i][0];

s1_rno=rno[i];

Page 108: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 108

}

if(s2_max<m[i][1])

{

s2_max=m[i][1];

s2_rno=rno[i];

}

if(s3_max<m[i][2])

{

s3_max=m[i][2];

s3_rno=rno[i];

}

if(total_max<m[i][3])

{

total_max=m[i][3];

total_rno=rno[i];

}

}

printf(“\n\t Roll no \t Sub1 \t Sub2 \t Sub3 \t Total\n”);

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

{

printf(“\t %d \t %6.2f \t %6.2f \t %6.2f \t %6.2f \n”,rno[i],m[i][0],m[i][1],m[i][2]);

}

printf(“Maximum marks in subject 1 is %6.2f and the roll number of the student is %d \n”,

s1_max,s1_rno);

printf(“Maximum marks in subject 2 is %6.2f and the roll number of the student is %d \n”,

s2_max, s2_rno);

printf(“Maximum marks in subject 3 is %6.2f and the roll number of the student is %d \n”,

s3_max, s3_rno);

printf(“Highest total marks is %6.2f and the roll number of the student is %d \n”, total_max, total_rno);

getch();

Page 109: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 109

}

SUMMARY

C uses arrays as a way of describing a collection of data items with identical properties. The

group has a single name for all its members, with the individual member being selected by an index. We have learnt in this unit, the basic purpose of using an array in the program, declaration

of array and assigning values to the arrays. All elements of the arrays are stored in the contagious

memory locations. Without exception, all arrays in C are indexed from 0 up to one less than the bound given in the declaration.

One important point about array declaration is that they don‟t permit the use of varying

subscripts. The numbers given must be constant expressions which can be evaluated at compile

time, not run time.

Global and static array elements are initialized to 0 by default, and automatic array elements are

filled with garbage values.

C never check whether the array index is valid – either at compile time or when the program is

running.

Single operations, which involve entire arrays, like copying one array into another array, input or

output of all the elements of the array without subscripts are not permitted in C.

EXERCISES

Multiple choice Questions:

4.1.What is the output when the following program segment is executed?

int a[5]={71,82,69,69,78};

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

printf(“%c”,a[i])

a) GREEN b)71 82 69 69 78 c)FQDDM d) ISFFO

4.2. What is the output when the following code is executed?

#include<stdio.h>

void main()

{

int arr[6]={12,13};

printf(“\n %d , %d”,a[1],a[3]);

}

a)13,garbage b)12,13 c)12,garbage d)13,0

4.3.Array name is

a)an array variable b)a key word

c)a common name shared by all elements d)not used in a program

Page 110: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 110

4.4. Array elements occupy

a)adjacent memory locations

b)random location for each element

c)varying length of memory locations for each element.

d) no space in memory.

4.5. Array is used to represent

a)a list of data items of integer data type.

b) a list of data items of real data type.

c) a list of data items of different data type.

d) a list of data items of same data type.

4.6. Array subscripts in C always starts at

a)-1 b)0 c)1 d)any value

4.7.If the size of the array is less than the number of initializes, then

a) extra values are neglected

b) it is an error

c) the size is automatically increased

d) the size is neglected.

4.8. What is the output when the following program is executed?

#include<stdio.h>

main()

{

int a[5]={1,2,3,4,5},sum=0,i=0

begin:

sum+=a[i];

++i;

if(i<5)

goto begin;

printf(“%d”,sum);

}

Page 111: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 111

a) 10 b) 1 c) 15 d)21

4.9. What is the output when the following program is executed?

#include<stdio.h>

main() {

int a[5] = { 1,3,4 } , i ;

for ( i = 4; i> = 0; --i ) printf ( “%d \t”, a[i]);

}

a)0 0 4 3 1 b) 0 4 3 1

c)1 3 4 0 d) syntax error will occur during execution of the program 4.10. What is the output when the following program is executed?

#include<stdio.h>

main() {

int a[5], i;

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

a[i] = i * i ; for( i=0; i< 5 ; ++i)

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

} a)1 4 9 16 b) 1 2 3 4 5 c) 1 4 9 16 25 d)0 1 4 9 16

4.11. What is the output when the following program is executed?

#include<stdio.h>

main()

{

int a[5] = { 3,1, 10, 20, 30},i=0,x,y,z;

x = ++a[1];

y = a[i++];

z = a[i]++;

printf( “ x= %d , y = %d, z = %d \n “ , x, y, z );

}

a)x=2,y=3,z=1 b) x=4,y=3,z=1 c) x=4,y=1,z=2 d) x=3,y=3,z=1

4.12. Identify the error in the following code.

#include<stdio.h>

main()

Page 112: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 112

{

int a[5]={9,11,3,6,4},b[5],i;

b=a;

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

printf(“\n %d”,b[i]);

}

a) variable subscript “i” is not allowed

b) since the array b is not initialized we cannot display the values of the array b

c) one array cannot be assigned to another array using assignment operator

d) array cannot be initialized in the type declaration statement

4.13. What is the output generated by the following program segment.

int a, b = 0 ;

int c[10] = {1,2,3,4,5,6,7,8,9,0};

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

if

b + = c ;

printf(“b = %d”, b);

a) b= 25 b) b= 20 c)b=45 d)15

4.14.What is the output generated by the following program segment?

int a, b = 0 ;

int c[10] = {1,2,3,4,5,6,7,8,9,0};

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

if((c[a]%2)= = 0)

b + = ;

printf(“b=%d”, b);

a) b= 25 b) b= 20 c)b=45 d)15

4.15.What is the output generated by the following program segment?

int i ;

int a[5]={0};

Page 113: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 113

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

= i +

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

printf (“%d \t”, ) ;

a)2 6 8 10 12 b)2 4 6 8 10 c)0 1 3 6 10 d) unpredictable output

4.16. What is the output generated by the following program segment?

int a, b, c ;

int x [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

for(a=0; a < 3 ; ++a)

{ c = 999 ;

for (b=0 ; b < 4 ; ++b)

if (

c =x ;

printf (“%3d”, c);

}

a) 1 2 3 b)999 999 999 c) 999 5 999 d)1 5 9

4.17. What will be the output of the flowing program ?

#include<stdio.h>

int main()

{

int arr[5], i=0;

while(i<5)

arr[i]=++i;

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

printf("%d\t ", arr[i]);

return 0;

}

a)0 1 2 3 4 b)garbage c)1 2 3 4 5 d)0 0 0 0 0

4.18. What is the output if the flowing program is executed?

Page 114: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 114

#include<stdio.h>

main()

{

int x[10],i,sum=0;

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

{ x[i]=i;

sum=sum+x[i];

}

printf(“%d \n”,sum);

}

a) 55 b) 45 c) 65 d)unpredictable output

Comprehensive Questions:

4.1 Write a program to rearrange the elements of an array in reverse order without using

a second array

4.2 Write a C program to find the binary equivalent of an integer number using array

4.3 Write a program to find median of a set of numbers

4.4 Write a program to compare two one dimensional arrays containing two sets of numbers

4.5 Write a program to find the median height of students in a section

4.6 Write a program to implement the binary search

4.7 A list of failed registered numbers of students is stored in an array. Write a program to

determine whether a given register number is in the list using linear search

4.8 Write a program for fitting a straight line through a set of points (xi, yi), i =1,2, . . . n.

The straight line equation is

y = mx + c

and the values of m and c are given by

All summations are from 1 to n.

Page 115: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Arrays 115

4.9 Given a list of 200 integers each of them ranges from 0 to 10 write a program to count

the number of occurrences of each character

4.10 The annual examinations results of 100 students are tabulated as follows:

Roll No. Subject 1 Subject 2 Subject 3 . . . . . . . .

Write a program to read the data and determine the following:

a) Total marks obtained by each student

b) The highest marks in each subject and the Roll No. of the student who secured it. c) The student who secured the highest total marks.

4.11 Write a program to find the transpose of a matrix

4.12 Write a program to find the trace of a matrix

4.13 Write a program to check if a given matrix is symmetric

4.14 Write a program to sort the elements of each row of a matrix in ascending order

4.15 Write a program that fills a five-by-five matrix as follows:

i. Upper left triangle with 1s

ii. Lower right triangle with -1s iii. Right to left diagonal with zeros

Display the contents of the matrix.

4.16 Write a program to find the transpose of a matrix without using additional array

4.17 Write a program to check if a given matrix is upper triangular

4.18 Write a program to input 10 integers and sort them. Use a menu system to determine

whether the sort should be ascending or descending order. Also determine whether the elements have to be sorted by their actual value or absolute value. The process should continue till the user

desires to exit.

Page 116: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 116

Chapter 5

FUNCTIONS

LEARNING OBJECTIVES After going through this chapter, the readers will be able to

understand the need of writing a function.

write user defined functions for a task.

write programs using structured programming concept.

understand the use of global and local variables.

apply the storage classes of variables and functions.

5.1 INTRODUCTION Consider the following program to calculate area of a circle

void main ()

{

float r, area; printf(“\nEnter radius of circle:”);

scanf(“%f”,&r);

area=3.14159*r*r; printf(“\narea=%f”,area);

}

The above example is one of the functions which contain its own set of statements for the task to find area of a circle. Now we can understand what is a function

A function is self-contained program segment which performs a specific task. For example

A function to find area of a circle

A function to find factorial of a number

A function to find gcd of two numbers

Here the task of each example is different and writing the set of statements is also independent to each

other. Generally a C program consists of one or more modules called functions, one of these functions must be

called main. Execution of the program will always begin by carrying out the instructions in main. Other

functions are subordinate to main and perhaps to one another. Program5.1 Program to read a negative number and find square root of its absolute value

void main ()

{

int a, b , c ; printf(“ \n enter a negative number : ”);

scanf(“%d”, &a );

b = abs( a ); d = sqrt( b );

printf( “ \n a=%d b=%d c=%d ”, a, b, c );

} In this program the different functions are

main() is the main function of the program

printf(), scanf(), abs() and sqrt() are the functions that are called by main( )

C functions can be classified as

i) Built-in functions(Library functions)

ii) User-defined functions

Page 117: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 117

Built-in functions

These functions are already defined and stored in C Library files. The meaning and purpose of these functions are fixed. It is not possible to change its meaning and purpose by the user, but user can

utilize these functions in their programs by including the corresponding header file.

Examples of library functions are

printf(), scanf(), sqrt(), abs(), fabs(), sin(), strlen(), toupper(), isalpha(), etc....

User-defined functions These functions will be developed by the user at the time of writing the program. The function

name, meaning and the task of the function is decided by the user. However, a user-defined function can

later become a part of the C library. main() is also a user defined function. Example5.1: Function to find area of a circle float area(float radius)

{

float a; a=3.14159*radius*radius;

return(a);

}

5.2 STRUCTURE OF A FUNCTION The structure of a function is

Where First line is called the function header.

return_type indicates the data type of a value returned by the function and it may be of any data type like int, float, double, void, array, structure, pointer etc…

function_name is the name of the function given by the user and should follow the rules of an identifier.

arg1, arg2, arg3,… are the list of arguments used to pass data from the calling function to the called function. These arguments are called formal parameters.

Local_variables declaration is the declaration of local variables if required inside the function body.

Executable statements 1,2….:indicates any executable statements that are written to perform the task of

the function. return(expression); is the statement that returns the value of expression to the calling portion of the

program. Only one expression can be included in return statement. Thus a function can return only one

value to the calling portion of the program. The structure of a function is called the definition of the function

return_type function_name (data type arg1, data type arg2…)

{

Local_variable declaration;

Executable statement 1;

Executable statement 2;

…………………………………….

…………………………………….

…………………………………….

return(expression);

}

Page 118: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 118

Example5.2: Function to return the sum of two integers

Note1: Any function whether the library or user defined function will follow the same general form. Note2: The return-type and arguments in a function are optional. When a function does not return a value

then its return-type is void and for the function with no arguments the function-name is followed by

void in the parentheses. With the combination of return-type and arguments the functions may be of different categories shown as follows.

Example5.3: A function returns biggest of two integers

int big( int x, int y)

{ if( x > y)

return(x);

else return(y);

}

Example5.4: A function to display a given integer is even or odd number void odd( int n)

{

if( n%2 = = 0 )

printf(“\n the number %d is even”, n);

else

printf(“\n the number %d is odd”, n);

}

int sum(int a, int b)

{

int s;

s=a+b;

return(s);

}

Return type Function_name

List of arguments

Local variable

declaration

Executable statement

Return statement

Page 119: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 119

Example5.5: A function to display the message “WELCOME”

Example5.6: A function to returns a mile in terms of kilometers

Advantages of writing functions Every C program must have a function with the name main() and any number of other functions. Writing

all statements of a small task in main only is fine but if the main contains large number of statements say

100,1000,10000 lines for a big task, then it leads to a number of problems like

The program may become too large and complex.

It is difficult to understand, debug and test.

It is difficult to identify the logical errors.

Repetitions of same set of statements a number of times within the same program.

It is difficult to update the program.

If such big program is divided into functional parts, then each part may be independently coded, compiled

and later integrated into a single unit. These independently coded program modules are called

subprograms. In C these subprograms are called functions and they have the following advantages.

It is easy to write, understand, debug and test a function.

It is easy to locate and isolate a faulty function for further investigation.

We can avoid writing redundant program code and hence length of the program is reduced.

If the program is divided into subprograms, each subprogram can be written by one or two members of

the

team rather than having the whole team to work on the complex program.

A function can be accessed in many programs.

5.3 CALLING A FUNCTION

Every C program must have a function with the name main and may have one or more other functions. Calling of a function means referring its name in a statement for utilizing its purpose at that point. For

example the following fun1 () is called in main function.

Program5.2 Program to display a message by calling a function in main to display the message. void fun1()

{

printf(“\n My Name is Raju \n”); }

main()

{

fun1( ); }

Output

My Name is Raju

void wel(void ) {

printf(“\n WELCOME \n”);

}

float mile_kilo( void )

{

return(1.6093440);

}

Page 120: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 120

Here the fun1() is termed as called function and the function main() is termed as calling function.

A function can be called by any other function but main cannot be called by other functions. Execution of the program begins with main irrespective of the order of the functions.

Example5.7:

main() { ………..

fun3( );

………..

}

void fun1( )

{ …………. ………….

}

void fun2( )

{ ………….

fun1( );

…………. }

void fun3( ) { ……………

fun2( );

……………} Here fun3( ) is called by main( ) and fun3( ) calls fun2( ) which calls fun1( ).

5.3.1 Calling function with no return value Since the function does not return any value, its call cannot be written in an expression but has to be by

an independent statement. For example,

Example5.8:

void main()

{ int x;

h_line();

}

void h_line() { int i;

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

printf(“-“); }

Exampple5.9: void main()

{

int x;

} void h_line()

{ int i;

for(i=0;i<10;i++) printf(“-“);

}

x=h_line();

Wrong

Page 121: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 121

5.3.2 Calling function with a return value Since the function will return a value its call is written in expressions like assignment expression, logical

expression and as an argument of another function call. For example,

Example5.10: Example5.11: float PI(void); void main()

void main() { float p,r=5.5,area;

{ float r=5.5 printf(“\narea=%f”, PI()*r*r);

p=PI(); prinf(“\nArea of circle =%.2f”,area); }

}

float PI(void) {

return(3.14159);

} Program 5.3 Write a function to return GCD of two numbers and call this function in main to find GCD

and LCM of four given numbers;

#include<stdio.h>

void main()

{

int n1,n2,n3,n4,gc1,gc2,gc,lc1,lc2,lc;

printf(“\n enter any four integers:”);

scanf(“%d%d%d%d”,&n1,&n2,&n3,&n4);

gc1=gcd(n1,n2);

gc2=gcd(n3,n4);

gc=gcd(gc1,gc2);

lc1=n1*n2/gc1;

lc2=n3*n4/gc2;

lc=lc1*lc2/gcd(lc1,lc2);

printf(“\n GCD=%d and LCM=%d”,gc,lc);

}

int gcd(int a, int b) { int r;

while((r=a%b)!=0)

{ a=b;

b=r; }

return (b);

}

Page 122: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 122

5.3.3 Calling a function with arguments

The function call with arguments is used to pass the data to the called function by the calling function. The arguments in the function call are called actual arguments / parameters and arguments in the

function header are called formal parameters or dummy arguments

Example5.12: Program to find sum of two integers using function

int sum(int a, int b) void main()

{ int s; { int x=20,y=30,k; s=a+b; k=sum(x,y);

return(s); printf(“\nvalue=%d”,k);

} } Here the arguments a, b are dummy arguments and the arguments x, y are actual arguments

Note1:Dummy argument must be a valid variable name , whereasactual argument can be a variable

name, array name, a constant, an expression or it may be a function call which will return a value. Example5.13:void main()

{ int x=20,y=30,s1,s2,s3,s4;

s1=sum(x,y); // Function call with variables as arguments.

s2=sum(50,70);// Function call with constants as arguments. s3=sum(x-5, y+20);// Function call with expressions as arguments.

s4=sum(sum(x,30),sum(50,70));// Function call expression as argument.

} Note2:The names of dummy arguments and actual argument may or may not be same. Whatever the

names may be compiler allocate different memory locations for the actual and dummy arguments.

Example5.14:void fun1( int a ) {

a+ = 5;

printf(“\n value of dummy arguments after modification is ”);

printf(“\n a=%d ”, a ); }

main()

{ int x = 20; printf(“\n value of actual argument x is”);

printf(“\n x=%d ”,x );

fun1(x);

} In the calling function main ( ) the actual argument x = 20 is passed to the called function fun1( ). In its

definition the formal parameter a is incremented by 5.

Passing data

Data can be passed from calling function to the called function in two ways 1. Call by value

2. Call by reference

In call by value a copy of the values of actual arguments from calling function are passed to the formal

parameters of the called function

Output

value of actual argument is

x = 20

value of dummy arguments after

modification is

a=25

Page 123: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 123

Example5.15:

Output: values of x and y before swap

x=20 y=30

values of x and y after swap x=20 y=30

Note:It is noticed that there is no change in the values of x and y of the function main after the call of the

function swap. Because, the function swap interchanged the values of a and b in the copy and this change is not reflected in the original arguments x and y.

In call by reference the addresses of actual arguments are passed to the formal parameters. Since the

formal parameters hold addresses, they must be declared as pointers.

Example5.16:

Output:Values of x and y before swap x=20 y=30

values of x and y after swap

x=30 y=20

Page 124: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 124

Note: since addresses of the actual parameters x and y are passed to the function swap, the interchange

made by the function swap is reflected in the actual arguments

5.4 FUNCTION PROTOTYPE

In a multi-function program there is no restriction on the order of the functions. That is the definition of

calling function can precede the called function definition and vice-versa.

But the convention is to write the definition of calling function before the definition of called function.

In this case if the called function returns a non-integer value, the calling function definition should be

preceded by a forward declaration about the type of value returned by the called function. This forward

declaration is called function prototype

The general form of function prototype is

This is illustrated in the following example

Example5.17: Program to find area of a circle using a function which will calculate and return area float area( float radius)

{

return(3.14159*radius*radius);

} void main()

{

float r,a; printf(“\n Enter radius of circle:”);

scanf(“%f”,&f);

a=area(r); printf(“\n area value=%f”,a);

}

Since the definition of the called function area appears before the calling function there will be no syntax

error, as the function area is compiled before main. But the convention is to write the definition of the calling function before the called function shown as

follows.

void main() {

float r,a;

printf(“\n Enter radius of circle:”); scanf(“%f”,&r);

a=area(r);

printf(“\n area value=%f”,a);

} float area( float radius)

{

return(3.14159*radius*radius); } In this case as the function main is compiled first, as there is no declaration regarding the function area

compiler assumes that area is the name of a function and it return, an integer value. But in the function

header

float area( float radius) it is mentioned that the return data type is float. Hence, syntax error will occur when the function header

is encountered during compilation . To avoid this error we give advance information to the compiler

return_type function_name(data type arg1,data type arg2,……….);

Page 125: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 125

about the type of value returned by the function and the number and type of arguments. This is achieved

by writing the function prototype before the definition of main. Note: Function prototype is required for all the functions except the functions of return_type int.

Program5.4 Program to find area of a circle using function float area(float radius); //Function prototype

void main()

{

float r,a; printf(“\n Enter radius of circle:”);

scanf(“%f”,&r);

a=area(r); printf(“\n area value=%f”,a);

}

float area( float radius) {

return(3.14159*radius*radius);

}

Program5.5 Program tofind median of a list of numbers using a function to sort the list of numbers.

void bub_sort( int n, float a[10]); // Function prototype

void main() {

int n,i;

float a[10], median; printf(“\n Enter the no of values:”);

scanf(“%d”, &n);

printf(“\n Enter the values”)

for(i=0; i<n; ++i) scanf(“%f”, &a[i]);

bub_sort(n,a);

if(n%2) median = a[(n-1)/2];

else

median = (a[n/2] + a[n/2-1])/2;

printf(“\n median =%.2f”, median); }

void bub_sort(int n, float a[10])

{ int p,j; float temp;

for (p=1; p<n; ++p)

for(j=1; j<n-p; ++j) if(a[j]>a[j+1])

{

temp= a[j];

a[j] = a[j+1]; a[j+1] = temp;

}

return; }

Page 126: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 126

5.5 CATEGORIES OF FUNCTIONS

Based on the arguments present or not and a value is returned or not, the function may belong to one of

the following categories. 1. Functions with arguments and return value

2. Functions with arguments and no return value

3. Functions with no arguments and return value

4. Functions with no arguments and no return value

5.5.1 Functions with arguments and return value

Functions with arguments means the data required by the called function is passed through arguments from the calling function and with return value means, the calling function will receive a value of type

return_type from the called function.

That is the data is passed from the calling function to the called function and the called function return a value to the calling function. The general form of this function is

return_type function_name (data type arg_1, data type arg_2,…, data type arg_n)

{ ……………………..

…………………….. ……………………..

return(expression);

} Example5.18: Function to return simple interest for any given values of principle in rupees, time in years

and rate of interest

float simple_intrest(float principle, float time, float rate ) { float I;

I = principle * time * rate/100;

return( I);

} Example5.19: Function to return area of a circle.

float area(float radius)

{ float a;

a=3.14159*radius*radius;

return(a);

} Program5.6: Write a function power that computes x raised to the power y where x is float and y is a

integer.

#include<stdio.h>

double power(int x, int y);

void main() {

int y ;

float x;

double p; printf(“\n Enter base and exponent:”);

scanf(“%f%d”,&x,&y);

if(y>0) p=power(x,y);

else

Page 127: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 127

p = 1.0/power(x,y);

printf(“\n value of %f to the power of %d is %lf”,x,y,p); }

double power(int x,int y)

{ double p=1;

while(y--)

p*=x;

return(p); }

5.5.2 Functions with arguments and no return value

Function with arguments means, the required data is passed from the calling function to the called function through arguments and function with no return value means the called function does not return

any value to the calling function. In this case the return data type is void.

The general form of this type of function is

void function_name (data type arg_1, data type arg_2,…data type arg_n)

{ ……………………..

…………………….. ……………………..

return; }

Example5.20: Function to display a matrix void display(int m,int n,int a[10][10])

{

int i,j; for(i=0;i<m;++i)

{

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

printf(“%5d”a[i][j]); printf(“\n”);

}

return; }

In the above function the called function receive the address of the array which contains the matrix and

display it. It does not return any value to the calling function.

Example5.21: Function to print the given title. void title(char str[] )

{

printf (“%s”, str); return;

}

5.5.3 Functions with no arguments and return value Functions with no arguments means, no data is passed from the calling function to the called function

through the arguments, and with return value means, the called function will return a value of type

return_type to the calling function.

return_type function_name ( void) { ……………………..

……………………..

…………………….. return(expression);

}

Page 128: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 128

Eample5.22: Function to return pi value

float pi ( void) {

return(3.14159);

}

5.5.4 Functions with no arguments and no return value

Function with no arguments means, no data is passed from the calling function to the called function, and

function with no return value means; the called function does not return any value to the calling function. In this case the return data type is void

The general form of this type of function is

void function_name (void) { ……………………..

……………………..

…………………….. return;

}

Example5.23: Function to print the title “K L University”

void title(void) { printf (“K L University”);

return;

} Example5.24: Function to clear the screen

void clear_screen(void)

{ int i;

for(i=1;i<=25;++i)

printf(“\n”);

return; }

Program 5.7 Write a function to return factorial of a number and call this function in main to find the

value of the Binomial coefficient C(n,r)

#include<stdio.h>

long int factorial(int n); void main()

{

int n,r;

long ncr; printf(“\n Enter the values of n and r :”);

scanf(“%d%d”, &n, &r);

ncr = factorial(n)/(factorial( r )*factorial(n-r)); printf(“\n C(%d, %d) = %ld”, n, r, ncr);

}

long int factorial(int n)

{ long int f=1;

int i;

for(i=1; i<=n; i++) f = f * i;

Page 129: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 129

return(f);

}

5.6 PASSING ARRAYS TO FUNCTIONS

5.6.1Functions with One-Dimensional Arrays: Arrays can be passed to a function through arguments when an array is passed through argument, base

address of the array is passed. Therefore passing array is always call by reference

To pass one-dimensional array to a called function, simply write the name of array as actual argument without any subscripts, and size of array.

Program 5.8 Write a function to return largest of a list of integers and call this function in main to find

largest of a given list integer values.

#include<stdio.h> int max(int a[50], int n);

void main()

{ int a[50], larg,i,n;

printf(“\n Enter no of elements in the list”);

scanf(“%d”,&n);

printf(“\n Enter %d elements:”,n); for(i=0; i<n; i++)

scanf(“%d”,&a[i]);

larg=max(a,n); printf(“\n largest number of the list is %d”, larg);

}

int max(int a[50], int n) { int i,big;

big=a[0];

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

{ if(big<a[i])

big=a[i];

} return(big);

}

Program 5.9 Program to arrange a list of in ascending order using a function that will sort the list. #include<stdio.h>

void sort(int a[50], int n);

void main()

{ int rank[50],i,n;

printf(“\n enter the no of elements in the array:”);

scanf(“%d”,&n); printf(“\n enter %d elements:”,n);

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

scanf(“%d”,&rank[i]);

sort(rank,n); printf(“\n\n Elements after sort:\n\n”);

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

printf(“%5d”,rank[i]); }

sort(int x[50], int n)

Page 130: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 130

{

int p,i,temp; for(p=1; p<n; ++p)

{

for(i=0; i<n-p;++ i) {

if(x[i]>x[i+1])

{

temp=x[i]; x[i]=x[i+1];

x[i+1]=temp;

} }

}

} Program 5.10 Write function to reverse the elements of an array .Use this in main to display the given

list in reverse order.

#include<stdio.h>

void print_rev(int a[ ], int ); void main()

{

int a[50],n,i; printf(„\n Enter no of elements in the array:”);

scanf(“%d”,&n);

printf(“\n Enter %d number of elements:”,n); for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

printf(“\nElements in reverse order:\n”);

for(i=0;i<n;i++) printf(“%5d”,a[i]);

}

void reverse( int a[50],int n) {

for(i=0,j=n-1;i<j;++i,--j)

{

temp=a[i]; a[i]=a[j];

a[j]=temp;

} return;

}

5.6.2 Functions with Two-Dimensional Arrays To pass multi-dimensional array to a function we should fallow the following rules

In the function definition, the formal parameter must be two-dimensional array by indicating two

subscripts.

The size of second subscript must be specified.

The prototype declaration should be similar to the function definition

The function must be called simply by passing the array name only.

Page 131: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 131

Program 5.11 Writefunctions to read and display a matric .Call them in the main to read the elements of

a matrix from key board and display it. #include<stdio.h>

void read_mat(int a[10][10], int r, int c);

void print_mat(int a[10][10], int r, int c); void main()

{

int a[10][10],m,n;

printf(“\n Enter no of rows and calms of matrix:”); scanf(“%d%d”,&m,&n);

printf(“\n Enter the elements of the matrix row wise:”);

read_mat(a,m,n); printf(“\n Given matrix is:\n”);

print_mat(a,m,n);

} void read_mat(int a[10][10], int r, int c)

{ int i,j;

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

for (j=0; j<c; j++) scanf(“%d”, &a[i][j]);

}

void print_mat(int a[][10], int r, int c) { int i,j;

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

{ for(j=0; j<c; j++)

printf(“%5d”,a[i][j]);

printf(“\n”);

} }

Program 5.12 Program for addition of two given matrices using the functions to read ,display and add

the matrices. #include<stdio.h>

void read_mat(int a[10][10], int r, int c);

void print_mat(int a[10][10], int r, int c);

void add_mat(int a[10][10], int b[10][10], int c[10][10], int r1, int c1); void main()

{

int a[10][10], b[10][10], c[10][10], m1, m2, n1, n2; printf(“\n Enter the no rows and columns of 1

st matrix:”);

scanf(“%d%d”, &m1, &n1);

printf(“\n Enter the no rows and columns of 2nd

matrix :”); scanf(“%d%d”, &m2, &n2)

if(m1!=m2 ||n1!=n2)

{ printf(“Addition not possible \n”);

exit(0); }

printf(“\n Enter the elements of 1st matrix row wise :\n”);

read_mat(a,m1,n1); printf(“\n Enter the elements of 2

nd matrix row wise :\n”);

read_mat(b,m2,n2);

Page 132: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 132

add_mat(a,b,c,m1,n1);

printf(“\n Sum matrix is:\n”); print_mat(c,m1,n1);

}

void add_mat(int a[10][10], b[10][10], c[10][10], int r1, int c1) {

int i,j;

{

for(i=0;i<r1;i++) for(j=0;j<c1;j++)

c[i][j]=a[i][j]+b[i][j];

} return;

}

void read_mat(int a[10][10], int r, int c) { int i,j;

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

for (j=0; j<c; j++)

scanf(“%d”, &a[i][j]); }

void print_mat(int a[][10], int r, int c)

{ int i,j; for(i=0; i<r; i++)

{

for(j=0; j<c; j++) printf(“%5d”,a[i][j]);

printf(“\n”);

}

} Program 5.13 Program for multiplication of two given matrices using functions.

#include<stdio.h>

void read_mat(int a[10][10], int r, int c); void print_mat(int a[10][10], int r, int c);

void mult_mat(int a[10][10], int b[10][10], int c[10][10], int r1, int c1, int r2, int c2);

void main()

{ int a[10][10],b[10][10],c[10][10],m1,m2,n1,n2;

printf(“\n Enter the no rows and columns of 1st matrix:”);

scanf(“%d%d”, &m1, &n1); printf(“\n Enter the no rows and columns of 2

nd matrix :”);

scanf(“%d%d”, &m2, &n2)

if(n1!=m2) {printf(“multiplication not possible \n”);

exit(0);

}

printf(“\n Enter the elements of 1st matrix row wise :\n”);

read_mat(a,m1,n1);

printf(“\n Enter the elements of 2nd

matrix row wise :\n”);

read_mat(b,m2,n2); mult_mat(a,b,c,m1,n1,m2,n2);

printf(“\n Product matrix is:\n”);

Page 133: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 133

print_mat(c,m1,n2);

} void mult_mat(int a[10][10], b[10][10], c[10][10], int r1, int c1, int r2, int c2)

{

int i,j,k; for(i=0; i<r1; i++)

{ for(j=0;j<c2;j++)

{c[i][j]=0;

for(k=0;k<c1;k++) c[i][j]+=a[i][k]*b[k][j];

}

} }

void read_mat(int a[10][10], int r, int c)

{int i,j; for(i=0; i<r; i++)

for (j=0; j<c; j++)

scanf(“%d”, &a[i][j]);

} void print_mat(int a[][10], int r, int c)

{int i,j;

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

for(j=0; j<c; j++)

printf(“%5d”,a[i][j]); printf(“\n”);

}

}

5.7 BUILT-IN FUNCTION

In C library, several functions are available to perform various tasks like data input/output, calculation of

the values of mathematical functions, string manipulations, etc….which are needed in writing different application programs. These functions are called library functions or built-in functions. Since a large

number of built-in functions are available they are classified into different categories and their headers are

stored in different header files

Some of the header files corresponding to C standard libraries are

1. math.h – contains the headers of mathematical functions and macros 2. stdio.h – contains the headers of standard input and output functions and macros

3. string.h – contains the functions for string manipulation and processing

4. conio.h – contains the headers of console input/output functions 5. ctype.h – contains the headers of character type and manipulation functions

Some important built-in functions stored in the header files are

S.No Header file Function Use of the function

1

math.h

abs( ) Gets the absolute value of an integer

2 fabs( ) Gets the absolute value os a real value

3 sqrt( ) Calculates the positive square root of the input value

4 sin( ) Computes the sign of the input value

5 cos( ) Computes the cos of the input value

Page 134: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 134

6 tan( ) Calculates the tangent of the input value

7 asin( ) Computes the arc sin of the value

8 acos( ) Computes the arc cosine of the input value

9 atan( ) Calculates the arc tangent of the input value

10 exp( ) Calculates e to the x the power

11 pow( ) Calculates x to the power y

12 log( ) Calculates natural logarithm of input value

13 log10( ) Calculates bse10 logarithm of input value

14

stdio.h

scanf() To read input data in a given format through key board

15 printf( ) To display data in a given format on the screen

16 getchar( ) To read a character through key board

17 putchar( ) To display a character on the screen

18 gets( ) To read a string through key board

19 puts( ) To display string on the screen

20 flushall( ) Clears all buffers associated with open input stream

21

string.h

strlen( ) Calculates length of a string

22 strcpy( ) Copies one string into another string

23 strcmp( ) Compares two strings

24 strcat( ) Joins two strings together

25

ctype.h

toupper() Convert the given alphabet into uppercase

26 tolower() Convert the given character into lower case

27 isalpha() Check whether the given character is alphabetic or not

abs( ) its prototype is int abs( int x); fabs( ) its prototype is double fabs(double x);

Example5.25: int x= -1234, y;

double r=5.45, s;

y=abs(x);

s=fabs(r);

sqrt( ) its prototype is double sqrt(double x);

Example 5.26: double x=4.0, result;

result = sqrt(x);

sin( ) its prototype is double sin(double x); where x in radians

cos( ) its prototype is double cos(double x); where x in radians

tan( ) its prototype is double tan(double x); where x in radians

Example5.27: float angle=60, a1,a2,a3;

a1=sin(3.14159*angle/180);

a2=cos(3.14159*angle/180);

a3=tan(3.14159*angle/180);

Page 135: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 135

exp( ) its prototype is double exp(double x);

pow( ) its prototype isdouble pow(double x, double y);

log( ) its prototype is double log(double x);

log10( ) its prototype is double log10(double x);

Example5.28:Double p=8.687, x=2.0, y=3.0, r1,r2,3;

r1 = exp(p);

r2 = log(p);

r3 = pow(x,y);

5.8 RECURSION

Calling of a function by itself repeatedly until a condition is satisfied is called recursion.

Example5.29:

void fun1() {

--------

fun1(); --------

}

The function call fun1() is in the body of the function fun1().Thus fun1() calls itself. This feature is called

recursion.

Example5.30:

void main() {

printf(“\nKLU”);

main(); }

In this example main() calls itself indefinitely.

How to write a recursive function? Since recursion process simulates repetitive process, it is required to check a condition for stopping the

repetitions.

Example5.31: Recursive function to find factorial of an integer Factorial of an integer is a recursive function in Mathematics and is defined as follows

n!= 1 , if n=0 or 1

= n(n-1)! , if n>1

Using this mathematical function we can write the corresponding C code. long int factorial ( int n)

{

if (n==0 ) return(1);

else

return( n*factorial(n-1));

Output

KLU

KLU

…….Infinite number of times

( “KLU” is displayed infinite number

of times)

Page 136: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 136

long int factorial( int n );

void main( )

{ int n,f; printf(“\n Enter a number:”);

scanf(“%d”, &n);

f=factorial(n); printf(“\n factorial of given num %d is %”, n, f);

}long int factorial(int n)

{ long int f;

5.9 STORAGE CLASSES

5.9.1 Global & Local Variables

Variables declared in programs may be classified into two categories

1. Local variables

2. Global variables In all the programs written so far variables are declared inside of the functions. Such variables are called

local variables, However, variables may be declared outside the scope of a function such variables are

called global variables.

Local Variables:

Local variables scope is confined within the block or function where it is defined. That is, it is

recognized within the block or the function

Example5.32:

main()

{ int i=4; int j=10;

Output

value of i inside the block = 100

value of i outside the block=5

Page 137: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 137

i++;

if (j > 0) {

int i=100;

printf("value of i inside the block = %d\n",i); }

printf("value of i outside the block= %d\n",i);

}

Global Variables

Scope of the global variables is from the point of declaration through the remainder of the program. i.e.

any

function which falls in their scope can access their values.

If the global variables declaration does not include initial values they are initialized by the system as

follows: Datatype initialser

int 0

char „\0‟ float 0

pointer NULL

If same variable name is being used for global and local variable then local variable takes precedence

in its scope. But it is not a good practice to use same name for both global and local variable.

Example5.33: int i=4; /* Global definition */

main()

{ i++; /* Global variable scces */ func();

printf( "Value of global variable\ n i = %d\n", i );

} func()

{ int i=10; /* Local declaration of i */

i++;

printf( "Value of local variable in the function func \n i = %d\n", i ); }

Output

Value of local variable in the function func

i = 11

Value of global variable

i = 5

Page 138: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 138

Note: differences between local and global variables

5.9.2 Storage Classes

Each Variable in C is characterized by its

1 data type

2 storage class

Data type refers the type of data to be stored in the memory location allotted to that variable.

int x,y; // x and y are integer variables and represent integer data

float r; // r is a float variable and represent floating point type data

Storage class refers to the scope and longevity(life time) of a variable. It also describes the

default initial value and memory location

The scope actually determines the portion of the program that the variable is recognized.

The longevity of the variable determines how long the variable is alive or active.

There are four different storage classes in C and they are represented by the keywords

auto - automatic variables,

extern - external variables,

Local variables

1. Variables declared inside a function or a statement block are

called local variables.

2. For example void main( )

{ int x,y;

……..

}

3. Local variable can be accessed

only within the function in which it

is defined

4. Variables defined in one function

cannot be accessed in other

functions.

5. Values of local variable cannot be

modified by other functions except

the function in which it is defined.

6. If the values of local variables are

needed by other functions they

must be passed through arguments

in the function call

Global variables

1. Variables declared outside a

function are called global

variables. 2. For example

int x,y;

void main( )

{ …….

}

3. Global variable can be accessed

throughout the program

4. Global variables can be accessed by any function which falls in their

scope.

5. Values of global variable can be modified by other functions which

fall in its scope.

6. Since the global variables are recognized by any function within

their scope their values need not be

passed through arguments

Page 139: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 139

static - static variables and

register - register variables.

The general form of variable declaration with storage class is

For example

auto int x; // x is an automatic integer variable

static float y // y is static floating point variable

5.9.2.1 Automatic variables

The automatic variables are declared inside a function or a block

void main()

{ auto int x,y; //x and y are automatic variables

………………. ………………..

}

However, local variables without any storage class specifier will have the default storage class auto

void fun1() { int c,k; // c and k are automatic variables

………..

}

Scope: The scope of automatic variable is local to the function in which it is defined.

Life time: The lifetime of automatic variable is temporary. i.e. it is defined when a function is called

for execution and is destroyed when the control is exited from its defining function

Since x is automatic variable and is reinitialized with 10 in every call of fun1( ). Hence, fun1( ) returns same value 11 to main( ) in every call.

Storage_class data_type variable_name1, variable_name2,…..;

void main( )

{ int i;

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

printf(“%d\n”, fun1( ));

}

int fun1( )

{ x=10;

return(++x);

}

Output

x=11

x=11

x=11

x=11

Page 140: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 140

Default initial value: The default initial value of automatic variable is garbage

Since y is automatic variable and is not initialized, its default initial value is garbage. Automatic variables

can be initialized with expressions. For example,

int a=10, b=5, c = a+b; is allowed.

Memory location: These variables are located in main memory.

Note1: Variable defined in one function is not accessible to any other function.

Example5.34:

void main() { int x=25;

printf(“\n x=%d”,x);

}

void fun1()

{ int y=50; printf(“\n x=%d”,x);

printf(“\n y=%d”, y);

}

void fun2() { x=1000;

y=2000;

} Note2: If the name of global and local variables is same then in the scope of local variable the first

priority is for local variables. In such cases the value of global variable is temporarily put on shelf and

beyond the scope of local variable. Example5.35: what is the output of the following program?

x- is local to main( ) but

not accessed in fun1( )

x- is local to main( ) and y- is

local to fun1( ) but not

accessed in fun2( )

Output

y= garbage

void main( )

{

int y;

printf(“\n y=%d”, y+=5);

}

Page 141: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 141

5.9.2.2 External variables

Variables that are declared outside the scope of any function are external variables. All global variables

are

external variables. int s;

void main()

{ s=96; // s is global variable ………..

…………

} float r;

void fun1()

{

r=5.4; // r is global variable ……….

}

Scope: The scope of external variables extends from the point of definition through the remainder of

the Program

Life time: The lifetime of global variables is permanent i.e. they retain their values throughout the

execution of

the program

Default initial value: The default initial value of external variable is zero. External variables cannot be

initialized with expressions. For example,

int a=5, b=10, c=a+b; is not allowed, if a,b,c are external variables

Memory location: These variables are located in main memory.

Note1: Since external variables are recognized globally, they can be accessed from any function that falls within their scope, thus, an external variable can be assigned a value within one function, and this value

can be used within another function.

Example5.36: what is the output of the following program? int x=96;

Page 142: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 142

void main( )

{ printf(“\n x=%d”x)‟

fun1();

fun2(); printf(“\n x=%d”,x);

}

void fun1( )

{ x=200; printf(“\n x=%d”, x);

}

void fun2() { printf(“\n x=%d”,x);

x=500; }

Note2: If a global variable is accessed before it is defined then it needs to be declared as an external variable using the key word extern

Example5.37: What is the output of the following program

void main( )

{ extern int x; printf(“\n x=%d”, x );

fun1();

} int x;

void fun1()

{ x=200;

printf(„\n x=%d”, x );

}

Declaration Vs definition

The external declaration of x inside the function main informs the compiler that x is an integer type

defined

somewhere else in the program. Note that the extern declaration does not allocate storage space for variable x, where as variable definition outside the function does allocate storage space for variable

The assignment of initial values can be included within an external variable definition whereas the

external

variable declaration cannot include initial values as no storage space is allocated.

The storage class specifier extern is not required in an external variable definition whereas external

declaration must begin with the storage class specifier extern.

5.9.2.3 Static variables

In some of the applications, it is needed to retain the value of a variable even after the control is exited

from the function. For this purpose, variables of static storage class are used.

Static variables may be internal variables or external variables.

Internal static variables are declared inside a function using the key word static. Whereas external

static variables are declared outside of a function using the key word static.

Output

x=96

x=200

x=200

x=500

Output

x=200

x=200

External variable

declaration (memory not

allocated)

External variable

definition (memory is

allocated)

Page 143: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 143

static int c; // c is static external

int s; // s is external void main()

{ static int x; //x is static internal variable

int i,j; // i and j are automatic variables …….

…..

}

void fun1(void) { static int c,k; // c and k are static internal variable

……..

}

Scope: The scope of internal static internal is local to the function in which it is defined and the scope

of static external variable is from the point of declaration through the remainder of the program

Life time: The lifetime of static variable is permanent. Internal static variable retain its value even after

the control is exited from the function

Example5.38: What is the output of the following program

The internal static variable x initialized only once at compilation time. Since it retains its values during

successive function calls the values returned by fun1( ) to the function main( ) are 11, 12, 13 and 14 in the first, second, third and fourth calls.

void main( )

{ int i;

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

printf(“%d\n”, fun1( ));

}

int fun1(void )

{ static int x=10;

return(++x);

}

Output

x=11

x=12

x=13

x=14

Page 144: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 144

Default initial value: The default initial value of internal or external static variable is zero

Since x and y are static variables they are initialized with zero rather than garbage.

Memory location: Both these variables are located in main memory.

The difference between static external variable and a simple external variable is that the static variable

is available only within the file where it is defined , while the simple external variable can be accessed by

other files.

5.9.2.4 Register variables

Storage space normally allocated for variable in main memory.

It is possible to tell the compiler that a variable should be kept in the CPU registers by defining it as

register

variable.

Since a register access is much faster than memory access, keeping the frequently accessed variables

(like loop control variables) in the register will make the execution of the program faster.

Except the memory space allocation all the other properties of register variables are similar to that of

automatic

variables.

Very few variables can be placed in the registers. Normally two or three per function.

Only local variables of type int, char can be declared with the storage class register

void main( )

{

register int i; // i is register variable.

…………………

for(i=0; i<=10000; i++) { }

………………..

………………...

}

Scope: The scope is local to the function in which it is defined.

Life time: The life time of register variables is temporary

Default initial value: The default initial value is garbage

Memory location: These variables are located in registers of CPU

Output

x=1

y=5

static int x;

void main( )

{

static int y;

printf(“\n x=%d”,

++x);

printf(“\n y=%d”,

y+=5);

}

Page 145: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 145

SUMMARY

A function is a module or block of program code which deals with a particular task. Defining

functions for each task is a way of isolating one block of code from other independent blocks of code.

A function can take a number of parameters, do required for processing and then return a value. There

may be a function which does not return any value, but perform a given task.

You already have seen couple of built-in functions like printf( ); Similar way you can define your

own functions in C language.

Consider the following code

int total = 20;

printf(“Hellow World”);

total = total+1;

To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single

compound statement and write the name that you want to give it in front of the brackets:

demo( )

{ int total = 20;

printf("Hello World");

total = total + l;

}

Curly brackets after the function's name are required. One or more parameters to a function can be

passed as

follows

demo( int a, int b)

{ int total;

printf("Hello World");

total = a + b;

}

By default function does not return anything. But you can make a function to return any value as

follows:

int demo( int a, int b) { int total;

printf("Hello World");

total = a + b; return (total);

}

Page 146: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 146

A return keyword is used to return a value and datatype of the returned value is specified before the

name of function. In this case function returns total which is int type. If a function does not return a

value then the return data type is void.

Once a function is defined it can be used within a program:

Each function behaves the same way as C language standard function main(). So a function will have

its own local variables defined. In the above example the variable total is local to the function demo.

A global variable can be accessed in any function in a similar way as it is accessed in main() function.

A function declaration does not have any body.

A function declaration is usually declared at the top of a C source file, or in a separate header file.

A function declaration is sometimes called function prototype. For the above demo() function which

returns an integer, and takes two parameters a function declaration will be as follows:

A function can be called recursively. The following code prints the word Hallow repeatedly because the

main( ) is called recursively

void main( )

{

printf(“Hallow”);

main();

}

A recursive function code involves if....else control to decide whether the recursive call is to be

continued or to be stop. The following code prints the output 0 1 2 void f( )

{

static int x;

if(x==3) return;

else

{

printf(“ %d”, x);

main()

{ int s;

s=demo(20,30);

}

int demo( int a, int b);

Page 147: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 147

x++;

f( );

}

}

There are two ways to pass parameters to a function:

Pass by Value mechanism is used when you don't want to change the value of passed paramters. When

parameters are passed by value then functions in C create copies of the passed variables and do

required processing on these copied values. Pass by Reference mechanism is used when you want a function to do the changes in passed

parameters and reflect those changes back to the calling function. In this case only addresses of the

variables are passed to a function so that function can work directly with original data through addresses.

EXERCISES

Multiple choice questions:

1.What is the output when the following code is executed? #include<stdio.h>

main()

{

int p=10; printf(“%d”,fun(p));

}

int fun(int x) {

if(x>0)

return(x+fun(x-1));

else return(0);

}

a) 0 b) 55 c) 45 d) 10

2.What is the output when the following code is executed?

#include<stdio.h> void main()

{

int n;

for(n=1;n<5;++n) printf(“\t %d “, fun());

}

int fun(void) {

static int x;

return(--x); }

Page 148: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 148

a) 1 1 1 1 1 b) 1 2 3 4 5 c) 0 1 2 3 4 d)Garbage

value as x is not initialized in function fun 3. 3.What is the output when the following code is executed?

#include<stdio.h>

int i; int fun();

int main()

{

while(i) {

fun();

main(); }

printf("Hello\n");

return 0; }

int fun()

{

printf("Hi"); }

a) Hello indefinitely b)Hello c)Hello two times on separate lines d) No Output

4. What is the output when the following code is executed? #include<stdio.h>

int reverse(int);

int main() {

int no=5;

reverse(no);

return 0; }

int reverse(int no)

{ if(no == 0)

return 0;

else

printf("%d \t ", no); reverse (reverse(--no);

}

a) 5 4 3 2 1 b) 5 4 3 2 1 0 c)5 5 5 5 5 d) 1 2 3 4 5

5. What is the output when the following code is executed?

#include<stdio.h> void fun(int);

int main()

{

int a=3; fun(a);

return 0;

} void fun(int n)

{

Page 149: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 149

if(n > 0)

{ fun(--n);

printf("%d,", n);

fun(--n); }

}

6. There is an error in the following program. Which statement will you add to remove it?

#include<stdio.h> int main()

{

int a; a = f(10, 3.14);

printf("%d\n", a);

return 0; }

float f(int aa, float bb)

{

return ((float)aa + bb); }

a) a separate statement to add aa and bb in function f b)Type declaration in the function f

c)function prototype d) none of these

7. Point out the error in the program

#include<stdio.h> int main()

{

int a=10;

void f(); a = f();

printf("%d\n", a);

return 0; }

void f()

{

printf("Hi"); }

8.Find the output of the following program segement. #include <stdio.h>

main()

{ int j,ans;

j = 4;

ans = count(j);

printf("%d\n",ans); }

int count(int i) {

if ( i < 0) return(i);

Page 150: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 150

else

return( count(i-2) + count(i-1)); }

a) -17 b) -10 c)-4 d) 4

9. What will be the output when the flowing program segment is executed?

#include<stdio.h>

int i;

void increment(int i) {

i++;

} int main()

{

for(i=0;i<10;increment(i)) {

}

printf(“i=%d\t “,i)

return 0; }

a) 1 2 3 …. 10 b)10 c)1 2 3 …. 11 d) No ouput

10.What will be the output when the flowing program segment is executed? #include<stdio.h>

void func()

{ int x=0;

static int y=0;

x++; y++;

printf(“ x=%d,y= %d \t”,x,y); }

int main()

{ func();

func();

return 0;

} a)x=1,y=1 x=1,y=2 b) x=1,y=0 x=1,y=1

c) x=1,y=1 x=2,y=2 d) x=1,y=1 x=1,y=1

11. What is the output when the flowing program segment is executed? int a=1,b=2;

int f1(int a,int b);

main() {

int i=1,c,d;

c=5*(i+1);

d=10*(i-1); printf(“% d, %d “,f1(a,c),f1(b,d));

}

} int f1(int x,int y)

{

Page 151: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 151

return(x*y);

} a) 10,0 b)11,0 c)10,1 d)11,1

12. What is the need for functions? 13. Explain the general form of defining a function.

14. What do you mean by function call?

15. What are formal arguments?

16. What are actual arguments? 17. Define function prototype.

18. Mention the categories of functions.

19. What is calling function? 20. What is a called function?

21. The number of actual arguments and the number of formal arguments should be same

when a function is called. True / False 22. One function can be defined within another function. True / false

23. How many values can a function return?

24. What is meant by the scope of a variable?

25. What is meant by lifetime of a variable? 26. Mention different storage classes.

27. Define recursion and a recursive function

28. A function can returns float value by default. True / False 29. Variables declared within functions are by default of static storage class. True / False

30. The name of global variable and that of a local variable can be same. True / False

31. Only local variables can be of register storage class. True / False 32. Static variables retain their values between function calls. True / False

33. Write about storage classes in C along with their location, scope and life span.

Comprehensive Questions:

5.1 Discuss how parameters are passed between functions in C by writing a function swap to exchange the values of two integers passed to it by the main function.

5.2 Write about storage classes in C along with their location, scope and life span.

5.3 What is a recursion ? Write a recursive function two find n!

5.4 Write a non-recursive function to find the factorial of a given integer.

5.5 Write a function to find the greatest common divisor(gcd) of two integers passed as parameters to it and a

program to call the function repeatedly to find the gcd of four integers.

5.6 How do you pass data to a function? Explain the concept of call by value and call by reference through

suitable examples.

5.7 Write a function to find the factorial of an integer and use it to write a program for finding the number of

combinations C(n,r) possible, given the values of n and r.

C(n,r) = n!/ (n-r)!r!

5.8 Write a recursive function that will generate a given element of Fibonacci sequence. Use this

function in

main to print first n elements of Fibonacci sequence.

5.9 Write a function to find gcd of two numbers and use this function to find their lcm .

5.10 Write a recursive function for binary search with function prototype.

Page 152: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Functions 152

int binsearch(int data[], int key,int ll,int ul); and call this function in main() to test this function.

5.11 Write a function which imitates the behavior of strlen() function. Use this function to check if a given string is a palindrome or not.

5.12 Write a recursive function power that computes ax w here a is a real constants and x is an integer.

5.13 Write a function that will scan a character string passed as an argument and convert all lower case

character into their uppercase equivalents.

5.14 Write a function that can be called to find the largest element of an m X n matrix

5.15 Write a function that converts miles to kilometers. Note that 1 mile equals 1.6093440 km.

5.16 Write a function that will round a floating-point number. For example the number 17.457 would

yield the value 17.46 when it is rounded off to two decimal places.

5.17 Write a recursive function to find the binary code of a decimal inreger.

5.18 Write a program to find the reverse of a number using function

5.19 Write a function isprime that returns 1 if its argument is a prime number and returns zero otherwise.

5.20 Write a function to evaluate the formula y = xn where y and x are floating-point variables and n is

an integer variable

5.21 Calculate factorials n! for n from 1 to 20 using a factorial function with return type of unsigned long

long.

5.22 Discuss how parameters are passed between functions in C by writing a function „SWAP‟ to exchange the values of two integers passed to it by the main( ) function.

5.23 Write a function sort to sort a list of values and call this function in main to find the median of a list

of n numbers

5.24 Write a program to reverse an integer using a recursive function

5.25 The Fibonacci numbers are defined recursively as follows F1 = 1

F2 = 1

Fn = Fn-1 + Fn-2 if n>2

i) Write a recursive function that will find n th element of the Fibonacci sequence ii) Write a function with local static variables to find n th element of Fibonacci sequence

5.26 Write a recursive function for binary search with function prototype int binsearch( int n, double

data[], double key ); and call this function in main to test binary search function

5.27 Write a recursive function to find gcd of two numbers, use this function to find their lcm

Page 153: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 153

Chapter 6

POINTERS AND DYNAMIC MEMORY ALLOCATION

LEARNING OBJECTIVES

After reading this chapter, the readers will be able to

understand the concept of pointer

know the operations on pointers.

learn the passing of pointers to functions

learn handling one-dimensional and two-dimensional numerical arrays and string manipulations

through pointers.

learn the `concept of dynamic memory allocation and usage of DMA functions.

6.1 INTRODUCTION Pointer is a variable that refers to the location of another item such as a variable or array. Pointers have

number of applications, for example pointer can be used to back and forth between a function and its

point of reference. Using pointers we can pass multiple values through arguments and also return multiple

values. Arrays and pointers resemble in their operations to access or process elements. Multidimensional arrays can be represented and processed through pointers. This feature enables us to represent

multidimensional arrays as lower-dimensional array of pointers. The above feature helps in representing a

string or a group of strings. Pointers can be used for implementation of DMA which reduce the wastage of memory.

Background

All variables in a program reside in memory.

The statements

float x;

x = 10.5; Requests the compiler to reserve 4 bytes of memory (machine dependent) for the floating-point variable

x, then stores value 10.5 in it.

`Sometimes we want to know where a variable resides in memory. The address (location in memory) of

any variable is obtained by placing the operator „&‟ before its name.

Therefore &x is the address of x.

6.2 WHAT IS A POINTER?

Definition:Pointer is a variable that store the address of another variable.

10.5

x

1562

Name of the location

Value at location

Address of location

Page 154: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 154

Relationship between variables and pointers

If x is a variable and ptr_variable is a pointer variable then

ptr_variable=&x ( & is a unary address operator)

6.3 DECLARATION OF POINTER VARIABLES

Example 6.1:

Declaration Interpretation Memory

occupied

int *iptr iptr is a pointer variable holding address of an integer. Variable 2bytes

float *fptr fptr is a pointer variable holding address of a float variable 2bytes

char *cptr cptr is a pointer variable holding address of a character variable 2bytes

Address of a variable of any data type is unsigned integral value. Hence each pointer variable occupies

2bytes for 16 bit processor or 4 bytes for 32 bit processor.

Address operator( &):The address operator & is used to get the address of the memory location allotted

to a variable.

Example 6.2:

ptr=&x ; Here ptr is a pointer variable holding the address of the variable x.

& is a unary operator that operates on variables and the associatively is from Right to Left and is of same

precedence group as other unary operators -,++, --, sizeof etc.. This group has higher precedence over the

other groups containing arithmetical operators.

& operator must act upon the operand that is associated with unique address, such as ordinary variables

or single array elements.

&150, &(x+y) is not allowed.

Syntax: data_type *variable name;

ptr_variable

Address of x Value of x

Variable _x

referring/pointing

Page 155: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 155

=>10.23

IndirectiIndirection operator/Value at operator: *

Ex. ptr=&x;

*ptr;

In the above example ptr is a pointer variable storing the address of the variable x. * with ptr is called as

indirection operator used to give the value at the address ptr holds.

* is unary operator operating from Right to Left and is of same precedence group as other unary operators -,++, --, sizeof etc.. This group has higher precedence over the other groups containing arithmetical

operators.

*operator must act upon the operand that is a pointer. It gives the value at that address or is said to refer to

the location so called as indirect reference operator.

Program 6.1:A program to illustrate pointer declaration

#include<stdio.h> #include<conio.h>

main()

{ int *ptr;

int sum;

sum=45;

ptr=&sum; printf (“\n The value represented by the variable sum is %d”, sum);

printf (“\n The value pointed by the pointer variable ptr is %d”, *ptr);

}

We will get the same result by assigning the value of sum to an ordinary (non pointer) variable. The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells the computer that we are

not interested in the address, but in the value stored in that memory location. Hence first and second

printf statements will result in the same output.

Program 6.2 Program to display the contents of the variable their address using pointer variable

#include <stdio.h>

main()

{ int num, *intptr;

float x, *floptr;

char ch, *cptr;

num=123; x=12.34;

ch=‟a‟;

2000 x

10.23 2000

3000 ptr

*2000

Page 156: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 156

intptr=&num;

cptr=&ch; floptr=&x;

printf(“Num %d stored at address %u\n”,*intptr,intptr);

printf(“Value %f stored at address %u\n”,*floptr,floptr); printf(“Character %c stored at address %u \n”,*cptr,cptr);

}

6.4 POINTER TO A POINTER In case of pointer to a pointer, the first pointer contains the address of the second pointer, which points to

the variable that contains the value desired.

Multiple indirections can be carried onto whatever extent desired, there may be few cases where more pointer to a pointer is needed.

A variable that is a pointer to a pointer must be declared as below. This is done by placing an additional *

in front of the variable name.

int **ptr; where ptr is a pointer which holds the address of another pointer.

Program 6.3 Program to declare pointer to pointer variable and to display their contents

#include<stdio.h>

void main(void)

{

int x,*ptr1,**ptr2;

x=10;

printf(“ x= %d”,x);

ptr1=&x;

printf(“x= %d”,*ptr1);

ptr2=&ptr1;

printf(“x= %d”,**ptr2);

}

Pointer Variable

Pointer Variable Pointer

All the three printf() statements display the same output x=10

Page 157: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 157

Program 6.4 Program to illustrate the contents of the variable their address using pointer

#include <stdio.h>

main()

{

int a, *aptr,**aaptr;

a=10;

aptr=&a ;

aaptr=&aptr;

printf(“\n\t %d is the value of a”, a);

printf(“\n\t %u is the value of aptr”, aptr);

printf(“\n\t %u is the value of aaptr”, aaptr);

printf(“\n\t %u is the value of &a”, &a);

printf(“\n\t %u is the value of &aptr”, &aptr);

printf(“\n\t %u is the value of &aaptr”, &aaptr);

printf(“\n\t %d is the value of *&a”, *&a);

printf(“\n\t %u is the value of *&aptr”, *&aptr);

printf(“\n\t %u is the value of *&aaptr”, *&aaptr);

printf(“\n\t %u is the value of **&aaptr”, **&aaptr);

printf(“\n\t %d is the value of ***&aaptr”, ***&aaptr);

printf(“\n\t %d is the value of *aptr”, *aptr);

printf(“\n\t %u is the value of **aaptr”, **aaptr);

}

}

2000

10

a

4000

2000

aptr=&a

8000

4000

aaptr=&aptr

Address

Value

Var_name

Output:

10 is the value of a

2000 is the value of aptr

4000is the value of aaptr

2000 is the value of &a

4000is the value of &aptr

8000 is the value of &aaptr

10 is the value of *&a

2000 is the value of *&aptr

4000is the value of *&aaptr

2000 is the value of **&aaptr

10 is the value of ***&aaptr

10 is the value of *aptr

10 is the value of **aaptr

Page 158: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 158

From the above program we can observe the following :

6.5 POINTER EXPRESSIONS &POINTER ARTHMETIC

Like any other variable, pointer variable can be used in arithmetic expressions.

For example if p1 and p2 are properly declared and initialized pointers, then the following statements are

valid.

y = *p1 * *p2;

sum = sum + *p1;

z = 5 - *p2/p1;

*p2 = *p2 + 10; x=3+5/ *p1;

Note that there must be a gap between / and *,otherwise /* is taken as the beginning of a comment.

Increment and decrement operations can be applied on pointers. The expressions ++p1,--p2 etc are

allowed.

`Program 6.5 Program to illustrate the pointer expressions

#include <stdio.h> main()

{

int ptr1,ptr2;

int a,b,x,y,z; a=30;b=6;

ptr1=&a; ptr2=&b;

x=*ptr1+ *ptr2 –6; y=6*- *ptr1/ *ptr2 +30;

printf(“\nAddress of a is %u”,ptr1);

printf(“\nAddress of b is %u”,ptr2); printf(“\na=%d, b=%d”,a,b);

printf(“\nx=%d,y=%d”,x,y);

ptr1=ptr1 + 70;

ptr2= ptr1;

printf(“\na=%d, b=%d”,a,b);

}

a==*&a==*aptr==**aaptr==***&aaptr

&a==aptr==*&aptr==**&aaptr

&aptr==aaptr==*&aaptr==*&aaptr

Page 159: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 159

Pointer Arithmetic

Following operations can be performed on pointers:

1. An integer constant or variable can be added to a pointer or subtracted from the pointer.

int x,*p1,i; p1=&x;

the expressions such as p1+1,p1+3,p1+i,

p1-1,p1-2,p1-i are allowed.

2. A pointer can be incremented or decremented.

The expressions such as ++p1,--p1,p1-- etc. are allowed.

3. Two pointers can be compared, if they are pointers to same datatype.

int *p1,*p2; the expressions such as p1==p2,p1!=p2,p1<p2 are allowed.

4. One pointer can be subtracted from another pointer if both point to the same array.

int a[10],*p1,*p2; p1=&a[0];

p2=&a[4];

k=p2-p1; is allowed

the value assigned to k is 4.

Following operations can‟t be applied on pointers:

1. Addition of two pointers 2. Subtraction of one pointer from another pointer when they do not point to the same array

3. Multiplication of two pointers

4. Division of one pointer by another pointer The expressions such as p1+p2,p1*p2,p1/p2,p1/3 are not allowed .

6.6 PASSING POINTERS TO A FUNCTION

Pointers (addresses) can be passed to a function through arguments. This mechanism of passing is called as pass by reference. In this mechanism any changes done to the parameters in function definition will

affect the actual parameters.

When addresses are passed through the actual parameters to the formal parameters, formal parameters

must be pointer type variables.

Program 6.6 Program to swap two integral values by passing pointers to the function swap

#include<stdio.h> #include<conio.h>

void swap(int *,int *);

void main()

Page 160: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 160

{

clrscr(); int a,b;

printf("\n\n\t\t Enter the int. values to be swapped :");

scanf("%d%d",&a,&b); printf("\n\n\t\t The values before swapping are %d & %d",a,b);

swap(&a,&b);

printf("\n\n\t\t The values after swapping are %d & %d".a,b);

} void swap(int *aptr,int *bptr)

{

temp=*aptr; *aptr=*bptr;

*bptr=temp;

return; }

Passing addresses from actual to formal parameters

Swapping of values

We know that a function can return single value only. However, multiple values can be returned through pointer parameters. The following program will illustrate this.

Program 6.7 Write a functionthat will find the area and parameter of a triangle and return them through

pointer parameters. Call this function in main() to find area and circumference of a given triangle

10

a

2000

20

b

4000

2000

aptr

6000

4000

bptr

7000

temp=*aptr

10

8000

*aptr=*bptr

a

a

10 20

2000

*bptr=temp

b

a

20 10

4000

Page 161: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 161

#include<stdio.h>

#include<conio.h> void find_ area_in(float a, float b, float c, float *pa, float *pc );

void main()

{ float a,b,c,area,circumference,*pa,*pc;

pa=&area;

pc=&circumference;

printf("\n\n\t\t Enter the three sides of the triangle :"); scanf("%f%f%f",&a,&b,&c);

find_area_in(a,b,c,pa,pc);

printf(" area of the triangle=%.2f\n”,*pa); printf(" circumference of the triangle=%.2f\n”,*pc);

}

void find_area_in(float a, float b, float c, float *pa, float *pc ) {

float s;

s=(a+b+c)/2.0;

*pa=sqrt(s*(s-a)*(s-b)*(s-c)); *pc=a+b+c;

return;

} In the above program addresses of area and circumference and the sides are passed. The calculated values

of area and circumference are stored in the memory locations allotted for the variables „area‟ and

„circumference‟ in the function main through the de referencing *pa and *pc.

6.7 POINTERS AND ARRAYS

Arrays are abstract data types which store a group of logically related items belonging to same data type

and are referred by a common name.

Array is identified by its name (common name) .Which is nothing but the base address of the array or

address of first element of the array. Array name is pointer to the array.

Let int a[5] be an array and the computer reserve 5 storage locations as follows:

10 20 30 40 50

a (array name)

2000 2002 2004 2002

2006 2002

2006 2002

&a[0]

&a[0]==a==Base address ==2000

Page 162: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 162

Array name „a‟ represent the base address i.e 2000. Thus both a and &a[0] represent the address of the

first element i.e 2000.

In general &a[i] is represented as a+i to get the i th elements address of the array.

similarly a[0] is 10 & *(a+1) also gives 10

a[1] is 20 & *(a+2) also gives 20

a[2] is 30 & *(a+3) also gives 30

a[3] is 40 & *(a+4) also gives 40

In general a[i] gives the value at i th location and is represented in pointers by *(a+i)

From the above we can say that the array name appearing as formal argument within the function

definition can be declared as pointer or as array of unspecified size. This will determine in which manner

the individual array elements are to be accessed within the function.

Program 6.8 Program to read and print the elements of one-dimensional array using functions and

pointers

#include<stdio.h> #include<conio.h>

void READARRAY(int n,int *aptr);

void PRINTARRAY(int n,int *aptr); void main(void)

{

int n,a[20];

clrscr(); printf("\n\n\t\t Enter the no. of elements to be read of the list : ");

scanf("%d",&n);

printf(“\n\n\t\t Enter n elements of the list :”); READARRAY(n,a);

printf(“\n\n\t\t Elements of array are : \n “);

Page 163: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 163

` PRINTARRAY(n,a);

} void READARRAY(int n,int *aptr)

{

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

scanf(“%d”,aptr+i);

}

void PRINTARRAY(int n,int *aptr) {

register int i;

for(i=0;i<n;i++) printf(“%5d”,*(aptr+i));

}

Array „a‟ is declared as int array of size 20. „n‟ is declared as int is used to accept the number of elements to be stored in „a‟, the value of which is between 1 and 20 and the variable is subscript for the array. In

the calling function „n‟ is passed by value and „a‟ which is the array name giving the base address of the

array is passed by reference. In the function definition „aptr‟ stores the address passed by „a‟. The

expression aptr+i gives the address of ith element of the array in the function READARRAY. The

following segment enables us to read the elements of the array

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

scanf(“%d”,aptr+i);

if aptr+i gives address of ith

location in the array then *(aptr+i) gives the value at ith location.

The following segment of PRINTARRAY displays the values stored in the array

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

printf(“%5d”,*(aptr+i));

Program 6.9 Program to SORT elements of one-dimensional array using functions and

pointers

#include<stdio.h>

#include<conio.h>

void READARRAY(int ,int *); void PRINTARRAY(int ,int *);

void SORTARRAY(int ,int *);

void main(void) {

int n,,a[20]; clrscr();

printf("\n\n\t\t Enter the no. of elements to be read to the array : ");

scanf("%d",&n); printf(“\n\n\t\t Enter elements of the array for sorting:”);

READARRAY(n,a);

SORTARRAY(n,a); printf(“\n\n\t\t Elements of array after sorting are : \n “);

PRINTARRAY(n,a);

}

here aptr+i is equivalent to &a[i]

here *(aptr+i) is equivalent to a[i]

Page 164: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 164

void SORTARRAY(int n, int *aptr)

{ register int i,p;

for(p=1;p<n;++p)

for(i=0;i<n-p;++i) if(*(aptr+i)> *(aptr+i+1))

{ temp=*(aptr+i);

*(aptr+i)= *(aptr+i+1);

*(aptr+i+1)=temp; }

return;

} void READARRAY(int n,int *aptr)

{

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

scanf(“%d”,aptr+i);

}

void PRINTARRAY(int n,int *aptr) {

register int i;

for(i=0;i<n;i++) printf(“%5d”,*(aptr+i));

return;

}

Array „a‟ is declared as int array of size 20. „n‟ is declared as int ,is used to accept the no. of elements to

be stored in „a‟, the value of which is between 1 and 20 and the variable is subscript for the array.

Reading of elements is defined through a function READARRAY, as explained in the previous example. In the calling functions „n‟ is passed by value and „a‟ which is the array name giving the base

address/address of first location of the array. In the function definition „aptr‟ stores the address passed by

„a‟. The expression *(aptr+i) gives the address of ith element of the array in the function SORTARRAY.

*(aptr+i) and *(aptr+i+1) are compared in the functionand performs swapping as already discussed. The

segment of code for displaying elements of the array is done through PRINTARRAY as discussed in the

previous example.

Program 6.10 Program to SEARCH (BINARY SEARCH) for an element in one-dimensionalarray using

functions and pointers

int BSEARCH(int ,int ,int ,int *); void main(void)

{

int n,i;int a[20],key,p; clrscr();

printf("\n\n\t\t Enter the no. of elements to perform BSEARCH : ");

scanf("%d",&n); printf("\n\n\t\t Enter the elements in sorted order : ");

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

{

scanf("%d",a+i); }

Page 165: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 165

printf("\n\t\t Enter the key element for searching:");

scanf("%d",&key); if((p=BSEARCH(0,n-1,key,a))==0)

printf("\n\n\t\t Element. is not in the array");

else printf("\n\n\t\tThe element %d is in the array at the position%d”,key,p);

}

int BSEARCH(int l,int u,int key,int *aptr) // recursive function for binary search

{ int m;

if(l<=u)

{ m=(l+u)/2;

if(key==*(aptr+m))

return (m+1); else if(key<*(aptr+m))

return(BSEARCH(l,m-1,key,aptr));

else

return(BSEARCH(m+1,u,key,aptr)); }

else

return(0); }

6.8 POINTERS AND TWO DIMENSIONAL / MULTIDIMENCTIONAL ARRAYS

Two dimensional array is a collection of one dimensional arrays.

If we can represent a two dimensional array as one dimensional, processing oftwo dimensional arrays

can easily be dealt with pointers. Consider the following two dimensional array initialization

int a[3][4]= {10,20,30,40,50,60,70};

Here a[0][0]=10,a[0][1]=20,a[0][2]=30,a[0][3]=40,a[1][0]=50,a[2][0]=60,… The memory organization will be as given below:

……………………………………………………………………………… so on

base address

2000 2002 2004 2002

a[0][0] a[0][1] a[0][2] 2002

0 th I Dim. array

2006 2008 2010 2002

a[1][0] a[1][1] a[1][2] 2002

1 th I Dim. array

base address

a+0

a+1

*(a+1)+0 *(a+1)+1 *(a+1)+2

*(a+1)+0 *(a+1)+1 *(a+1)+2

Page 166: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 166

So we can define a two dimensional array as a pointer to a group of contiguous one-dimensional arrays.

i.e. int a[3][4] is declared as int (*a)[4];

In general data-type(*ptr_variable)[size]; for two dimensional array

And data-type (*ptr_variable)[size][size]………[size]; can be generalized for higher-dimensional array;

The parenthesis that surrounds the array name and the preceding * is the pointer version of the

declaration. Without which the declaration would be considered as array of pointers rather than pointer to

a group of arrays.

If you have difficulty in memorizing what notation is for pointer to array and array of pointers, try this

:

int (*array)[4] : (, ) operators have higher priority because it is on the left of the [,]. So, it is a POINTER

to [4]. Again it is a POINTER. So, it means it is a pointer to array.

int *array[4] : [,] have higher priority than *, so, it is ARRAY of pointers. It is not pointer, it is ARRAY.

Example 6.11 Program to print base address of each one dimensional array & address of each location of

every one dimensional array

#include<stdio.h> #include<conio.h>

void rowaddress(int,int (*) []);

void coladdress(int,int,int (*) []);

void main(void) {

int a[4][6];

clrscr(); printf("\n\n\t\t Base address of each one dimensional array is : \n");

rowaddress(4,a); printf("\n\n\t\t Address of each element in two dimensional array is : \n");

coladdress(4,6,a);

}

void rowaddress(int r,int(*a)[6])

register int i,j;

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

printf("\t%u",a+i);

printf("\n");

} }

void coladdress(int r,int c,int(*a)[6])

{ register int i,j;

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

Page 167: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 167

{

for(j=0;j<c;j++) printf("\t%u",*(a+i)+j);

printf("\n\n");

}

}

The program uses concept of functions and pointer to an array.

Here „a[3][4]‟ is the array which is allocated with 3 one dimensional arrays where each one dimensional

array contains 4 elements. It will occupy 12*2 bytes overall. The program contain two functions; „rowaddress‟ which displays address of each one dimensional array as discussed in introduction;

‟address‟ gives address of each location of each element of the two dimensional array. „i‟ & „j‟are to

select rows and columns respectively.

(a+i) is pointing to base address of each one dimensional array. *(a+i)+j in the function „address‟ gives

the address of each element of one-dimensional array.

Program 6.12 Program to read and print the elements of a matrix using functions and pointers

#include<stdio.h> #include<conio.h>

void readmatrix(int,int,int (*) []);

void printmatrix(int,int,int (*) []);

void main(void) {

int a[4][6],r,c;

clrscr(); printf("\n\n\t\t Enter order of the matrix: ");

scanf("%d%d",&r,&c);

printf("\n\n\t\t Enter the elements of matrix row wise:\n");

readmatrix(r,c,a); printf("\n\n\t\t Elements of the matrix in natural form is \n");

printmatrix(r,c,a);

} void readmatrix(int r,int c,int(*aptr)[6])

{

register int i,j; for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{ scanf("%d",(*(aptr+i)+j));

}

} }

void printmatrix(int r,int c,int(*aptr)[6])

{ register int i,j;

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

{

Page 168: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 168

for(j=0;j<c;j++)

printf("%6d",*(*(aptr+i)+j)); printf("\n");

} }

Here „a[4][6]‟ is the array which is allocated with 4 one dimensional arrays where each one dimensional

array contains 6 elements. It occupies 24*2 bytes overall. The program contain two functions;

„readmatrix‟ which reads and stores the elements of matrix at a particular location; ‟printmatrix‟displayselements of the matrix in matrix form.

The program segment for accepting elements into the array a is

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

for(j=0;j<c;j++) scanf("%d",(*(aptr+i)+j));

observe that &a[i][j] used for reading elements in to the array is replaced by *(aptr+i)+j

The program segment for printing elements from the array a is

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

for(j=0;j<c;j++) printf("%d",*(*(aptr+i)+j));

observe that a[i][j] is replaced by *(*(aptr+i)+j)

Program 6.13 Program to multiply two matrices using functions and explicit pointers

#include<stdio.h>

#include<conio.h> void readmatrix(int,int,int (*) []);

void printmatrix(int,int,int (*) []);

void matmultiplication(int ,int,int,int(*)[],int (*)[6],int (*)[6]);

void main(void) {

int F[4][6],r1,c1,S[4][6],r2,c2,R[6][6]={0,0};

clrscr(); printf("\n\n\t\t Enter order of first matrix: ");

scanf("%d%d",&r1,&c1);

printf("\n\n\t\t Enter order of second matrix: "); scanf("%d%d",&r2,&c2);

if(c1==r2)

{

printf("\n\n\t\t Enter the elements of first matrix row wise:\n"); readmatrix(r1,c1,F);

printf("\n\n\t\t Enter the elements of second matrix row wise:\n:");

readmatrix(r2,c2,S); matmultiplication(r1,c1,c2,F,S,R);

printf("\n\n\t\t The product matrix is \n");

printmatrix(r1,c2,R);

} else

Page 169: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 169

printf("\n\n\t\t Matrix multiplication is not possible");

} void readmatrix(int r,int c,int(*aptr)[6])

{

register int i,j; for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{ scanf("%d",(*(aptr+i)+j));

}

} }

void printmatrix(int r,int c,int(*aptr)[6])

{ register int i,j;

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

{

for(j=0;j<c;j++) printf("%6d",*(*(aptr+i)+j));

printf("\n");

} }

void matmultiplication(int r1,int c1,int c2,int(*fptr)[6],int (*sptr)[6],int (*rptr)[6])

{ register int i,j,k;

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

{

for(j=0;j<c2;j++) {

*(*(rptr+i)+j)=0;

for(k=0;k<c1;k++) {

*(*(rptr+i)+j)=*(*(rptr+i)+j)+((*(*(fptr+i)+k)) * (*(*(sptr+k)+j)));

} }

}

} Here „a‟ is the array which is allocated with 4 one dimensional arrays where each one dimensional array

contains 6 elements. It will occupy 24*2 bytes overall. The program contain two functions;

‘readmatrixs’ which reads and stores the elements of matrix at a particular location; ‟printmatrix‟

displayselements of the matrix in matrix format. Processing of these functions is done as same as the

previous program. i, j ,k are register variables which whose values can be used for identifying different

elements of the array through pointers.

In the function „matmultiplication‟multiplies the matrices using the following code

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

for(j=0;j<c2;j++)

Page 170: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 170

{

for(k=0;k<c1;k++) {

*(*(rptr+i)+j)=0;

*(*(rptr+i)+j)=*(*(rptr+i)+j)+((*(*(fptr+i)+k)) * (*(*(sptr+k)+j))); }

}

}

In the above code *(*(rptr+i)+j)) points/refers to R[ ][ ]; resultant matrix.

*(*(fptr+i)+k) points/refers to the elements of F[][];First matrix

*(*(sptr+k)+j) points/refers to the elements of S[][];Second matrix

6.9 FUNCTIONS RETURNING POINTERS

In the previous sections we have seen that a function can return a single value by its name or return a single value by its name or return multiple values through pointer parameters. It is possible that a function

can return a pointer to the calling function.

Program 6.14 Write a function that receive pointers to two integers and return pointer to the smaller. Call this in main() to find the smallest of two integers.

#include<stdio.h> int *small(int *a,int *b)

void main()

{ int a,b;

int *p;

printf(“enter two integers:”);

scanf(“%d,%d”,&a,&b); p=small(&a,&b);

printf(“the smaller number is %d”,*p);

} int *small(int *a,int *a)

{

return((*a>*b)?a:b); }

6.10 DYNAMIC MEMORY ALLOCATION

Variables are named memory locations and they are to hold data to be manipulated by the programs.

Memory allocation for the variables used so far is static memory allocation. Staticmemory allocation is the phenomenon of allocation of memory during compilation time. The Allocated memory is released

at the end of program execution.

The declaration

int a;

allocates 2 bytes of memory to the variable a at compilation time where as the array declaration

int b[6];

Page 171: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 171

allocates 12 bytes of memory space at compilation time. In such a declaration there are few

shortcomings.

i) If we want to deal with more memory than size of the array during runtime of the

program, we cannot increase the size of array at runtime.

ii) Many a times all the memory allocated during compile time are not used; we cannot

decrease the wastage of memory at runtime.

To overcome the above problems we have the concept of Dynamic Memory Allocation.

As the name indicates, memory can be allocated dynamically whenever required.

Dynamic Memory Allocation is the phenomenon of allocationof memory during run time. Allocated

memory can be released during runtime.

Memory Management Functions with DMA

C library has the following built-in-functions to manage dynamic memory allocation.

1. malloc()

2. calloc() 3. realloc()

4. free()

The above functions are available in alloc.h, and stdlib.h. Either of the header files can be included.

1. malloc()

The general form of malloc is:

The function allocates a block of memory. On successful memory allocation the function returns a pointer

to the first byte of the block. Allocated space is initialized with garbage.

In the above syntax size of block is block size to be allocated. (cast type) is the cast expression which indicate the type of data that will be stored in the allocated block. ptr_variableis a pointer of the cast-

type which holds the address of the first byte of the block.

Example: ptr=(int *)malloc(10*sizeof(int));

Allocates 20 bytes of space and returns a pointer to the block which is assigned to the pointer ptr of type int. This is illustrated in the following figure.

The storage space allocated will have no name and hence must be accessed through the pointer only. If

the allocation fails, malloc() function returns a null pointer. Therefore check whether the allocation is

successful before using the pointer.

If sufficient memory is not available malloc() returns a null pointer.

Size of the block= (10 *2) bytes

2000

2000

ptr

ptr_variable=(cast type) malloc(size of block);

Page 172: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 172

Program 6.15 Program to arrange a list of numbers in ascending order

#include<stdio.h> #include<conio.h>

void main()

{ int *ptr , n,temp;

register int i;

clrscr();

printf(“Enter the number of values: “); scanf(“%d”,&n);

ptr=(int *)malloc(n*sizeof(int));

if(ptr==NULL) {

printf(“Memory not allocated”);

exit(0); }

printf(“Enter the numbers\n”);

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

scanf(“%d ” , ptr+i ) ; for(p=1;p<n;p++)

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

if( *(ptr+i) > *(ptr+i+1) ) {

temp= *(ptr+i);

*(ptr+i)=*(ptr+i+1); *(ptr+i+1)=temp;

}

printf(“The sorted list is : \n”);

for(i=0;i<n;i++) printf(“ %d “ ,*(ptr+i) );

getch();

} The program is to arrange a list of „n‟ numbers in ascending order. The method employed is bubble sort.

To store the „n‟ numbers in the memory a block of space is allocated using malloc() function .

For this , the statement

ptr=(int *)malloc(n*sizeof(int)); is used.

ptr, ptr+1, ptr+2,. . . are the pointers to first, second ,third ,… elements of the array. Thus the statement

scanf(“%d” ,ptr+i); is used to read the data from the keyboard and store in the allocated block.

The indirection operator „*‟ is used to access the data item at the address given by (ptr+i). Thus the

statement temp= *(ptr+i); would assign the value at the i

th position of the block to temp.

2. free( )

The free()is used to release(free) the block of memory which has already been allocated by malloc or

calloc functions This is done for reusability.

The general form of free() function is:

free (ptr_variable);

Page 173: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 173

ptr_variable=(cast type) calloc(no of blocks, size of block);

Example: free (ptr); Where ‘ptr’ is a pointer which points to the block which is to be released/de-allocated.

It is not the pointer that is being released but what it points to.

3. calloc( )

„calloc‟ is used to allocate multiple blocks of memory, all of which are of same size and returns a

pointer to the first byte of the first block. Initialize the allocated space with 0‟s .

The general form of calloc() function is

„calloc‟has two parameters first is the „no. of blocks to be allocated‟ and the second is the „size

ofblock‟.

ptr_variable is a pointer, which stores the address of the first byte of the first block allocated. If the

function is unable to allocate the requisite space, null pointer is returned and is assigned to the ptr

variable.

Program6.16 Program to read two matrices and find out their product with proper validation

#include<stdio.h> #include<conio.h>

#include<stdlib.h>

void main() {

int *pa,*pb,m,n,i,j,p,q ,*pc;

printf(“Enter the number of rows and cols of first matrix : \n”); scanf(“ %d%d “, &m,&n);

printf(“Enter the number of rows and cols of second matrix : \n”);

scanf(“ %d%d “, &p,&q);

if(n!=p) {

printf(“Multiplication of matrices is not possible”);

exit(0); }

pa=(int *)calloc(m , n*sizeof(int));

if(pa==NULL)

{

printf(“Memory not allocated”);

exit(0);

}

printf(“Enter the elements of the first matrix in row wise\n”);

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

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

Page 174: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 174

scanf(“%d ” , (pa+i*n)+j ) ;

printf(“Enter the elements of the second matrix in row wise\n”);

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

for(j=0;j<q;++j)

scanf(“%d ” , (pb+i*q)+j ) ;

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

for(j=0;j<q;j++)

{

*(pc+i*q+j)=0;

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

*(pc+i*q+j)+=(*(pa+i*n+k))*(*(pb+k*q+j));

}

printf(“Product matrix is:”);

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

for(j=0;j<q;++j)

printf( %5d” *(pc+i*q+j));

printf(“\n”); }

getch();

}

The problem is to store the elements of a matrix with m rows and n columns. So m blocks of memory

each of them to hold n integers is to be allocated.

In the statement ptr=(int *)calloc(m , n*sizeof(int));

calloc() function is used to allocate „m „ blocks of memory each of size sufficient to hold „n‟ integers . ptr+n*i+j is a pointer to i

th row j

th column element of the matrix(i=0,1,2 ,..m-1, j=0,1,2…n-1)

4. realloc()

malloc() and calloc() are functions used to dynamically allocate memory for storage. But in some

circumstances we need to alter the memory allocated by the above functions during runtime. This is

achieved with the help of realloc().

The general form of realloc() function is:

ptr_variable=(cast type) realloc(old_ptr, new size of block);

Here old_ptr is the pointer to the block which has been allocated and is to be altered (increased/

decreased).

Page 175: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 175

On successful reallocation the function returns a pointer to the first byte of the reallocated block. If the

functionis unable to allocate the additional size a NULL pointer is returned and the original block is freed.

„new size of block‟may be smaller or larger than the original block size. The location of old block and

new block may be same or different. If different data of old block will be copied to the new block. The function will guarantee that the old data is intact.

Program 6.17 Program to concatenate two strings using DMA

#include<stdio.h> #include<conio.h>

void main()

{ char *ptr1,*ptr2;

clrscr();

ptr1=(char *)malloc(sizeof("K.L.")); strcpy(ptr1,"K.L.");

printf("\n\n\t\t String 1 is %s",ptr1);

ptr2=(char *)malloc(sizeof("University"));

strcpy(ptr2,"University"); printf("\n\n\t\t String 2 is %s",ptr2);

ptr1=(char *)realloc(ptr1,sizeof("K.L.University"));

strcat(ptr1,ptr2); printf("\n\n\t\t Concatinated string is %s",ptr1);

getch();

} The program is to concatenate two strings .Each string have their own sizes and to concatenate them we

require to alter the size of the first string which is done with the help of realloc(). Here „ptr1‟ is pointer

to the first string “K.L.” of 5 bytes. „ptr2'is pointer to the second string “University”of 11 bytes.

Memory is allocated for the above strings using „malloc‟ function.

ptr1=(char *)realloc(ptr1,sizeof("K.L.University"));

Above statement allocates memory to be reallocated for the pointer „ptr1‟ which will set the pointer to 15

bytes.

strcat(ptr1,ptr2); statement appends the second string to the first string, resulting in “K.L.University”

SUMMARY

Pointer is a variable which stores address of another variable or address of block of memory.

Concept of pointers are extensively used with their operators & and *. Operators are used toexplain

different operations that are possible. Arithmetic‟s of pointers are used to relate pointers and

arrays. Accessing of elements of array are done through pointers. Strings can also be dealt with

pointers. Allocation of memory at run-time is done through Dynamic Memory Allocation. malloc, calloc are dealt as memory allocation functions where as realloc as memory reallocation to change

the memory and free to de-allocate memory that has been allocated.

Page 176: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 176

EXCERCISES

Multiple choice questions:

6.1. Which of the following statements is true after execution of following program segment? int a[5]={2,3},*p=a;

(*p)--;

(a) the value of a [0] will be 1 (b)the value of a[0] will be 2 (c) the value of a[1] will be 2 (d)none of these.

6.2. The fastest way to exchange two rows in a two- dimensional array is

a) exchange the address of each element in the two rows.

b) exchange the elements of two rows. c) store the addresses of the rows in an array of pointers and exchange the pointers.

d) none of these.

6.3. Which is the correct way to declare a pointer ? a ) int *ptr; b) *int ptr; c) int ptr*; d) int ptr x;

6.4. What will be the result of the following program?

main() {

int a=8,b=2,c,*p=&c;

c=(a=a+b,b=a/b,a=a*b,b=a-b);

printf(“\n %d”,++*p); }

a)45 b)46 c)50 d)51

6.5. What will be the value of x after execution of the following program? void main()

{

int x,*p;

p=&x; *p=2;

printf(“\n x=%d”,x);

} a)x=2 b)x=0 c)x=65504 d)none of the above .

6.6. What will be the value of variable a1 and a2 after execution?

main() {

int a1,a2,c=3,*p;

p=&c;

a1=3*(c+5); a2=3*(*p+5);

}

a)a1=24,a2=24 b)a1=12,a2=24 c)a1=12,a2=24 d)none of the above.

6.7. What will be the values of variables a and b after execution?

void main() {

int a,*b=&a,**c=&b;

a=5;

**c=15; *b=**c;

printf(“a=%d,b=%d”,a,*b);

Page 177: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 177

}

a) a=15,b=15 b)a=5,b=15 c) a=15,b=5 d)a=5,b=10 6.8. What is the output?

main()

{ int n[25];

n[0]=10;

n[5]=25;

printf(“\n %d”, *(n+0)+*(n+5)); }

a)compilation error b)40 c)15 d)35

6.9. What will be the output main()

{

int b[]={10,20,30,40,50} int *k;

k=&b[1]-1;

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

{ printf(“%d”,*k);

k++;

} }

a)10 20 30 40 50 b)10 30 50 c)20 40 d)compilation error.

6.10. What is the output? main()

{

int a[]={1,2,3,4},i;

for(i=0;i<=3,++i) *(a+i)=a[i]*i[a];

printf(“%d”,*(i+a));

} a)2 4 6 8 b)0 4 9 16 c)1 4 9 16 d)compilation error because i[a] is not allowed.

6.11. What is the output?

main()

{ int a[]={0,1,2,3};

int *ptr;

for(ptr=&a[0];ptr<=&a[3];ptr++) printf(“%d”,*ptr+5);

}

a)compilation error because ,the test expression in for is invalid. b) compilation error because ,the expression *ptr+5 is invalid.

C) 5 6 7 8 d) Garbage

6.12. Pointer variable may be assigned

a) An address value represented in hexadecimal b) An address value represented in octal

c) The address of another variable.

d) All the above. 6.13. Identify the invalid expression.

a)&35 b)&(x+y) c)&(x-y) d)all the above

Page 178: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 178

6.14. Identify the correct declaration statements.

a)float a=5;int *p=&a; b)float *p=&a;float a; c)int a=5,p=&a; d)all the above .

6.15. Identify the invalid expression given

int num=15,*p=&num; a)*(&num) b)**&num c)p++ d)*num

6.16. Identify the invalid expression for given

float x=2.14,*y=&x;

a) &y b)*(&x) c)**&y d)(*&)x 6.17.The operand of the address of operator is

a)a constant b)an expression c)a register variable d)a variable

6.18. How does the compiler differentiate address of operator from bitwise AND operator? a) by using the number of operands and position of operands

b) by using the declaration

c)both options a and b d)by using the value of operand. 6.19. The operand of indirection operator is

a)pointer variable b)pointer expression

c)both options a and b d)ordinary Variable

6.20. The operand of address operator may be a)an ordinary variable b)an array variable

c)a pointer variable d)any of the above

6.21.Assume 2bytes for int ,4bytes for float and 8bytes for double data types respectively, how many bytes are assigned to the following pointer variables?

int *ip;

float *fp; double*dp;

a)2bytes for ip,4bytes for fp and 8 bytes for dp

b)2bytes for all pointer variables ip,fp and dp.

c)one byte for ip,2bytes for fp and 4bytes for dp. d)2bytes for ip and 8bytes for each fp and dp

6.22. Identify the invalid expression for given syntax:

float fnum[10],*fptr=fnum a)fnum+=4 b)fptr[4] c)fnum=++ftr d)&fnum[4]

6.23.Identify the correct statement for given expression float x[10];

a)x is a pointer variable b)f is a fixed address and not a variable

c)x is an address that can be modified d)all the above 6.24. Given the declaration int x[5],the address of the element x[2] is obtained by

a)&x[2] b)x+2 c)both a and b d)*(x+2)

6.25.Given the declaration float x[5],the element[2] is accessed by a)*(&x[2]) b)x+2 c)*(x+2) d)both a and c

6.26.Given the declaration int x[5][5],the address of the element x[1][4] is obtained by

a)&x[1][4] b)x[1]+4 c)*(*(x+2)+4) d)all the above 6.27. Given the declaration int x[5][5],the element[2][4] is accessed by

a)x[2][4] b)*(x[2]+4 ) c)*(*(x+2)+4) d)all the above

6.28.Given

int *p1,**p2,***p3,v=25; P1=&v;p2=&p1;p3=&p2;

How to obtain the value of v using pointer variable

a) *p1 b) **p2 c)***p3 d) all the above 6.29. The declaration float * a [5]; is

a) An ordinary array b) a two dimensional array

Page 179: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 179

b) Pointer to an array d) an array of pointers

6.30. The declaration at (*p) [5]; is a) Function returning a pointer b) pointer to function

c) An array of pointers d) a pointer to an array

6.31. Array of pointers such as int *p [5]; is used for a) Fixed row size and varying column size

b) Fixed row size and fixed column size

c) Varying row size and fixed column size

d) Varying row size and varying column size 6.32. Pointer to array such as int (*a) [8]; is used for

a) Fixed row size and varying column size

b) Fixed row size and fixed column size c) Varying row size and fixed column size

d) Varying row size and varying column size

6.33. Identify the invalid expression for the given syntax: float x [10], *p=x;

a) x+4 b) p [4] c) &x [4] d) x= ++p;

6.34. Given float x [5] [5], (*y) [5]; the assignment of the array x to the pointer variable y may be

done as a) y= &x; b) *y=x; c) y [0] =x d) y=x;

6.35. In the declaration int *f ();

a) f is a pointer to a function b) f is a function returning a pointer c) f is an array of functions d) f is a pointer to an array

6.36. Identify the invalid assignment, for given int * p, x;

a) p = „10‟ ; b) p = 3142; c) p = & x; d) *p = 20; 6.37. The invalid pointer arithmetic is (are)

a) adding two pointers b) multiplying two pointers

c) dividing two pointers d) all the above

6.38. The invalid pointer arithmetic is (are) a) Shifting pointers using shift operators b) addition of float or double values to pointers

c) both options a and b d) incrementing pointers

6.39. When applied to a variable what does the Unary “&” operator field? a) The variable value b) The variable‟s address

c) The variable‟s format d) The variable‟s right value

6.40. Which of the following is true about pointers?

1. Pointers do not require memory storage 2. The size of a pointer depends on the type of the variable it points to

a) option 1 only b) option 2 only c) options 1 and 2 d) neither option 1 nor 2

6.41. If p1 and p2 are valid pointers in the same array, then which of the following statements is

valid?

a) p1 + 2 b) p1 – p2 c) p1 * p2 d) both a and b 6.42. What will be the output of the following code is executed

main ()

{

int a [5] = {1,2,3,4,5}; int *b= &a [2];

printf(“%d”, *(b-1));

} a) 2 b) 3 c) 4 d)

6.43. int x, y [10];

Page 180: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 180

From the above statement which of the following is not a valid initialization?

a) int *p = *y; b) int * p = &x; c) int *p = y + 2; d) int * p = (int *) ox1000;

6.44. What is the output when the following segment is executed?

int c [ ] = { 1,2,3,4,5,6 }; int j, *p = c;

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

printf(“%d”, *c);

a) 1 2 3 4 5 b) 1 1 1 1 1 c) 5 5 5 5 5 d) compilation error 6.45. What is the output?

int c [ ] = { 1,2,3,4,5}, *p =c;

int j; for(j=0;j<5;++j)

{

Printf(“%d”, *p); ++p;

}

a) 1 1 1 1 1 b) 1 2 3 4 5 c) Base address of the array is printed five times

d) compilation error 6.46. C program contains the following statement

float a= 0.001, *pa= &a;

If the value assigned to a stored at address 2432, then what is the value represented by f(*pa)?

a)0.001 b) 2432 c) data not sufficient d)Syntax error

6.47. What is the output Float a=0.001,b=0.003, *pa,*pb;

Pa=&a;pb=&b; *pa=4*a;

Printf(“%f”,(*pa-*pb)*3);

a) 0.004 b) 0.003 c)0.002 d) Syntax error 6.48. Consider the C program segment

{ int a[10],*p;

p=++a; } Suppose the code base address of array a is 1250 what value is assumed to p?

a) 1250 b) 1251 c)1252 d) syntax error.

6.49. Consider the C program segment int a[5]={0,1,2,3,4,},*p;

p=a+1;

Suppose the base address of array a is 1250 ,What is assigned to p? a) 1250 b)1251 c)1252 d) 1

6.50. What is the output of the following program segment?

int i,j=25; int *pi,*pj=&j;

*pj=j+5;

i=*pj+5;

printf(“%d”,i+j); a) 30 b)35 c) 60 d)65

6.51. What is the output?

int i,j=25; int *pi,*pj=&j;

*pj=j+5;

Page 181: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 181

i=*pj+5;

pi=pj; *pi=i+j;

printf(“%d”,(*pi+2));

a) 57 b)62 c)72 d) 67 6.52. What is the output?

int f1(char a,char b);

main()

{ char a=‟X‟,b=‟Y‟; int i;

i=f1(a,b);

printf(“a=%c,b=%c”,a,b); }

int f1(char c1,char c2);

{ c1=‟P‟;c2=‟Q‟; return((c1<c2)?c1:c2); }

a) a=P, b=Q b) a=X,b=Y c) a=Q,b=P d) a=Y,b=X;

6.53. What is the output?

void f(char*p a,char*p b); main()

{ char a=‟X‟,b=‟Y‟;

f(&a,&b); printf(“a=%c,b=%c”,a,b);

}

void f(char *pa,char*pb); { *pa=‟P‟;

*pb=‟Q‟;

return;

} a) a=X, b=Y b) a=P,b=Q c) a=80,b=81 d) a=88,b=89

6.54. What is the output?

main() { int a[5] = { 10,20,30,40,50};

int sum=0,i;

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

sum+=*(a+i); printf(“sum==%d\n”,sum);

}

a) sum= 150 b) sum=165 c) sum=65 d) sum=155 6.55. What is the output?

main()

{ int a[5] = { 10,20,30,40,50}; int sum=0,i;

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

sum+=*a+i;

printf(“sum==%d\n”,sum); }

a) sum= 150 b) sum=165 c) sum=65 d) sum=155

6.56. What is the output? void f(int *p);

main()

Page 182: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 182

{static int a[5] = { 10,20,30,40,50};

f(a+3); }

void f(int*p)

{ int i,sum=0;

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

sum+=*(p+i);

printf(“sum==%d\n”,sum); }

a) sum= 30 b) sum=70 c) sum=50 d) sum=90

6.57. What is the output?

int *f(int *p); main()

{ int a[5] = { 6,8,4,2,5};

int *p;

p=f(a); printf(“%d”,*p);

}

int *f(int *p) { int i,imax,max=0;

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

if(*(p+i)>max) { max=*(p+i);

imax=i;

}

return(p+imax); }

a) 5 b) 6 c)8 d)un predictable.

6.58. int *p(int *p); main()

{

int *p,a[5]={0,1,2,3,4};

p=f(a); }

int *f(int *p)

{ int i =2; return(p+i); }

a)Return the third element of the array a

b)Return the first element of the array a c)Return the pointer to the third element of array a

d)Return 0

6.59. A C program contains the following declaration

int a[6]={10,20,30,40,50,60}; What is the value of (*a+2)?

a) 32 b)12 c) 22 d) 23

6.60. A C program contains the following declaration static int a[2][3]={1,2,3,4,5,6};

What is the value of *(*(a+1)+1)?

Page 183: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 183

a) 4 b)5 c)2 d)3

6.61. A C program contains the following declaration static int a[2][3]={{1,2,3},{4,5,6}};

What is the value of *(*a+1)?

a) 1 b)2 c)4 d)5 6.62. A C program contains the following declaration

static int a[2][3]={{1,2,3},{4,5,6}};

What is the value of *(*(a+1))?

a) 2 b)4 c)5 d)3 6.63. Which of the following about the following declarations is true?

i) int *f() ii) int (*f)()

a) both are identical b) the first is correct declaration and second is wrong c) both are different ways of declaring pointer to a function

d) The first deceleration is a function returning a pointer to an integer and the second is

pointer to function retuning int. 6.64. What will be the output of the following

main()

{ int i;

char *p; i=OX23;

p=(char *)i;

p++; printf(“%x\n”,p); }

a) 25 b)24 c)26 d)28

6.65. What is the output? int a[]={1,2,9,8,6,3,5,12,8,9}

int *p=a+1,*q=a+6;

printf(“%d\n”,q-p);

a) 6 b)5 c) 10 d) 4 6.66. What is the output?

int a[]={1,2,5,6,9,10}

int *b=&a[4]; printf(“\n%d”,b[-3]);

a) 6 b)9 c)2 d)5

6.67. int y[4]={1,2,3,4}

int *p=y+2; printf(“%d\n”,p[1]);

What is printed when the above code is executed?

a)2 b)4 c)3 d)compilation error 6.68.main()

{

int a[4][2]; int b=0,x,I,j;

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

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

a[i][j]=b++; x=*(a+2)-1);

}

What is the value of x in the above example? a) 2 b)3 c)4 d)5

6.69. void f(int *a, int *b)

Page 184: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 184

{

int *t; t=a;

a=b;

b=t; }

main()

{

int a =2;b=3; f(&a,&b);

printf(“%d,%d”,a,b);

} What will be the output?

a) Error in run time b)compilation error c)2,3 d) 3,2

6.70. What is the result of the expression for the following declaration ? int a[]={1,2,3,4,5};

printf(“%d”,*a+2-*a+4);

a) 2 b) 5 c) 6 d) 1

6.71. p and q are pointers to same type of data items which of the following expressions is invalid?

a) p+2 b)q-p c)q-p+1 d) q+p

6.72. p and q are pointers to same type of data items which of the following expressions is valid? i) *(p+q) ii)*(q-p) iii)(*p)*(*q)

a) all b) (i) and (ii) c) (ii)and(iii) d) (ii) and (iii)

6.73. What is the output ? main()

{

int a[5],*p;

for(p=a;p<&a[5];p++) { *p=p-a;

printf(“%d”,*p);

} }

a) 0 1 2 3 4 b) 0 2 4 6 8 c) 1 2 3 4 5 d) compilation error

6.74. What is the output of the program?

main()

{ int b[]={5,9,10,13,14},*p;

p=b;

++*p; p+=2;

printf(“%d”,*p); }

a) 9 b)10 c) 7 d)13

6.75. What is the output of the program? main()

{ int b[]={5,9,10,13,14},*p;

p=b; printf(“%d”,++ *p); }

a)Depends on the base address of the array b b)base address of b+1

Page 185: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 185

c)6 d)9

6.76. What is the output of the program? int x[]={5,3,9,8};

main()

{ int *p,*q;

p=x;

q=x+2;

*p++; printf(“%d\n”,q-p);

}

a) 1 b)2 c) -2 d)base address of array x is required. 6.77. What is the output?

int a[]={5,10,15,20,25};

int *p,i; p=x;

i=*p++;

printf(“%d”,i);

a) 6 b) 10 c) 15 d) 11 6.78. Which of the following is false?

a) Adding two pointers is an invalid operation

b) An integer can be added to a pointer c) Pointer can not be multiplied

d) An array name can be used at the left side of an assignment.

6.79. If m and n have been declared as integers and p1 and p2 are pointers to integers , then which of the following is false?

a) p2=&*n; b) m=p2-p1; c) m=*p1+*p2++ d) *p1=&n;

6.80. A C program contains the following declaration :

int m,n,*p,**q; Which of the following is true?

a)p=&25 b)q=&p c)q=&(*p+5); d)p=&(m+n);

6.81. What is the output? main()

{

int a,b,*p1=&a,*p2=&b,x;

a=12, b= 4; x=4*-*p2/*p1+10;

printf(“x=%d\n”,x);

} a) x=9 b)x=10 c)14 d)12

6.82. What is the output?

main() {

int a=12,b=4,*p1=&a,*p2=&b;

int z;

*p2=*p2+3; *p1=*p2-5;;

z=*p1**p2-6;

printf(“z=%d\n”,z); }

a) z=6 b)z=42 c)z=12 d)z=8

Page 186: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Pointers & Dynamic Memory Allocation 186

6.83. What is the output?

main() {

int x=20;

change(&x); printf(“%d\n”,x);

}

change (int *p)

{ *p=*p+20;

} a)20 b)40 c) 30 d) 60

Comprehensive questions 6.1 Write a function that receives a floating point number and send back the pointers to integer and

fractional parts.

6.2 Write a function that receive the coefficients of a quadratic equation and pointers to the roots and return the roots. Call this in main() to find the roots of a given quadratic equation.

6.3 `Write a function that receive pointer to an array of integers and display its elements in reverse

order. Call this in main() to real and display a list of numbers in reverse order.

6.4 Write a function that receive pointer to an array and reverse its elements. 6.5 Write a menu driven program using pointers to add, subtract, multiply or divide two numbers.

Page 187: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 187

Chapter 7

DATA INPUT AND OUTPUT

LEARNING OBJECTIVES After reading this chapter, the readers will be able to

understand input and output concepts as they apply to C programs.

use different input and output functions available in the C library.

understand formatted input & output using prinf() & scanf() functions.

7.1 INTRODUCTION

One of the essential operations performed in a C language program is to provide input values to the

program and output the data produced by the program to a standard output device. We can assign values

to variable through assignment statements such as x = 5; a = 0; or initialize variables in the type declaration statement like

int a= 10; float b=25.4;

Another method is to use scanf() function which can be used to read data from the key board. For

outputting results we have used extensively the function printf() which sends results out to a terminal. There exists several functions in „C‟ language that can carry out input output operations. These functions

are collectively known as standard Input/Output Library.

7.2 SINGLE CHARACTER INPUT OUTPUT

The basic operation done in input/output is to read characters from the standard input device such as the

keyboard and to output or writing it to the output unit usually the screen.

7.2.1 getchar() function

The getchar() function can be used to read a character from the standard input device. The scanf()

function can also be used to achieve the purpose.. The getchar() function has the following form

variable _name = getchar();

where variable_name is any valid C identifier that has been declared as single character type. When this

statement is encountered, the compiler waits until a key is pressed and then assigns this character as a value to getchar(). Since getchar() is used on the right-hand side of an assignment statement, the character

value of getchar() is in turn assigned to the variable_name on the left-hand side.

For example: char ch;

ch=getchar();

will assign the character ‟H‟ to the single character variable ch when we press the key ‟H‟ on the keyboard. Since getchar() is a function, it requires a set of parentheses as shown in the above example. It

accepts no arguments and returns a single character constant.

Program 7.1 Program for reading & writing a character

# include < stdio.h >

Page 188: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 188

void main ( )

{ char ch;

printf (“Type one character:”) ;

ch = getchar () ; // gets a character from key board and stores it in variable ch. printf (” \nThe character you typed is = %c”, ch) ; // displays value of ch on the screen.

}

C supports many other similar functions which are given in the table below .These character functions are contained in header file ctype.h .Assume ch is declared as character type variable

Function Test Description

isalnum(ch) Is ch an alphanumeric character? Returns value 1 if true or 0 otherwise

isalpha(ch) Is ch an alphabetic character? Returns value 1 if true or 0 otherwise

isdigit(ch) Is ch a digit? Returns value 1 if true or 0 otherwise

islower(ch) Is ch a lowercase letter? Returns value 1 if true or 0 otherwise

isupper(ch) Is ch a uppercase letter? Returns value 1 if true or 0 otherwise

isprint(ch) Is ch a printable character? Returns value 1 if true or 0 otherwise

ispunc(ch) Is ch a punctuation mark? Returns value 1 if true or 0 otherwise

isspace(ch) Is ch a whitespace character? Returns value 1 if true or 0 otherwise

toupper(ch) If variable ch assigned with

lowercase alphabet converts it to uppercase alphabet

Converts to uppercase

tolower(ch) If variable ch assigned with

uppercase alphabet converts it to

lowercase alphabet

Converts to lowercase

Program7.2 Program to test the type of input character

#include,stdio.h>

#include<ctype.h>

Output:

Type one character

K

The character you typed is =K

Page 189: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 189

main()

{ char ch;

printf(“Press any key \n”);

ch=getchar(); if (isalpha(ch)>0)

printf(“The character is a letter.”);

else if (isdigit(ch)>0)

printf(“The character is a digit.”); else

printf(“The character is not

alphanumeric.”); }

7.2.2 putchar() function

The putchar() function which is analogus to getchar() function can be used for writing character data one

at a time to the output terminal. The general form is

putchar(variable /constant /expression);

The only one argument that is specified in the pair of parentheses should be either a single character

variable (or) a single character constant (or) an integer constant (or) any expression whose result should be of single character type. No other data type is allowed.

variable is any C identifier containing a character declared as a single character type. If variable is used

as an argument to putchar(), the character that is stored in that variable is displayed.

Constant is any single character constant (or) an integer constant. If a single character constant is used as an argument to the putchar(), it is directly displayed on the output terminal whereas if an integer

constant is used as an argument to putchar(), the character whose ASCII value is equivalent to the

specified integer constant will be displayed on the output terminal.

If an expression is used as an argument to the putchar() function, the result of that expression

which is of single character type will be displayed directly on the output terminal. If the expression whose

result is of integer type is used as an argument, its ASCII character will be displayed on the output terminal.

Example 7.1:

(a) char ch;

ch=‟y‟; would print character constant ‟y‟

putchar(ch);

(b) putchar(‟f‟); //prints single character constant ‟f‟ on the screen

(c) putchar(65); // prints A whose ASCII value is 65.

(d) putchar(65+35); // prints d whose ASCII value is 65+35(i.e.,100) (e) putchar(65.2); // cause an error as floating point type is not allowed.

Output:

Press any key

H The character is a letter.

Press any key

5 The character is a digit

Press any key

&

The character is not alphanumeric

Page 190: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 190

Program7.3 Program to read and display a single character

#include<stdio.h> main()

{

char in; printf(”please Enter one character”);

in = getchar ( ) ; // assign the keyboard input value to in.

putchar(in); // out put „in‟ value to screen.

}

Program 7.4:Program to read an alphabet from terminal and displaying it after case conversion.(lower

case to upper case & vice versa) .

#include<stdio.h> #include<ctype.h>

main()

{

char ch; printf(“Enter an alphabet \n”);

ch=getchar();

if (islower(ch)) putchar(toupper(ch);

else

putchar(tolower(ch));

}

7.3 STRING INPUT AND OUTPUT

7.3.1 gets() function

The gets() function reads string from standard input device. A string is an array or set of characters. The function gets( ) accepts the name of the string as a parameter, and fills the string with characters that are

input from the keyboard till newline character is encountered (that is till we press the enter key). At the

end function gets( ) appends a null character as must be done to any string and returns. The standard form of the gets function is

gets (str)

Here “str” is a string variable. For example,

char str[15]; puts(“enter any string:”);

gets(str);

If the string entered is “GREEN FIELDS” ,it is stored as

G R E E N F I E L D S \0

The character „\0‟ is appended automatically, indicating termination of string.

7.3.2 puts() function puts() is a function that copies a string to the standard output device, usually the display screen. When we

use puts(), we include the standard input/output header file (stdio.h). puts() also appends a newline

character to the end of the string that is printed. The format string can contain escape sequences. The standard form for the puts function is

Output:

please Enter one character

H

H

Output

Enter an alphabet

a

A

Enter an alphabet

Q

q

Page 191: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 191

puts (str)

Where str is a string variable.

Example7.2: puts("This is printed with the puts( ) function!");

Example 7.3: puts("This prints on the first line. \nThis prints on the second line.");

puts("This prints on the third line.");

puts("If we used printf( ) instead of puts( ), all four lines would be on two lines!");

Output

This prints on the first line.

This prints on the second line. This prints on the third line.

If we used printf( ) instead of puts( ), all four lines would be on two lines!

Program 7.5 Program to read and display a string

#include<stdio.h>

main() { char s[80];

printf (“Type a string less than 80 characters”);

gets(s); printf(“\n the string typed is\n”);

puts(s);

}

7.4 FORMATTED INPUT

The formatted input refers to input data that has been arranged in a particular format. Input values are

generally taken by using the scanf() function. The scanf() function has the general form.

The control string contains format of the data being received. The ampersand symbol (&) before each variable name is the address operator that specifies variable name‟s address. The use of & is must in

scanf() function.

The control string also specifies the field format which includes format specifications. Each format

specification must begin with % sign followed by conversion character which indicates the type of

corresponding data item. and optional number specifying field. width.

The blanks, tabs and newlines will be real but are ignored. Multiple format specifiers can be contiguous, or they can be separated by white space characters. If whitespace characters are used to separate the

formats, then they will be read but are ignored.

Output

This is printed with the puts() function!

Output:

Type a string less than 80

characters the string typed is

K L UNIVERSITY

scanf(“control string”,&variable1,&variable2,….);

Page 192: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 192

7.4.1 Commonly used format specifications:

%c – read a single character

%d – read a decimal Integer

%e – read a floating point value in exponential form.

%f – read a floating point value

%i – read a decimal, hexadecimal or octal Integer

%h- read a short integer

%x – read a hexadecimal integer (Unsigned) using lower case a – f

%X –hexadecimal integer (Unsigned) using upper case A – F

%o – read an octal integer

%s – read a string

%u –unsigned decimal integer.

%[ character set]-read only the characters specified with in brackets when inputting string

%[^character set]- The characters specified after ^(circumflex) are not permitted in the input

string.

7.4.2 Input specifications for Integer

The general format for reading an integer number is :

%wd

Here

percent sign (%) denotes that a specifier for conversion follows

w is an integer number which specifies the width of the field of the number that is being read.

The data type character d indicates that the number should read is integer mode.

Example7.4:

scanf (“%3d %4d”, &sum1, &sum2);

If the input is

175 1342 sum1 sum2

175 is assigned to sum1 and 1342 to sum 2. sum1 sum2

If the input is 1342 175 .

1342 175

2 134

Page 193: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 193

The number 134 will be assigned to sum1 and 2 is assigned tosum2. Because of %3d first three digits of

1342 is taken and is assigned to sum1 and the remaining digit2 is assigned to the second variable sum2.

If floating point numbers are assigned then the decimal or fractional part is skipped by the computer and

scanf() skips reading further input.

Program 7.6 Program to read integer numbers using scanf()

#include<stdio.h>

main() {

int a,b,c,x,y,z;

printf (“\n Enter three integers\n”); scanf(“%3d %3d %3d”,&a,&b,&c);

printf(“ %d %d %d”,a,b,c);

}

Output: Suppose the input data items are entered as

12 35 45

Then the following assignments will result. a=12 , b=35, c=45.

If the data had been entered as

212 359 458 Then the assignment would be

a=212 b=359 c=458

Now suppose that the data had been entered as

304685923 Then the assignment would be

a=304 b= 685 c=923

Finally, suppose that the data had been entered as 2385 4372 10

The resulting assignment would be

a=238 b=5 c=437 The remaining digit 2 and the number 10 would be

ignored, unless they were read by a subsequent scanf() statement.

Assignment Suppression:

An input data item may be skipped without assigning it to the designated variable or array by placing *

after the % sign. For example,

scanf(%d %*d %d”,&a,&b);

If the input is

123 456 789

123 assigned to a a b 456 skipped (because of *)

789 assigned to b

123 789

Page 194: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 194

Program7.7 Program to read integer numbers

#include<stdio.h> main()

{

int a,b,c; printf (“\n Enter three integers\n”);

scanf(“%d %*d %d”,&a,&b,&c);

printf(“ %d %d %d”,a,b,c);

}

In the above example, as the second format contains the input suppression character „*‟, the second input

item 23 is not assigned to any variable. Hence, 12 and 45 are assigned to a and b and c holds garbage value.

7.4.3 Input specifications for floating point constants

Field specifications are not to be used while representing a real number. Therefore real numbers are

specified in a straight forward manner using %f or %e specifier. The general format of specifying a real

number input is

scanf (“%f ”, &variable);

or

scanf (“%e”, &variable); For example,

scanf (“%f %f % f”, &a, &b, &c);

with the input data 321.76, 4.321, 678 a b c

The value 321.76 is assigned to a, 4.321 to b & 678 to C.

If the number input is a double data type then the format specifier should be % lf instead of %f.

Similarly if the number input is a long double data type then the format specifier should be % Lf

Program 7.8 Program to read real numbers using scanf()

#include<stdio.h>

main() {

float x,y;

double p,q; printf(“Enter values of x & y”);

scanf(“%f %e “,&x,&y);

printf(“\nx=%f\t y= %f\n”,x,y);

printf(“Enter values of p & q”); scanf(“%lf %lf “,&p,&q);

printf(“\np=%.12lf\t q= %e”,p,q);

}

Output:

Enter values of x & y 12.3456 17.5e-2

x=12.345600 y=0.175000 Enter values of p & q 4.142857142857 18.5678901234567890

P=4.142857142857 q= 1.856789e+01

Output: Enter three integers

12 23 45

12 45 3050

321.76 4.321 678

Page 195: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 195

7.4.4 Input specifications for single character and strings

In section 7.2.1 we have seen that a single character can be read from the terminal using getchar()

function .The same can be achieved using scanf() function also using „%c‟ format specifier or %1s

specifier The general format is %c or %1s. For example, char ch;

scanf(“%c”, &ch);

Suppose the input data item is V, then the character V is assigned to ch.

If the control string contains multiple character formats same care must be taken to skip whitespace characters in the control string. As the whitespace character is also interpreted as a data item, to skip such

whitespace characters and read the next nonwhite space character , the format %1s can be used.

Example 7.5: Consider the following program #include<stdio.h>

main( )

{ char ch1, ch2, ch3;

scanf(“%c%c%c”, &ch1, &ch2, &ch3);

printf(“%c %c %c \n”, ch1, ch2, ch3);

} If the input data consists of

p q r

then the following assignments would result: ch1=p , ch2 =<blank space> , ch3= q

We could have written the scanf function as

scanf(“%c %c %c”, &ch1, &ch2, &ch3); with white blank spaces seperaing the format specifier %c or we could have used original scanf

statement with the input data as consecutive characters without blanks; i.e., pqr.

A scanf() function with %wc or %ws can be used to input strings containing more than one character. The general format is

Where c and s represents character and string respectively and w represents the field width.

scanf () function supports the following conversion specifications for strings.

%[character set] and %[^character set] :

%[character set] specification means that only the characters specified with in brackets are permissible in the input string. If the input string contains any other character, the string will be

terminated at the first occurrence of such a character.

%[^character set] specification does exactly the reverse.. i.e. The characters specified after ^(circumflex) are not permitted in the input string .The reading of string will be terminated when one of

these characters is encountered.

The address operator need not be specified while we input strings.

The specification %s terminates reading at the encounter of a white space character.

For example Char str[25]

scanf(“%4c”, str);

Reads characters from keyboard until the user enters a white space character. . Only first four characters

of the string will be assigned to the string variable str. 1. If the user input is

“abcd ef” ,the string variable str holds ”abcd”

2. scanf(“%s”,str)

% wc or %ws

Page 196: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 196

Read characters form keyboard and the specification %s terminates reading at the encounter of a

white space. If the user input is “abc def” ,the string variable str holds “abc”

3. scanf(“%[a-z]”,str);

Read characters form keyboard and terminates reading at the encounter of non alphabet. If the user input is “abc123” , the string variable str holds “abc”

4. scanf(“%[^z]”,str);

Read characters form keyboard and terminates reading at the encounter of character „z‟.

If the user input is “abc123 z” , the string variable str holds “abc123”. Program 7.8 Program to read strings from keyboard

main()

{ char name1[15], name2[15], name3[15];

printf(“Enter name1:\n”);

scanf(“%15c”,name1); printf(“Enter name2:\n”);

scanf(“%s”,name2);

printf(“\n %15s”,name2);

printf(“Enter name3:\n”); scanf(“%15s”,name3);

printf(“\n %15s”,name3);

} In the above example;

string name1= K L UNIVERSITY”

The specification %s terminates reading at the encounter of a blank space ,so name 2=”GUNTUR”

only.

Second part of name2 will be automatically assigned to name3.Hence name3wiill be printed as

DIST Program 7.9 Program to illustrate %[ character set ] specification

main()

{ char address[80];

printf(“Enter address \n”); scanf(“%[a-z]”,address);

printf(“%s\n\n “,address);

} The reading of the string is terminated when blank space is encountered. Hence the string will be

read as Vijayawada only.

Program 7.10 Program to illustrate %[ ^character set ] specification main()

{

char address[80];

printf(“Enter address \n”); scanf(“%[^\n]”,address);

printf(“%-80s\n\n “,address);

}

Output:

Enter name1 K L UNIVERSITY

K L UNIVERSITY

Enter name2

GUNTUR DIST GUNTUR

Enter name3

DIST

Output: Enter address

Vijayawada 520001

Vijayawada

Output:

Enter address Vijayawada 520001

Vijayawada 520001

In the above example when newline(\n) is entered, reading will be terminated. Hence string

variable address will be “Vijayawada 520001”

Page 197: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 197

7.4.5 Reading Mixed data Types

scanf() function can be used to input a data line containing mixed mode data. Care should be taken to ensure that input data items match the control specifications in order and type

For example:

scanf(“%d%c % f%s”,&count,&code,&ratio,name); If the input is

35 x 42.76 ABC

the character after 35 is space,so it is taken as value of character variable code and the character x is not

assigned to any of the variable. To avoid this mistake one way is giving input without space between 35 and x i.e the input is

35x 42.76 ABC

Another way is skip the space by leaving a space in control string of scanf() function. The function should be rewritten as

scanf(“%d %c % f %s”,&count,&code,&ratio,name);

7.5 FORMATTED OUTPUT General format of printf( ) is as follows :

printf(“control string”,exp1,exp2,exp3,……);

The control string contains format of the data to be displayed and exp1,exp2,exp3…are output

expressions.

Control string consists of three items

1. Characters that will be printed on screen as they appear.

2. Format specifications that defines output format for display of each item.

3. Escape sequence characters such as \n, \t etc. Control string indicates how many variables follow and what their type is.

A simple format specification has the following form:

% flag w.p type-specifier

Where

Flag- used for print modifications - justification, padding, sign

w - is an integer specifies total number of columns for output value

p - is an integer specifies the number of digits to right of decimal part of

real number or no of characters to be printed from string Note: flag , w , p are optional

7.5.1 Output of Integer Numbers

Format specification for printing an integer is

%wd

where

w-specifies minimum field width for the output .However , if a number is greater than specified

width it will be printed in full

d- specifies that value to be printed is an integer.

The number will be right justified

Negative numbers will be printed with – sign

Page 198: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 198

For example,

Format Output

printf(“%d”,9876);

printf(“%6d”,9876);

printf(“%2d”,9876);

printf(“%-6d”,9876);

printf(“%06d”,9876);

placing - sign after % causes the output left justified with in the field. Remaining field will be

blank

placing 0 before the filed width specifier causes leading blanks padded with zeros.

%2hd - output is short integer with 2 print positions

%4d - output is integer with 4 print positions

%8ld - output is long integer with 8 print positions(not 81)

7.5.2 Output of floating point constants

The output of floating point constants may be displayed in decimal notation using the following format specification:

% w.p f

w indicates minimum number of positions that are to be used for the display of the value

p indicates number of digits to be displayed after decimal point (precision).Default precision is 6

decimal columns

The number will be right justified in the field of w columns

Negative numbers will be printed with – sign

The output of floating point constants may also be displayed in exponential notation using the following format specification:

Let x=98.7654

Format output

printf(“%7.4f”,x)

printf(“%7.2f”,x)

printf(“%-7.2f”,x)

printf(“%f”,x)

printf(“%10.2e”,x)

printf(“%-10.2e”,x)

printf(“%11.4e”,-x)

9 8 7 6

9 8 7 6

9 8 7 6

9 8 7 6

0 0 9 8 7 6

% w.p e

9 8 . 7 6 5 4

9 8 . 7 7

9 8 . 7 7

9 8 . 7 6 5 4 0 0

9 . 8 8 e + 0 1

9 . 8 8 e + 0 1

- 9 . 8 7 6 5 e + 0 1

Page 199: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 199

7.5.3 Printing of single Character

A single character can be displayed in a desired position using following format specification

The character will be displayed right justified in the filed of w columns

We can make display left justified by placing - sign before the field width w

Default value of w is one

Example 7.6 :

main()

{ char ch;

printf(“Enter any character:\n”);

scanf(“%c”,&ch);

printf(“\n % c”,ch); printf(“\n % 5c”,ch);

}

7.5.4 Printing of single strings The format specification for outputting string is similar to that of real numbers. It is of the form

w specifies filed width for display

p instructs only first p characters of the string are to be displayed

The display is right justified

The following examples show the effect of a variety of specifications in printing a string “K L UNIVERSITY”

Specification Output

%s

%20s

%20.5s

%.5s

%-20.8s

%5s

7.5.5 Mixed Data Output:

We can mix data types in one printf() statement. printf ()uses its control string to decide how many

variables to be printed and what their type are. The format specifications should match variable in number

,order, type .For example printf(“%d %f % s %c”,a,b,c,d);

7.5.6 Commonly used printf() format codes %c – print a single character

%d – print a decimal Integer

%wc

Output:

Enter any character:

K

K K

%w.ps

K L U N I V E R S I T Y

K L U N I V E R E S I T Y

K L U

K L U

K L U N I V

K L U N I V E R S I T Y

Page 200: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 200

%e – print a floating point value in exponential form.

%f – print a floating point number

%g- print a floating point value using either e-type or f-type, conversion depending on

value. Trailing zeros and trailing decimal points will not be displayed

%i – print a decimal, hexadecimal or octal Integer

%h- print a short integer

%u - print an unsigned integer

%x – print a hexadecimal integer (unsigned) using lower case a – f

%X –hexadecimal integer (unsigned) using upper case A – F

%o – print an octal integer without leading zero

%s – print a string

The following letters may be used as prefixes for certain conversion characters‟

h for short integers

l for long integers or for double

L for long double

7.5.7 Output Format Flags

Flag Type Flag code Meaning

Justification

none Output is right-justified

- Output is left-justified

sign

None Positive Value: no sign

Negative Value: -

+ Positive Value: +

Negative Value: -

padding

None Space padding

0 Causes leading 0‟s to appear(Zero padding)

#(with 0 or

0x) Causes octal and Hexa decimal numbers to be

preceeded by 0 or 0x,respectively

#(with e,f,g) Causes a decimal point to be present in all

floating point numbers even for whole number.

Prevents truncation of trailing 0‟s in g-type

Page 201: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 201

Example 7.7:

#include<stdio.h>

main()

{ int a,b,c,d;

float x,y,z;

printf (“\n Enter three integers\n”);

scanf(“%d %d %d”,&a,&b,&c); printf (“\n Enter three floating numbers:\n”);

scanf(“%f %f %f”,&x,&y,&z);

printf(“ \n%5d\t %5d \t%5d”,a,b,c); printf(“ \n%05d\t %05d”,a,b,c);

printf(“ \n%-5.2f\t %-5.2f \t%-5.2f”,a,b,c);

}

Example 7.8:

#include<stdio.h>

main()

{ int a,b,;

printf (“\n Enter two integers\n”);

scanf(“%d %d”,&a,&b); printf(“ \n%5d\t %5d”,a,b);

printf(“ \n%+5d\t %+5d”,a,b);

printf(“ \n%05d\t %05d”,a,b); }

Example 7.9:

#include<stdio.h>

main() {

int a,b,c,d;

printf (“\n Enter two octal integers\n”); scanf(“%0 %0”,&a,&b);

printf (“\n Enter two hexadecimal integers\n”);

scanf(“%x %x”,&c,&d);

printf(“ \n%o\t %o”,a,b,); printf(“ \n%x\t %x”,c,d,);

printf(“ \n%#o\t %#o”,a,b,);

printf(“ \n%#x\t %#x”,c,d,); }

Output:

Enter three integers

12 23 45 Enter three floating numbers

23.456 89.1234

12 34 45 00012 00034 00045

23.46 89.12

Output: Enter two integers

12 -23

12 -23 +12 -23

00012 00-23

Output:

Enter two octal integers 12 45

Enter two hexadecimal integers

94 2d

12 45 94 2d

012 045

0x94 0x2d

Page 202: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 202

EXERCISES

Review Questions:

7.1.What will the values of each variable be after the input command:

data input: Tom 34678.2 AA4231

scanf("%s %3d %f %c %*c %1d %x",name,&m,&x,&ch,&i,&j);

name: m : x : ch : i : j :

7.2. What output does each of these produce?

a) putchar('a'); b)putchar('\007');

c) putchar('\n');

d) putchar('\t'); e) n = 32; putchar(n);

f) putchar('\"');

7.3. For the different values of n, what is the output?

printf("%x %c %o %d",n,n,n,n); a) n = 67 b) n = 20

c) n = 128 d) n = 255

7.4. What is wrong with each of the following statements? a) scanf("%d",i);

b) #include stdio.h

c) putchar('\n'); d) puts("\tHello");

e) printf("\nPhone Number: (%s) %s",phone_number);

f) getch(ch);

g) putch() = ch; h) printf("\nEnter your name:",name);

7.5. Which numbering system is not handled directly by the printf() conversion specifiers?

a) decimal b) binary c) octal d) hexadecimal

7.6. Which one of the following conversion specifiers cannot be used for a number represented in binary

form in the computer?

a) %b b) %d c) %o d) %x

Comprehensive questions

7.1. Write a small program that will prompt for the input of a value for each of the following types:

%c - Yes or No

%s - Your Name %f - Your Height

%ld - The Circumference of the Earth

%f - Your Bank Balance

%lf - The Distance from the Earth to the Moon Read the values with scanf() and then print those values out on the display using printf().

7.2. Write a program that will prompt for the input of a temperature in Fahrenheit and will display as

output both the Fahrenheit value and the temperature converted to Celsius. Use the formula Celsius Degrees = (Fahrenheit Degrees - 32) * 5/9

Page 203: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Data Input and Output 203

7.3. Write a program that uses scanf() and printf() statements to prompt for your first name, last name,

street, city, state and zip code. After input of the values, then print the values out with the following format:

Name:

Street: City: State:

Zip:

7.4. Write a program that converts and prints a user supplied measurement in inches into

a.foot(12 inches) b. yard (36 inches) c.centimeter (2.54/inch) d. meter (39.37 inches)

7.5. Write a program to accept three integers and to display them

%d format specifier

with column width 5

with sign (+ or - ) as prefix

with column width 5 and left justified

with column width 5 & Padding 0‟s

7.6. Write a program to accept octal & hexadecimal integers and to display them

Using %o ,%x format specifiers

with column width 5

padding 0 for octal & 0x for hexadecimal

with column width 5 and left justified

with column width 5 & Padding 0‟s

7.7. Let a=6.789654,b=1.3e+02,write a „C‟ program to display the values of a &b in the following format

Display a & b values in floating point notation with precision of 3digits

Display a & b values in exponential notation with left justified

For exercise 8 & 9 The variables count, price city declared as – int ,float, char [] data type

and have the values. Count=1275, Price=235.74, City=Guntur 7.8. Show the exact output that the following statements will produce.

a. printf("%d %f ",count,price);

b. printf("%2d \n%f ",count,price);

c. printf("%d %f ", price , count); d. printf("%10dxxxx%5.2f ", count price);

e. printf("%s", city);

f. printf("%-10d%-15s",count, city); 7.9. State what (if anything) is wrong with each of the following output statements.

a. printf(“%d 7.2%f,year ,amount);

b. printf(“%-s,%c”\n,city,code);

c. printf(“%f, %d, %s,price,city,code); d. printf(“%c%d%s\n”,amout,code,year);

Page 204: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 204

Chapter 8

STRINGS

LEARNING OBJECTIVES

After going this chapter the reader will be able to

Use different input/output functions for string

Learn the usage of important string manipulation functions available in the header file string.h

Write his own functions for string manipulation

Learn the storage and manipulation of multiple strings.

8.1. INTRODUCTION:

String is a sequence of characters treated as a single data item.

Any group of characters(except double quotes) enclosed between double quotation marks is a

string constant.

“Vijayawada” ,“green fields”,“1234” , “5” ,”A” are string constants

5 is integer constant and is assigned to an integer variable

„5‟ is character constant and is assigned to a character variable.

“5” is string constant and is assigned to a string variable

If the double quote is also a character of the string we may include it preceded by black slash sign.

“welcome\”” is a string constant

C does not support string data type . Strings in C are represented by arrays of characters.

A string is stored in an array of characters as shown below

The end of the string is marked with a special character , the null character „\0‟ whose ASCII value is

zero.

char city [10] = ”HYDERABAD”;

The above string is stored as

The name of the character array „city‟ is pointer to the beginning of the string. The compiler automatically append null character (\0) at the end of the string. The

ASCII value of the null character is zero.(null character and the null pointer are different . In the ASCII

character set , the null character is named as NUL)

Null string is represented as “” and it is stored as

8.2. DECLARING AND INITIALIZING STRINGS

A string variable is any valid C variable name and it is always declared as an array. Hence to declare a string variable we use character array. The general format is

H Y D E R A B A D \0

\0

Page 205: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 205

char str[size];

Where str is a string variable and the size determines the number of characters in the string. Consider the following array declarations

char city[10],name[20],address[25];

Where city, name and address are character arrays which can hold strings of length 9,19 and 24 characters

respectively

Initializing strings:

We can initialize a string the same way that we initialize any other variable by assigning a value to it when it is defined. In this case the value is a string. For example

char city[10] = “HYDERABAD”;

If we declare city as

char city[9] = “HYDERABAD”;

then the null character will not be appended automatically to the character array . because , city can hold

9 characters and the string HYDERABAD has already 9 characters filling the 9 spaces.

Since a string is stored in a character array , while initializing through type declaration, size of the array

can be omitted as shown below.

char city[ ] = “HYDERABAD”;

In this case compiler will create an array of 10 bytes and initialize it with HYDERABAD followed by

null character

A string may be initialized as an array of characters.

char city[ ] = {„H‟,‟Y‟,‟D‟,‟E‟,‟R‟,‟A‟,‟B‟,‟A‟,‟D‟,‟\0‟};

A character pointer may be initialized with a string.

char *city = “HYDERABAD”;

Since a string variable is a character array, one string variable cannot be assigned to another

string variable.

char str1[6 ] = “green”,str2[6];

str2 = str1;

The above assignment leads to compilation error.

When pointers are initialized with strings we can assign one string to another string.

char *str1=”green”,*str2;

str2=str1;

The above assignment is valid.

Page 206: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 206

A character array cannot be initialized with a string by an assignment statement.

char city[10];

city = “HYDERABAD”;

The above assignment is invalid.

8.3. READING STRINGS FROM KEYBOARD

There are different methods to read a string

Using %s control with scanf()

The familiar input function scanf ( ) can be used with %s conversion specification to read string of

characters.

Example 8.1:

char city[15];

scanf(“%s”,city);

If the input is

VIJAYAWADA

then it is stored in the memory as given below.

V I J A Y A W A D A \0 ? ? ? ?

The „\0‟ (null character) is appended automatically after the last character to designate the end of the

string.

Note: Thus the unused locations are filled with garbage

The problem with the scanf function is that it terminates its input on the occurrence of first white space .

Example8.2:

char city[20];

scanf(“%s”,city);

If the input is

GREEN FIELDS

Only first word GREEN is read and is stored in the memory as given below

G R E E N \0

Using gets() function:

gets() function is useful to read strings from the keyboard. The general syntax is

Page 207: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 207

gets(str);

str is any valid string variable name and it will read a string of characters until enter key is pressed(i.e until new line character is entered).

Example8.3:

char city[20];

gets(str);

If the input is

GREEN FIELDS

then the string GREEN FIELDS is stored in the memory as

G R E E N F I E L D S \0

The „\0‟ (null character) is appended automatically at the end of the string to designate the end of the string.

Using scan set:

The function scanf() also allows for the input of string through the scan set , which is a sequence of

characters enclosed in square brackets[] and proceeded by a % sign . The scan set causes the function scanf() to search for the characters in the input string that matches those in the scan set. Only those

matching characters are stored in the corresponding array. The scan set operation terminates once a

character not contained in the scan set is encountered.

Example 8.4:

char str[10];

scanf(“%[pqrst]”,str);

If the input is pqrsx

Then the string pqrs is stored in the memory as

p q r s \0

Using inverted scan set:

The inverted scan set can also be used for character input. The inverted scan set does the opposite of scan

set. This means that only characters not appearing with in the square brackets are stored inside the character array. An inverted scan set is identified by a caret ^ with in the square brackets and preceding

the character sets

Example 8.5:

char str[20];

Page 208: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 208

scanf(”%[^\n]”,str);

The string entered through key board until new line character is taken and is stored in the array str.

If the input string is GREEN FIELDS

Then it is stored in the memory as

G R E E N F I E L D S \0

Using getchar() function:

A string may also be read character by character using getchar() function.

Example8.6:

char str[50];

int i=0;

while((str[i]=getchar()) !=‟\n‟)

{

++i;

}

str[i] =‟\0‟;

Note that null character(„\0‟) must be appended explicitly in this case. We can also use any other character in place of „\n‟ and the string will be read until that character is entered.

8.4.WRITING STRINGS TO THE SCREEN:

Using %s control with printf():

We can use printf ( )function with %s conversion to print string. The string is taken from the memory

until the occurrence of null character and is displayed. For example,

char str[ 20];

printf(“%s”,str);

Unlike scanf() even if the string contains white space characters entire string is displayed

Example8.7:

char str[20]=”GREEN FIELDS”;

printf(“%s”,str);

would output

GREEN FIELDS

Note that the stored string has a white space characters.

Page 209: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 209

Using puts() function :

puts() function is useful to print/display string on the screen. The general syntax is

puts(str);

Where str is any valid string variable name.

Program 8.1 program to read and write string using gets and puts functions.

#include<stdio.h>

#include<conio.h>

void main()

{ char name[20];

clrscr();

printf(“enter string from keyboard\n”); gets(name);

printf(“the string is\n “);

puts(name);

getch(); }

The output for above program is

Enter string from keyboard Good morning

The string is

Good morning

Program 8.2 Program to copy one string into another string #include<stdio.h>

#include<conio.h>

void main() {

char source[20],destination[20];

int i=0;

clrscr(); printf(“enter any string from keyboard\n”);

gets(source);

while((source[i] = destination[i] ) !=‟\0‟) i++;

printf(“the destination string is \n”,);

puts(destination); getch();

}

The character of the string destination are copied into the string source one by one until null character is

copied. After the null character is copied, while loop condition becomes false and control is exited from the loop.

8.5. STRING MANIPULATION FUNCTIONS

C language supports several functions useful for string manipulation. Whenever these functions are used

the header file string.h must be included. Some of the functions are:

1. strlen(): This function returns length of a string, that is counts no of characters in the string

excluding null character. If the string is empty it returns zero. The general format of this function is

Page 210: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 210

n=strlen(str);

Where n is an integer variable which receives the length of the string str.

Program 8.3 Program to find length of string.

#include<stdio.h> #include<conio.h>

#include<string.h>

void main()

{ char str[20];

int n;

clrscr(); printf(“enter any string \n”);

scanf(“%s”,str);

n=strlen(str); printf(“the length of string %s is %d”,str,n);

getch();

}

The output for above program is

Enter any string

Welcome

The length of the string welcome is 7

2.strcat(): This function is useful to join two strings together. The general format of strcat() function is

strcat(str1,str2);

str1, str2 are two string variables. When strcat() function is executed str2 is appended to strg1 and str2

remains unchanged.

Program 8.4 Program to join two strings “hello” and “world”

#include<stdio.h> #include<conio.h>

#include<string.h>

void main()

{ char str1[20] =“hello”,str2[20] =”world”;

clrscr();

printf(“the two strings before concatenation\n”); printf(“the first string is %s”,str1);

printf(“\n second string is %s”,str2);

Page 211: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 211

strcat(str1,str2);

printf(“the two strings after concatenation\n”); printf(“\nthe first string is %s”,str1);

printf(“\n second string is %s”,str2);

getch(); }

3.strcmp(): This function is useful to compare to strings. If the two strings are similar then it returns 0 ,

otherwise , it returns the difference between the ASCII values of first pair of non-matching characters.

The general syntax is

strcmp(str1,str2);

str1 and str2 may be string variables or string constants.

The returned value is

Zero if the strings are identical.

Positive if the strings are not in alphabetical order.

Negative if the strings are in alphabetical order.

Program8.5. Program to check the given strings are same or not.

#include<stdio.h>

#include<conio.h> #include<string.h>

void main()

{ int n;

char str1[20],str2[20];

clrscr();

printf(“enter any two strings\n”); scanf(“%s%s”,str1,str2);

n=strcmp(str1,str2);

if (n==0) printf(“two strings are same”);

else

printf(“strings are not same”); getch();

}

4.strcpy(): This function is useful to copy one string into another string. The general syntax is

strcpy(str1,str2);

Page 212: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 212

The content of str2 will be copied into str1.

Program8.6: Program to copy one string into another string.

#include<stdio.h>

#include<conio.h> #include<string.h>

void main()

{

char str1[20],str2[20]; clrscr();

printf(“Enter the first string\n”);

gets(str1); printf(“Enter the second string\n”);

gets(str2);

printf(“strings before copying\n”) printf(“%s\t%s”,str1,str2);

strcpy(str1,str2);

printf(“two strings after copying\n”);

printf((“%s\t%s”,str1,str2); getch();

}

Program8.7 : Program to check the given string is palindrome.

#include<stdio.h>

#include<string.h> void main()

{

char str[100];

int i,n,j,flag=0; printf(“enter the string to be checked\n”);

gets(str);

n=strlen(str); for(i=0, j=n-1; i<j; ++i, --j)

{

if(str[i] != str[j]) {

flag=1;

break;

} }

if (flag ==1)

printf(“given string is not a palindrome”); else

print(“given string is palindrome”);

}

Using the function strlen() length of the string is obtained and is assigned to n. Initial values of i and j are 0 and n-1 respectively, represents the first and last positions of the string. If the given string is not

palindrome, a pair of corresponding characters from the beginning and end are unequal and the loop is

Page 213: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 213

terminated after 1 is assigned to flag, otherwise, the initial value of flag 0 is not changed.

The following are some other string functions which we commonly use in c programming language.

S.No Function name Description

1 strrev() reverses a string

2 strstr() locates a substring in a string

3 strchr() locates the first occurrence of given

character in a string

4 strlwr() converts a string into lower case

5 strupr() converts a string into upper case

1.strrev(): This function reverses the string. The general syntax is

strrev(string);

Example 8.8:

char str[10] = ”GREEN”;

strrev(str); printf(“the reverse string is %s\n”,str);

Output:

the reverse string is NEERG.

2.strstr(): This function is used to locate a sub string in a string. The general syntax is

strstr(str1,str2);

This function searches str1 to see whether str2 is contained in str1.If yes, then the function returns the position of the first occurrence of the sub string str2 otherwise, it returns a NULL pointer.

3.strchr() This function is used to locate the first occurrence of a character in a string. The general syntax is

Example 8.9:

strchr(“this is an example”,‟a‟);

4.strlwr(): This function is useful to convert upper case string into lower case. The general syntax is

strchr(str1,character);

Page 214: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 214

String is any valid string variable which holds upper case data.

5.strupr(): This function is useful to convert lower-case data into upper-case.The

general format for this function is

“str" is any valid string variable , which contains lower-case data.

8.6. ARRAY OF STRINGS:

A list of names can be treated as a table of strings and two dimensional character arrays can be used to

store the entire list.

The character array str[20][15] may be used to store a list of 20 names.

Since a two dimensional array is an array of one dimensional arrays, str[0],str[1],str[2] etc represent the pointers to first, second third etc rows of the two dimensional array str.Thus the following code can be

used to store the list of names in the two dimensional array.

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

gets(str[i]);

Similarly , the following code can be used to display the list of names.

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

puts(str[i]);

Program 8.9 Program to sort a list of names.

#include<stdio.h> #include<conio.h>

#include<string.h>

void main() {

char str[10][20],temp[20];

int n,p,i,j;

clrscr(); printf(“Enter the strings one by one ,at the end of the list type END:\n”);

i=0;

while(i) {

gets(str[i]);

if(strcmp(str[i],”END”)==0) break;

++i;

}

n=i; /* sorting process begins*/

for(p= 1; p < n;pi++)

{

strlwr(str);

strupr(str);

Page 215: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 215

for(j = 0; j <= n-p; j++)

{ if (strcmp(str[j],str[j+1]>0)

{

strcpy(temp,str[j]); strcpy(str[j],str[j+1]);

strcpy(str[j+1],temp);

}

} }

printf(“\n The sorted list of names is :\n”);

for(i=0; i<n; i++) printf(“%s\n”,str[i]);

getch();

}

This program allows the user to enter unspecified number of strings until the string END is entered. The

program will count the strings as they are entered, ignoring the last string END. Here str is a two-dimensional character array.str[0],str[1], str[2] etc are pointers to 0

th, 1

st, 2

nd etc rows of it, i.e they are

pointers to 1st, 2

nd, 3

rd etc strings entered through keyboard. strcmp( ) function used at two places: while

testing for a stopping condition, and in rearrange, to test the need for interchange of strings. The actual interchange of strings is done through strcpy( )function.

8.7.POINTER TO STRINGS

In section 8.1 we have seen that strings are one-dimensional arrays of type char and therefore they are

declared and initialized as follows.

char str[10]=”GREEN”;

The compiler automatically append null character at the end of the string.

The following examples specify that how the pointers are used in string manipulation functions.

Example 8.10: Function to find length of a string using pointers

int str_len(char *p) {

char *q=p;

while(*p != ‟\0‟) ++p;

return(p-q);

}

The local pointer variable q is initialized with the address of the first character of the string. Since a string is terminated by the null character, the while loop

while(*p!=‟\0‟)

++p;

is executed until the end of the string is reached . When the while loop is terminated, the pointer p holds

the address of the null character. Hence the expression (p-q) gives the length of the string.

Page 216: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 216

Example 8.11: Function to copy one string to another string.

void str_cpy(char *ptr1, char *ptr2) {

while((*ptr1 = *ptr2) !=‟\0‟)

{ ++ptr1;

++ptr2;

}

return; }

The content of the second string represented by pointer ptr2 is copied in to the string represented by ptr1

until the null character is copied.

Example 8.12: Function to concatenate one string at the end of another string.

void str_cat(char *ptr1, char *ptr2)

{

while(*ptr1 !=‟\0‟) ptr1++;

while((*ptr1 = *ptr2) != „\0‟)

{

++ptr1; ++ptr2;

}

return; }

When the loop while(*ptr1!=‟\0‟)

prt1++;

is executed, ptr1 points to the null character of the first string. When the second while loop is executed, the content of second string represented by the pointer ptr2 is appended to the first represented by ptr1

character by character until the null character is copied.

The pointer to charter is can be taken as a pointer to string

Example 8.13:

char *str[10]=”EXAMPLE”;

char *p=&str[0];

then „p‟ is a pointer to the string.

P

A character pointer may be initialized with a string constant

Char *str = “EXAMPLE”;

E X A M P L E \0

Page 217: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 217

The address of the constant is stored in the pointer variable str . The pointer str now points to the first

character of the string “EXAMPLE” as:

Where p represent the address 2000 of E and p+1 ,P+2,p+3, etc.. represent the addresses (2001,2002,2003

etc..) of the characters X,A,M etc.. We can also give values to the string pointer by assigning strings during runtime using scanf() with %s format or gets() function.

Example 8.14:

char *str;

scanf(“%s”,str); (or)

gets(str);

The contents of the string str can be printed using either printf() or puts() functions.

printf(“%s”,str); (or)

puts(str);

Here no need to use indirection operator * as str is a pointer

p+1

Page 218: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 218

A constant character string always represents a pointer to that string Hence the following statements are

valid.

char *ptr;

ptr = “ GREEN FIELDS”;

so the character string “GREEN FIELDS”; is assigned to the pointer to character str.

This type of assignment is not allowed to character array.

Example8.15:

char place[20];

place = “GREEN FIELDS”;

is not allowed.

Example 8.16: Function to compare two strings.

int str_cmp(char *ptr1, char *ptr2)

{

while(( *ptr1 == *ptr2) && (*ptr1 !=‟\0‟) && (*ptr2 != „\0‟)) {

++ptr1;

++ptr2;

} return(*ptr1-*ptr2);

}

The comparison of the strings is done until there is a mismatch or one of the strings terminated in to a null

character, whichever occurs first When the control exits from the loop the difference between the ASCII value of the first pair of non-matching characters is returned.

Example 8.17: Function to reverse a string.

void str_rev( char *sptr)

{

char *eptr = sptr,*temp; while( *eptr != „\0‟)

++eptr;

for(--eptr; sptr <eptr; ++sptr,--eptr) {

temp = *sptr;

*sptr=*eptr; *eptr=temp;

}

return;

} /*sptr is the pointer to first character and eptr is the pointer to the last character*/

When the loop

while(*eptr!=‟\0‟)

Page 219: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 219

++eptr;

is executed eptr points to the null character .When it is decremented in the initial expression of the for loop it points to the last character of the string.Initially first and last characters are interchanged and then

second and last but one characters are interchanged and so on . To access the next characters starting

pointer str is incremented by 1 and the end pointer eptr is decremented by 1 in each repetition.

Array of pointers to strings :

A list of strings can be stored in the memory in another way. For each string, a memory block is allocated

through malloc() function and the pointer to that block is stored in an array of pointers to strings . The

declaration

char *str[20];

would represent an array of pointers to strings.

The following program code can be used to allocate the memory block for each string and store the string

in that block

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

{

str[i]=(char * ) malloc(15*size of (char));

gets(str[i]);

}

The following program will illustrate the sorting a list of names using array of pointers.

Program 8.10 Program to arrange a list of names in alphabetical order using array of pointers

#include<stdio.h> #include<conio.h>

void main()

{ char *str[20],*temp;

int i,n;

printf(“Enter the number of names:”);

scanf(“%d”,&n); printf(“Enter the names:\n”);

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

{ str[i]=(char*)malloc(15*sizeof(char));

flushall();

gets(str[i]); }

for(p=1;p<n;++p)

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

if(strcmp(str[i],str[i+1]>0) {

temp=str[i];

str[i]=str[i+1];

Page 220: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 220

str[i+1]=temp;

} printf(“The list of names in alphabetical order :\n”);

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

puts(str[i]); getch();

}

Note that if the strings are not in alphabetical order the pointers to the strings are interchanged rather than

the strings. This would result in the saving of execution time.

SUMMARY

A single character is assigned to 0 character variable , that is stored in the memory allocated to

a character variable .

A string is a group of characters and is stored in a character array.

Although C does not have a string data type , it allows string constant

scanf() function with %s conversion, gets[] function, scan set inverted scan set, using getchar()

function repeatedly can be used to input strings

When stored in the memory the string will be terminated by the null character „\0‟ and is used to

identify the end of the string.

printf() function with %s conversion , puts() functions can be used for string output.

There are several library functions in the header file <string.h> for manipulations of strings

List of strings can be stored in a two dimensional character array.

EXERCISES

Review Questions:

8.1 Describe the limitations of getchar(), gets() and scanf() functions in reading string

8.2 Explain the feature of null character in the strings?

8.3 Can we use strings in switch statement?

8.4 How can we compare two strings?

8.5 _______ conversion specification is used in scanf() function to read a string.

8.6 _______ function does not require any conversion specification to read a string from the key board.

8.7 When reading a string with scanf() , terminating null character is automatically inserted(T/F).

8.8 When reading a string with scanf() using the conversion specification %s , stop reading when

white space character is encountered (T/F)

8.9 While concatenating two strings the function strcat() insert a space between them (T/F)

8.10 ______ string manipulation function is used to determine whether a character is present in a

string.

Multiple choice questions:

1. Which library function is used to append one string at the end of another string

Page 221: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 221

1) strcpy 2) strstr 3) strcat 4) strcmp

2. What is the output when the following code is executed ?

#include<stdio.h>

main()

{

char str[]= “VIJAYAWADA”;

int i=0;

while(str[i]!=‟\0‟)

{

if(i%2==0)

printf(“%c”,str[i]);++i;

}

}

a) 02468 b)VJYWD c)IAAAA d)13579

3) Which of the following is true ?

a) String must have at least one character

b) String is terminated in the memory by the character „\n‟

c) String is a group of characters enclosed between single quotation marks

d) A string is stored in a one dimensional character array.

4) Which of the following initialization is invalid ?

a) char str[10]=”HELLO” ; b) char str[5]=”HELLO” ;

c) char str[6]={„H‟,‟E‟,‟L‟,‟L‟,‟O‟,‟\0‟} d) char str[]=”HELLO”

5) Which of the following is invalid string.

a) “356” b) “3” c) “3\0” d) “HONR”BLE”

6) What is the output when the following code is executed ?

char str[][10]={“BLUE”,”RED”,”ORANGE”,”GREEN”,”YELLOW”}

puts(str[2]);

a) RED b) ORANGE c) puts(str[2]) is invalid d)Invalid initialization

7) Which of the following code is invalid ?

Page 222: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 222

a) char str[10],str2[10]=”HELLO”; b) char str[6],str2[10]=”HELLO”;

strcpy(str1,str2); strcpy(str1,str2);

c) char str[10],str2[10]=”HELLO”; d) char *str;

str1=str2; str=”HELLO”;

8) What will be the output of the following statement?

printf(“%d”,strcmp(“Rahul”,”Rajiv”));

a)2 b)0 c)-2 d)Given statement is not correct

9) Which of the following statements will correctly store the concatenation of the strings str1 and str2 in

the str3

a) strcpy(str3,strcpy(str1,str2)); b) strcpy(str1,str2,str3);

c) strcpy(str3,strcat(str1,str2)); d) strcpy(strcat(str1,str2),str3);

10) What will be the output of the following code ?

char str[10]=”GREEN”; int i=0;

while(str[i]!=‟\0‟)

{ putchar(str[i]+1);

++i;

}

a) HSFFO b)5 c)FQDDM d)Invalid code

11) What will be the output of the following code ?

char str[10]= ”GREEN”;

while(str[i]!=‟\0‟)

{

printf(“%d”,str[i]);

++i;

}

a)70,8,68,68,77 b)67,69,69,75,81

c)71,82,69,69,78 d)none of these

Comprehensive Questions:

8.1 What are the different ways in which a single character and a string can be accepted and displayed

8.2 Write a program to read two strings and compare them using the function strcmp() and print a

message that the first string is equal , lesser or grater than the second one

8.3 Develop a program to check given name is present in the given list or not. 8.4 Write a program to accept a list of strings and display the largest string.

Page 223: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Strings 223

8.5 Write a program to accept a string and a character and find out whether this character is present in

the string. 8.6 Write a program to find length of string including and excluding spaces.

8.7 Write a program to copy source string to destination string up to a specified length. Length is to

be entered through the keyboard. 8.8 Write a program to extract a substring of given length from a string starting from a given

position.

8.9 Write a program to delete all occurrence of vowels in a given text assume that the text length will

be of one line. 8.10 Write a program to encrypt the text “INDIA” the output should be ”KPFKC” („A‟ should be

replaced with „C‟, „B‟ with ‟D‟ and „C‟ with „E‟ and so on).

8.11 Write a program which will read a text and count all occurrences of a particular word. 8.12 Write a program which will read a string and rewrite it in alphabetical order. for

example the word HELLO should be written as OLLEH.

8.13 Write a program to enter a string containing combination of capital, small, symbols and numerical characters. Carry out separation of capitals, small, symbols and numerical by using

ASCII values from 48 to 122.

8.14 Write a program to display alphabets as given below .

az by cx dw ev fu gt hs ir jq kp lo mn nm ol pk qj ri sh tg uf ve wd xc yb za. 8.15 Given a string

char str[]=”123456789”;

write a program that displays the following:

8.16 Write a program to display the following pattern

8.17 Write a program to convert each character of a string into the next character and print the same.

8.18 Write a function that takes a string and number between 0 and 9 as parameters and display the string that many times and returns its length.

8.19 Write a program to read a sentence and count the number of times each of the vowels appears in it, count the consonants separately.

1 2 3 2 3 4 5 4 3 4 5 6 7 6 5 4 5 6 7 8 9 8 7 6 5

K K L K L U K L U B K L U B S K L U B K L U K L K

Page 224: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 224

STRUCTURES, UNIONS AND ENUMERATED DATA TYPES

LEARNING OBJECTIVES

After reading this chapter, the readers will be able to

understand the purpose of the user defined data types – Structures, Unions and Enumerated data

types.

declaration of structure data types and variables.

access, initialize and process the structure members and the entire structures.

use array of structures and nested structures.

use structures as function arguments and return values.

use pointers to access structures and their members.

learn about union data types.

learn the purpose of enumerated data types.

9.0 typedef

The typedef keyword allows the programmer to create a new data type name for an existing data type. No

new data type is created but an alternative name is given to any standard data type or derived data type.

The general form of the declaration statement using the keyword typedef is

typedef <existing data type><new data type>

We can redefine int to INTEGER with the statement shown below

typedef int INTEGER;

typedef statements can be placed anywhere in a C program as long as they precede to their first use in

the program.

The typedef identifier is traditionally coded in uppercase.

Example 9.0

typedef int MARKS;

typedef int ID_NUMBER;

typedef float HEIGHT; typedef char UPPER_CASE;

In the first two statements typedef used to give new data type name MARKS and ID_NUMBER respectively to the standard type int, while HEIGHT is the new name given to the data type float and

UPPER_CASE is the new name given to the data type char .

MARKS English, physics, chemistry; ID_NUMBER student, employee;

HEIGHT building, tower, hill;

9.1. INTRODUCTION:

We have seen that arrays can be used to represent logically related data items that belong to the same data

type using a single name. However, array cannot be used to represent a collection of logically related

items belonging to different data types using a single name. To tackle this suitably, C supports a user defined data type known as structure that can store related information of same data type or different data

types together under a single name. For example, it can be used to store the related items of different data

types : employee number, name, basic pay, da, hra, gross pay and net pay together under a single name. Some other examples of structure are:

Page 225: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 225

complex : real part, imaginary part

fraction : numerator, denominator

date : day, month, year

student : roll number, name, age, marks in three subjects

address : name, door number, street, locality, city, pin code

Each element in a structure is called a field. It has many of the characteristics of the variables that have been used in the programs so far. It has a type, and it exists in memory. It can be assigned values, which

in turn can be accessed for selection or manipulation. The primary difference between a field and variable

is field is part of a structure.

The difference between an array and a structure is that all elements in an array must be of the same type,

while the elements in a structure can be of the same or different types.

9.2 STRUCTURE TYPE DECLARATION

There are two ways to declare a structure : tagged structure and type – defined structures.

Tagged structure

A tagged structure can be used to define variables, parameters, and return types. The general syntax is

struct TAG {

data type field1;

data type field2;

…. … ….; data type fieldn;

};

A tagged structure begins with the key word struct followed by TAG. The TAG is the identifier for the structure, and it allows us to declare structure variables, function parameters and return type. Field1

,field2, … fieldn can be variables ,arrays, pointers or other structure variables. After the closing brace, if

semicolon is there no variables are declared.

Example 9.1:

struct student {

long int id_no;

char name[20]; int age;

float cgpa;

};

Type declaration with typedef

The more powerful way to declare a structure is to use a type definition typedef . The general syntax is

Page 226: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 226

typedef struct

{

data type field1;

data type field2;

…. … ….;

data type fieldn;

}TYPE;

An identification TYPE is required at the end of the block , The identifier is the type definition name.

Example 9.2:

typedef struct

{

long int id_no; char name[20];

int age;

float cgpa; }STUDENT;

9.3 Declaring structure variables

After a structure has been declared, we can declare variables using it. The structure variable declaration is

similar to the declaration of any other data type. The following examples will demonstrate the declaration of structure type and the variables that use it.

Example 9.3:

struct student

{

long int id_no; char name[20];

int age;

float cgpa; };

struct student first, second , third;

typedef struct

{

long int id_no;

char name[20];

int age;

float cgpa;

}STUDENT;

STUDENT first , second, third;

id_no name age cgpa

STUDENT

Structure

Page 227: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 227

Note that in the second form of variable declaration, the keyword struct is not required because

STUDENT is the name of the structure data type.

Remember that the fields of structure themselves are not variables. They do not occupy any memory until

they are associated with structure variables such as first, second, third. When the compiler encounters declaration statement, it allocates memory space for the structure variables.

The declaration of structure variables can be combined with the definition of tagged structure as

shown in the following example. Example 9.4:

struct student

{

long int id_no; char name[20];

int age;

float cgpa; }first, second, third;

If the variables are declared in the definition of tagged structure the use of tag is optional

Example9.5:

struct

{ long int id_no;

char name[20];

int age;

float cgpa; }first, second, third;

But the problem with this definition is without tag name we cannot use it for future declarations.

Initialization:

We can initialize structure. The rules for structure initialization are similar to the rules for array initialization. The initializers are enclosed in braces and separated by commas. They must match with

corresponding types in the structure definition.

Example 9.6:

typedef struct

{ long int id_no;

int age;

char gender; float cgpa;

}STUDENT;

STUDENT ex6={11000136,16,‟M‟,7.8};

In this example there is an initial value for each structure member.

11000136 16 M 7.8

age Id_no gender cgpa

Page 228: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 228

If the number of initializers is less than the number of fields, like in arrays, the structure members will be

assigned null values, zero for integers and floating point numbers, and null(„\0‟) for characters and strings.

Example 9.7:

STUDENT ex7= {11000136,16};

Since there are no initial values for gender and cgpa, they are initialized with null and zero respectively.

Individual members cannot be initialized in the structure definition .The following initialization is not

valid struct student

{

long int id_no=11000035;

char name[20]=”XXX”; int age=16;

float cgpa=7.2;

};

9.4 ACCESSING STRUCTURE MEMBERS

Any field of a structure cannot be accessed directly. It can be accessed through the structure variable by using the operator „.‟ Which is also known as „dot operator‟ or period operator. The general syntax is

<structure variable name>.<fieldname>

In example 9.3, the fields of the structure id_no, name, age and cgpa through the structure variable first can be accessed by

first.id_no first.name

first.age

first.cgpa

Structure fields can be used in expressions like ordinary variables or array elements.

We can read data into and write data for structure members just as we can for individual variables. The

value for the fields of the structure in example 9.3 can be read from the keyboard and placed in the

structure variable first using the following scanf() statement.

scanf(“%d%[^\n]%d%f”,&first.id_no,first.name,&first.age,&first.cgpa);

Note that the address operator at the beginning of the structure variable name.

The structure member operator „ .„ has highest priority along with the operators( ) and [ ], and the

associatively is left to right.

Increment and decrement operators can be applied to numeric type members

first.age ++;

++ first.age; are allowed.

In both cases value of the field age is incremented by 1.

Page 229: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 229

Program 9.1: program to read and display the data of a student consisting of id_number, name,age and

cgpa.

typedef struct

{ long int id_no;

char name[20];

int age; float cgpa;

}STUDENT;

#include<stdio.h> void main()

{

STUDENT first; printf(“Enter the Id number:”);

scanf(“%ld”,&first.id_no);

printf(“Enter the name :”) ;

gets(first.name); printf(“”Enter the age:”);

scanf(“%d”,&first.age);

printf(“Enter the CGPA:”); scanf(“%f”,&first.cgpa);

printf(“ID number=%ld\n”,first.id_no);

printf(“Name=%s\n”,first.name); printf(“Age=%d\n”,first.age);

printf(“CGPA=%.ef\n”,first.cgpa);

}

Operations on structures

Only one operation , assignment is allowed on the structure itself. That is, a structure can only be copied

to another structure of the same type using the assignment operator.

Example 9.8:

Consider the definition of the structure in program 9.7

STUDENT x={11000025,”xxx”,16,9.1};

y={11000047,”yyy”,16,9.3};

y=x; /* structure x is copied to the structure y*/

Before

cgpa

a

Id_no name age

11000471 YYY\0

16 9.3

y

cgpa

a

Id_no name age

11000025 XXX\0 16 9.1

x

Page 230: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 230

y=x

C does not permit any relational or logical operations on structures. The expressions such as

x==y, x!=y, x&&y

are not allowed.

Program 9.2: Define a structure COMPLEX whose fields are the real and imaginary parts of a complex number. Write a program to read two complex numbers through keyboard and find their sum.

#include<stdio.h> typedef struct

{

float real; float imaginary;

}COMPLEX;

void main()

{ COMPLEX z1,z2,z3;

printf(“Enter the real and imaginary part of first complex number:”);

scanf(“%f%f”,&z1.real,&z1.imaginary); prinf(Enter the real and imaginary parts of second complex number:”);

scanf(“%f%f”,&z2.real,&z2.imaginary);

z3.real=z1.real+z2.real;

z3.imaginary=z1.imaginary+ z2.imaginary; printf(“Sum of given complex numbers=(%.2f,%.2f)\n”,z3.real,z3.imaginary);

}

9.5 ARRAY OF STRUCTURES

We can create the array of structures like array of integers. For example, to store the data of a group of students, we can use an array of structures. By putting the data in an array,we can quickly and easily work

with the data.

Example 9.9

struct stinfo

{

int rno; float height;

float weight;

}; strut stinfo stary[10];

After

cgpa

char

nam

e[20

];

char

nam

e[20

];

char

nam

e[20

];

char

nam

e[20

];

a

Id_no name age

11000025 XXX\0 16 9.1

y

cgpa

a

Id_no name age

11000025 XXX\0 16 9.1

x

Page 231: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 231

stary is an array of structures of the type struct stinfo .To access the data for one student, we refer to the

array name with the subscript.

stary[0].rno, stary[1].rno, stary[2].rno etc will refer the roll numbers of first, second and third students.

stary[3].height refer the height of the 4th

student

stary[4].weight refer the weight of the 5th student

Program 9.3 Create a structure to store the following details:

Roll number ,name ,marks1,marks2,marks3 and total.

Write a program to read roll number, name and marks in three subjects of n students and find the total

marks of each student. Display all the above student details sorted by total marks.

typedef struct

{

int rno; char name[20];

float marks1,marks2,marks3;

float total; }STUDENT;

#include<stdio.h>

void main()

{ STUDENT stary[10],temp;

int i,n,p;

printf(“Enter the number of students:”); scanf(“%d”,&n);

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

{

printf(“Enter the roll number:”); scanf(“%d”,&stary[i].rno);

flushall();

printf(“Enter the name:”); gets(stary[i].name);

printf(“Enter the marks in 3 subjects:”);

scanf(“%f%f%f”,&star[i].marks1,&stary[i].marks2,&stary[i].marks3”); }

/* To find the total marks of each students */

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

stary[i].total=stary[i].marks1+stary[i].marks2+stary[i].marks3;

/*To sort the student details on total marks */

for(p=1;p<n;++p)

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

if(stary[i].total<stary[i+1].total)

Page 232: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 232

{

temp= stary[i];

stary[i]=stary[i+1];

stary[i+1]=temp;

}

printf(“ROLL NO \t \t NAME \t \t MARKS1 \t MARKS2 \t MARKS3 \t TOTAL \n\n”);

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

printf(“%d\t%s\t\t%6.2\t%6.2f\t%6.2f\t%6.2f\n”,stary[i].rno,stary[i].name,

stary[i].marks1,stary[i].marks2,stary[i].marks3,stray[i].total);

}

Note that when the total marks are not in order, the elements of the array, that is structures are

interchanged. During the interchange one structure is copied into another structure as shown in the following program segment

{ temp=stary[i];

stray[i]=stary[i+1];

stary[i+1]=temp;

}

Structures containing arrays

Structures can have one or more arrays as members. We have already used arrays of characters inside a

structure. Similarly we can use one-dimensional or multidimensional arrays of type int or float

Example 9.10:

struct strecord

{

int rno;

float sub[6]; float total;

}stary[10];

In the above structure definition sub[6] is a field of the structure strecord.

The elements of the array sub[6] can be accessed using appropriate subscripts.

stary[0].sub[0], stary[0].sub[1], stary[0].sub[1], stary[0].sub[2] would refer to the marks of first student in

first, second ,third subjects.

stary[4].sub[5] would refer the marks of 5th student in sixth subject.

Program 9.4: Create a structure to store the following details:

Id.Number;

marks in six subjects;

total marks.

Page 233: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 233

Write a program to read the Id.Number and marks in six subjects of a list of students, find the total marks

of each student, and display all the above student details in tabular form.

typedef struct

{ long int id_no;

float sub[6];

float total;

}STUDENT; #include<stdio.h>

void main()

{ STUDENT stary[10];

int i,n;

i=0; while(1)

{

printf(“Enter the Id.Number at the end enter 0:”);

scanf(“%ld”,&stary[i].id_no); if(stary[i].id_no ==0)

{

n=i; break;

}

printf(“Enter the marks in six subjects:”); for(j=0;j<6;++j)

scanf(“%f”,&stary[i].sub[j]);

++i;

} /* To find the total marks of each student */

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

{ stary[i].total=0;

for(j=0;j<6;++j)

stary[i].total=stary[i].total+stary[i].sub[j];

} printf(“ID-NUMBER \t SUB1 \t SUB2 \t SUB3 \t SUB4 \t SUB5 \t SUB6 \t TOTAL\n”);

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

{ printf(“%ld\t”,stary[i].id_no);

for(j=0;j<6;++j)

printf(“%6.2f \t”,stary[i].sub[j]); printf(“%6.2f\n”,stary[i].total);

}

}//end of main

Marks in the six subjects are stored in a one dimensional array sub[6] . Marks of the (i+1)th student in

(j+1)th

subject is referred by stary[i].sub[j]

The following loop is used to read the marks ith student and store in the array sub[6]

for(j=0;j<6;++j) scanf(“%f”,stary[i].sub[j]);

Page 234: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 234

9.6 NESTED STRUCTURES

Structure member can be another structure. When a structure includes another structure, it is a nested

structure. For example, we can have a structure called birth that stores the date and time of birth of a

baby. The DATE is a member structure that stores the day, month and year. The TIME is another member structure that stores the hour, minute and second . The structure design is shown below.

Although it is possible to declare a nested structure with one declaration it is not recommended. But it

will be more clear and easier if each structure is declared separately and then grouped in the higher level

structure

The nesting must be done from the lowest level to the most inclusive level.

The definition of the above design is given below

Example9.11:

typedef struct {

int day;

int month; int year;

}DATE;

typedef struct

{

int hour;

int min; int sec;

}TIME;

typedef struct {

DATE dob;

TIME tob;

}BIRTH; BIRTH baby;

There is no limit to the number of structures that can be nested, normally we do not go beyond three

Referencing nested structures

The complete set of references for the structure baby are given below:

Page 235: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 235

baby .dob

baby .dob.day baby .dob.year

baby .tob

baby .tob.hour baby .tob.min

baby .tob.sec

Nested structure Initialization

Initialization procedure for nested structure is same as the simple structure initialization. Each lower

level structure member values are enclosed in as set of braces. Definition and initialization for the

structure variable baby are shown below.

BIRTH baby={{05,06,2012},{15,30,20}};

First inner pair of braces contains values for day, month and year, and second inner pair of braces

contains the values for hour, minute and second.

Program 9.6: Program to read the roll number and date births of a list of students and display the output

sorted on date of birth.

typedef struct

{

int day;

int month; int year;

}DATE;

typedef struct {

int rno;

DATE dob;

}STUDENT; #include<stdio.h>

void main()

{ STUDENT x[10],temp;

int i,n,p;

i=0; while(1)

{

printf(“Enter the roll number, at the end enter 0:”);

scanf(“%d”,&x[i].rno); if(x[i].rno==0)

{

n=i; break;

}

printf(“Enter the date of birth in the format dd-mm-yy:\n”); scanf(“%d-%d-%d”,&x[i].dob.day,&x[i].dob.month,&x[i].dob.year);

}

Page 236: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 236

/* To sort the student records on date of birth*/

for(p=1;p<n;++p)

{

for(i=0;i<n-p;++i) if(x[i].dob.year<x[i+1].dob.year)

{

temp=x[i]; x[i]=x[i+1];

x[i+1]=temp;

}

else if(x[i].dob.year==x[i+1].dob.year) {

if(x[i].dob.month<x[i+1].dob.month)

{ temp=x[i];

x[i]=x[i+1];

x[i+1]=temp;

} else if(x[i].dob.month==x[i+1].dob.month)

{

if(x[i].dob.day<x[i+1].dob.day) {

temp=x[i];

x[i]=x[i+1]; x[i+1]=temp;

}

}

} }//end of outer for loop

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

printf(“%d\t\t%d-%d-%d\n”,x[i].rno,x[i].dob.day,x[i].dob.month,x[i].dob.year); }

After sorting the student records are arranged in the order of youngest to oldest.

9.7 STRUTURES AND FUNCTIONS

C supports the passing of structure members and structures to functions and return them. A function can

accesses the members of a structure in three ways:

1. Individual members of a structure can be passed through arguments in the function call and they

are treated as ordinary variables in the called function. 2. The second method is a copy of the whole structure can be passed, that is the structure can be

passed by value. Any changes to structure members within the function are not reflected in the

original structure. Therefore it is necessary to return the whole structure back to the calling function.

3. The third method is to pass the address of a structure or member and the function can accesses

the members through indirection operator.

The following program will demonstrate the passing of structure members to a function.

Page 237: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 237

Program 9.7 Program to find the modulus of a complex number.

typedef struct

{

float real; float imaginary;

}COMPLEX;

#include<stdio.h> #include<math.h>

float find_modulus(float x, float y);

void main()

{ COMPLEX z;

float modulus;

printf(“Enter the real and imaginary parts of the complex number:”); scanf(“%f%f”,&z.real,&z.imaginary);

modulus=find_modulus(z.real,z.imaginary);

printf(“Modulus of given complex number = %f\n”,modulus);

} float find_modulus(float x,float y)

{

return(sqrt(x*x+y*y)); }

In the above program the structure members z.real and z.imaginary are passed to the function

find_modulus through arguments. They are copied to the dummy arguments x and y.

The following program demonstrate the passing of structures by value and the function returning a

structure.

Program 9.8: Program to find the product of two given complex numbers, using a function which will

find the product typedef struct

{

float real; float imaginary;

}COMPLEX;

#include<stdio.h> void main()

{

COMPLEX z1,z2z3;

printf(“Enter the real and imaginary parts of the first complex number:”); scanf(“%f%f”,&z1.real,&z1.imaginary);

printf(“Enter the real and imaginary parts of the second complex number:”);

scanf(“%f%f”,&z2.real,&z2.imaginary); z3=product(z1,z2);

printf(“Product=(%.2f,%.2f)\n”,z3.real,z3.imaginary);

} COMPLEX product(COMPLEX z1,COMPLEX z2)

{

COMPLEX z3;

z3.real=z1.real*z2.real-z1.imaginary*z2.imaginary; z3.imaginay=z1.real*z2.imaginay+z1.imaginary*z2.real;

Page 238: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 238

return(z3);

} In the above program the structure variables z1 and z2 are passed to the function by value. Within the

function product, the product of the complex numbers is obtained and is stored in z3. The value of z3 is

returned to the called function.

Passing structures through pointers

Structure can be passed through pointers. When the structure is in dynamic memory, it is common to pass

structure through pointer. now let us rewrite Program9.8 by passing structures through pointers

Program 9.9: Passing structures through pointers.

#include<stdio.h> typedef struct

{ float real;

float imaginary; }COMPLEX;

void main()

{ COMPLEX z1,z2,z3;

printf(“Enter the real and imaginary parts of first complex number:”);

read_num(&z1);

printf(“Enter the real and imaginary parts of second complex number:”); read_num(&z2);

product(&z1,&z2,&z3);

print_num(&z3); }

void read_num(COMPLEX*pz)

{

scanf(“%f%f”,&pz real,&pz imaginary); return; }

void product(COMPLEX *pz1,COMPLEX *pz2,COMPLEX *pz3)

{

pz3 real=pz1 real*pz2 real-pz1 imaginary*pz2 imaginary;

pz3 imaginary=pz1 real*pz2 imaginary+pz2 imaginary*pz2 real; return; }

void print_num(COMPLEX *pz)

{

printf(“Product=(%f,%f)\n”,pz real,pz imaginary); return; }

The following points are to be noted in this program

1. The function read_num() is written to read the complex number. The pointers to the structure

variables z1and z2 are passed in the first and second calls of the function. 2. In the header of the function read_num() the dummy argument pz is a pointer to the structure.

3. Pointers to the structure variables z1,z2 andz3 are passed to the function product which will return

the pointer to the product of the two complex numbers z3.

Page 239: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 239

4. The function print_num() is written to display a complex number.

5. To accesses the members of the structure through the pointer the indirection operator( ) is used, which has the highest precedence along with . , ( ) and [ ] operators.

6. The expressions pz real and pz imaginary are used to access the values of the structure members.

7. In the expressions &pz real and &pz imaginary the operator ‟&‟ apply on the members real and

imaginary but not on the pointer pz.

Size of structure

The operator sizeof can be used to find the size of a defined structure data type . The expression

sizeof(struct ex)

will evaluate the number of bytes required to hold all the structure members.

If a is a variable of the type struct ex then the expression

sizeof(a)

would also give the same answer.

9.8 UNIONS

The union is a user defined data type that allows the memory to be shared by different types of data. The union follows same syntax as the structure .Except the keywords struct and union, the formats are the

same but there is a major difference in the storage. In structure, each member has its own storage

location, where as all the members of a union share a common memory location.

Even though union contain many members in the program only one member is available at a time. The general syntax of union declaration is

union TAG typedef union { {

data type member 1; data type member1;

data type member 2; data type member1; ……. …….

data type member n; data type member n;

}; }TAG;

A student in a section may be referred by roll number or id.number. Therefore depending on the available data only one of them may be stored in the memory at any time. Thus a union can be defined to

allocate a common memory location for them.

Example 9.12:

union student_id

{ int rno;

long int id_number;

}x;

Both rno and id_number start at the same memory address

student_id

rno/id_number

rno/id_number

Page 240: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 240

The rules for referencing a union are identical to those for structures. To reference individual fields

within the union we use the dot operator. When a union is being referenced through a pointer, the

arrow operator can be used. x.rno and x.id_number canbe used to refer the union members rno and id_number.

Union may be initialized only with a value of the same type as the first union member. Other members

can be initialized either assigning values or reading from the keyboard.

Example 9.13:

union student_id {

int rno;

long int id_number;

}; union student_id x={35};

printf(“rno=%d\n”,x.rno);

printf(“id_number=%ld\n”,x.id_number); The output of the above program segment is

rno=35

id_number=0 Example 9.14:

union ex

{ int a ;

float b;

}; union ex x={19.75};

is invalid declaration . Because the type of first member is int , but x is initialized with float value.

When a union is defined, enough space is allocated to store the largest data type member in the definition. In the above example the size of rno is 2 bytes and the size of id_number is 4 bytes. Therefore 4 bytes of

space is allocated regardless of what type of data is being stored.

Storage of 4 bytes

During the accessing of union members we should make sure that we can access the member whose

value is currently stored.

x.rno=50;

x.id_number=11000132;

printf(“%d”,x.rno); would produce erroneous output(which is machine dependent)

9.9 ENUMERATED TYPES

The enumerated type is a user defined data type based on the standard integer type. In an enumerated

type, each integer is given an identifier called an enumerated constant. We can thus use the enumerated constants as symbolic names, which make our programs more readable.

rno

2146 2147 2148 2149

id_number

Page 241: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 241

Like standard types have identifiers(int for integer),a set of values and a set of operations , enumerated

type also will have a name, set of values and a set of operations defined on them.

Declaring an enumerated type

enum typename{ identifier 1, identifier 2,…,identifier n};

Where enum is a keyword, typename is the name given to the enumerated type and identifier 1, identifier2, ... are a set of enumerated. constants enclosed in a pair of braces.

Enumeration identifiers are assigned integer values beginning with 0. That is , the identifier 1 is assigned 0, identifier 2 is assigned 1 and so on.

Example 9.15:

enum color {BLUE,GREEN,ORANGE,PURPLE,RED};

The enumerated type color has five possible values. The range of values BLUE representing the value 0,GREEN representing the value 1, ORANGE the value 2, PURPLE the value 3 and RED the value 4.

The automatic assignments can be overridden by assigning values explicitly to the enumeration

constant.

Example 9.16:

enum color{ BLUE=1,GREEN,ORANGE,PURPLE,RED };

Here the identifier BLUE is assigned the value 1. The remaining identifiers are assigned values that

increase successively by 1.

The explicit assignment can be made to any one of the identifier in the list

Example 9.17:

enum color{ BLUE,GREEN,ORANGE=3,PURPLE,RED };

Here the identifier ORANGE is assigned the value 3. The remaining identifiers are assigned values that

increase successively by 1 in the forward direction and decrease successively by 1 in the backward direction.

Declaring variables of enumerated type

We can declare variable of enumerated data type. The general syntax is

enum type name v1,v2,v3,…vn;

The enumerated variables can have one of the values identifier 1,identifier 2, … identifier n;

Example 9.18:

enum color{ BLUE,GREEN,ORANGE,PURPLE,RED };

enum color foreground, background;

9.9.1 Operations on enumerated type

We can store values in enumerated type variables and manipulate them.

Page 242: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 242

Assigning values to enumerated type.

Enumerated variables van be assigned values through assignment statement.

Foreground=GREEN;

Background=RED;

The value of one enumerated variable can be assigned to another enumerated variable.

foreground=background;

Comparing enumerated types

Enumerated types can be compared using the relational operators. Given two variables of enum type color, they can be compared for equal, lesser than, greater than, not equal to. We can also compare

them to enumeration identifiers as shown follow:

if (foreground==background)

….. if (foreground==ORANGE)

.....

Since enumerated types are derived from integer types they can be used in switch statement.

Example 9.19: enum day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,

SUNDAY};

enum day birthday; switch (birthday)

{

case MONDAY: printf(“The birthday is on MONDAY”);

break; case TUESDAY: printf(“The birthday is on TUESDAY”);

break;

---

}

Enumerated variable can be used as index of for loop.

for (birthday=MONDAY; birthday<=SUNDAY; ++birthday)

{

}

Input/output Operations:

Since enumerated types are derived data types they cannot be read and written using the formatted

input/output functions. An enumerated type must be read as an integer and written as an integer.

enum day holiday, birthday;

scanf(“%d%d”,&holiday,&birthday”);

printf(“%d\t%d”, holiday, birthday”);

Page 243: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 243

if the input is

1 2

The output is

1 2

Note that “SUNDAY” is a string, where as SUNDAY is an enumerated type identifier.

SUMMARY

Structure is used to pack a collection of logically related data items, possibly of different data types,

having a common name.

Each element of a structure is called a field or member.

One difference between array and structure is that all elements of the array must be of same data type

while the elements in a structure can be same or different data types.

Unlike arrays, structure data type must be defined first that will be used later for declaring structure

variables.

Structure members cannot be initialized in the structure data type definition

Structure variables can be initialized in the declaration. The rule for initialization is the same as that for

array initialization.

Structure members can be accessed using the dot(.) operator.

Structure members can also be accessed through structure pointer. For this the arrow ( ) operator is used.

Structure members can be used in expressions like ordinary variable names or array elements.

The only operator allowed on entire structure is assignment.

The individual members or the whole structure or the pointer to the structure can be passed to a

function through arguments and a function can return a structure.

An array of structures can be declared and structure members can be arrays.

One structure can be embedded in another structure .This is called nesting of structure

A union is a structure all of whose members share the same storage.

A union can store only one of its members at a time.

An enumerated data type is a user defined data type to improve the readability of the program. It is built

on the integer data type.

An enumerated data type consists of collection of enumeration constants which are represented by

identifiers. Each identifier is given an integer value.

EXERCISES

Review Questions

9.1 How is a structure different from array? 9.2 How is a union different from structure?

9.3 What is the purpose of tag in structure type declaration?

9.4 What is the keyword used to define a structure data type? 9.5 What is the keyword used to define union data type?

9.6 Can we declare structure variable in the structure definition?

9.7 Is the tag of a structure mandatory? 9.8 Can the structure contain members of the same data type?

9.9 Can we use pointers to access the members of a structure?

9.10 Can a function return a structure?

Page 244: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 244

9.11 Can we copy one structure to another structure?

9.12 Can we compare two structures using „==‟ operator? 9.13 Will type definition create a new data type?

9.14 Can we declare array of structures?

9.15 Can an array be a member of a structure? 9.16 Can a structure be a member of another structure?

9.17 Can a structure variable be initialized?

9.18 ________ operator is used to access the members of a structure?

9.19 ________ operator is used to access the members of a structure through its pointer? 9.20 Can we initialize the members of a structure in the structure definition?

9.21 Can a structure be member of a union?

9.22 Can a union be member of a structure? 9.23 Is structure a fundamental data type?

9.24 What is the error in the following structure definition?

struct {

int a;

float b;

}

9.25 What is the error in the following structure definition?

struct ex {

int a=5;

float x=3.75; char ch=‟?‟;

};

9.26 Find the error in the following code?

struct ex {

int a;

char b; } ex x[10];

9.27 Find the error in the following code?

struct ex {

int a;

char b;

}; struct ex x=10, „*‟;

9.28 Is there any error in the following code?

struct ex1 {

int a;

float b;

}; struct ex2

{

double a;

Page 245: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 245

char ch;

} struct ex1 p;

struct ex2 q;

9.29 Find the error in the following code?

struct ex

{

int a;

float b; }

void main()

{ struct ex p = {10,3.5},

struct ex q = {8,3.5};

if (p==q) printf(“The structures are equal\n”);

else

printf(“The structures are not equal\n”);

}

Multiple Choice Questions

1. What is the output when the following code is executed?

struct s

{

int i;

float f;

} x;

void main()

{

x.i=10;

x.f=14.5;

printf(“i=%d; f=%f\n”,x.i,x.f);

}

a) i=10, f=14.500000 b) error in the program as the structure members cannot be initialized through

assignment statement c) 10, 14.50000

2. What is the output when the following program is executed?

(Assume that the program is run on a 16 bit machine)

#include<stdio.h>

main()

Page 246: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 246

{

struct ex;

{

int a;

float b;

char ch;

}

printf(“No of bytes allotted for the structure=%d”, sizeof(ch));

}

a) No of bytes allotted for the structure = 3

b) No of bytes allotted for the structure = 7

c) No of bytes allotted for the structure = 8 d) No of bytes allotted for the structure = 12

3. Consider the following declaration

struct ex {

int rno;

char name[20], gender;

float height; };

struct ex p;

How many bytes of space is allotted for the structure variable p if the program is run on a 16 bit machine.

a) 4 b) 24 c) 27 d) 28

Comprehensive Questions

9.1 Explain the structure data types in C?

9.2 Explain how structures are passed to a function through arguments?

9.3 Define a structure with the following address fields: street, block, area, country. Write a program to conduct search for an address based on any of these fields.

9.4 Create a structure to store the following employee details: employee number, designation, gender,

basic pay, da, hra, deductions, gross pay, net pay. Given the employee number, designation, gender, basic pay, da rate, hra rate and deductions, write a program to calculate gross pay and net pay.

9.5 Define a structure POINT where members are the coordinates of a point in a plane. Write a

function that receive the coordinates of two points from the calling function and return the distance between them. Write another function that return the coordinates of the midpoint. Write the

function main which accepts the coordinates of two points from keyword and option to perform the

specified operation by calling one of the two functions.

9.6 Define a structure TIME with the following fields: hours, minutes and seconds. Write a function that returns a time structure containing the time elapsed between two parameters. You must handle

the case when the start time is in the previous day.

9.7 Define a structure COMPLEX whose fields are the real and imaginary parts of a complex numbers. Write a function that returns the quotient of two parameters. Call this function in main to divide one

Page 247: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

Structures Unions and Enumerated Datatypes 247

complex number by another complex number. You must handle the case when the denominator is

zero. 9.8 Define a structure POINT whose members are the coordinates of a point in a plane. Write a

function that accepts the structure representing a point and return an integer (1,2,3 or 4) that

indicates in which quadrant the point is located. 9.9 Define a structure DATE with the fields: day, month and year. Write a function that will increment

the date by one day and return the new date. If the date is the last day in the month, the month field

must be incremented by one. If the month is December, the value of the year field must be changed

when the day is 31. Also check for the leap year. 9.10 Define a structure DATE with the fields: day, month and year. Define another structure STUDENT

whose fields are roll number, name, height and date of birth which is a structure of the type DATE.

Write a program to read and display the information. 9.11 Define a structure COMPLEX whose fields are real and imaginary parts of a complex number.

Write a function that receives the pointers to two complex numbers through arguments and return

pointer to the sum of the two complex numbers. Write the corresponding calling function main() also.

9.12 Define a structure CRICKET whose fields are name of the player, number of innings played, total

runs scored and getting average. Using CRICKET declare an array x with 50 elements and write a

program to read the name, number of innings and total runs scored by each of the 50 players, and find the batting average. Display all the 50 players details sorted by batting average in tabular from.

9.13 Define a structure FRACTION whose fields are the numerator and denominator of a fraction. Write

a function that will accept two fractions through arguments, return 0 if the two fractions are equal, -1 if the first fraction is less than the second, and 1 other wise.

Page 248: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 248

Chapter 10

FILE PROCESSING

LEARNING OBJECTIVES

After reading this chapter the reader will be able to

understand the need of data file.

learn the operations on files.

use different data input/output functions on files.

write simple programs for creating a data file, reading data from the file for processing and

display.

10.1 INTRODUCTION

What is a file?

With any C program there are two major operations between the user and the program which are

How to send data (input)into the program and

How to get results data (output) from the program

So far we have done these two operation using the following input/output functions

For example the following program reads input data and prints the out data

scanf( )

getchar( ) gets( ) ……..

……

Input functions printf( )

putchar( ) puts( ) ……..

……

Output functions

Page 249: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 249

In the above program the data that is input through keyboard and that is output on the screen is

temporary, because the data is stored in main memory. So whenever the application is closed or the

system is switched off the entire data on main memory is lost. So it is not possible to see the data in

future. Since these I/O functions use keyboard and screen, these functions are console oriented I/O

functions. Using these functions it is not possible to store data permanently in the system.

But in real application like student database, employee database and bank data, it is required to store data

permanently in the system. It is possible to store data permanently in the system by using secondary

memory. The console I/O functions do not support to handle data with secondary memory.

It is therefore necessary to have a flexible approach to operate input and output operations between a file

in secondary memory and the program. This can be achieved by using FILE concept.

For example assume that two files “INPUT.DAT” and “RESULT.DAT” in secondary memory and the

input/output operations between these files and the program shown as follows.

With this explanation we can define a file

A file is some reserved space on the disk where a group of related data is stored permanently in the

system.

Example 10.1: Student data input with the file name “STUDENT.IN”

Example 10.2: Student data output with the file name “OUTPUT.DAT”

STUDENT.IN

RNO NAME SUB1 SUB2 SUB3

10 Ramu 18 15 16

11 Gopi 20 18 15

OUTPUT.DAT

RNO NAME SUB1 SUB2 SUB3 TOTAL AVG

10 Ramu 18 15 16 410 16.33

11 Gopi 20 18 15 53 17.67

Example2.c

#include<stdio.h> void main( ) { FILE fp1, fp2; int x; fp1=fopen(“INPUT.DAT”, “r”); fp2=fopen(“RESULT.DAT”, “w”); f scanf(fp1, “%d”, &x );

fprintf(fp2, “\n x=%d”, x); }

Output (To the file)

x = 5

RESULT.DAT

5 7 10 11 13 14

INPUT.DAT

Input (Through

file)

where

fscanf( ) – is file input function used to read data from the file to the program

fprintf( ) – is file output function used to write data to the file from the

program

Page 250: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 250

10.2 FILE OPERATIONS

The different basic file operation are

Naming a file

Creating / Opening a file

Closing a file

Writing data to a file

Reading data from a file

C supports a number of functions that have the ability to perform basic file operations, which includes:

10.2.1 Creating a new file / Opening an existing file To create a new file or to open an existing file the function fopen( ) is used.

fopen( ) is a file function used to create a new file or to open an existing file. Its general form is

where

fp – is a file pointer which is of structure data type FILE declared in stdio.h

The general syntax to declare the file pointer is

For example,

FILE *p1, *p2, *fp;

“filename” – is the name of the file and is a string of characters that make up a valid filename for the

operating system. It may contain two parts, a primary name and an optional period with the extension.

For example,

“input.data”

“STUDENT.DAT”

“RESULTS.OUT”

“mode” – specifies the purpose of opening the file. The mode of the file may be one of the following

“w” -- open a new file for writing data

“r” -- open an existing file for reading data

“a” -- open an existing file for appending data to it

“r+” -- open an existing file for both readingandwritingdata

“w+” -- same as “w” except both for reading and writing

“a+” -- same as “a” except both for reading and appending

fp = fopen ( “filename”, “mode” );

FILE *file-pointer;

Page 251: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 251

Example10.3: Create a new file “STUDENT.IN” for writing

#include<stdio.h>

void main( )

{

FILE *fp;

fp = fopen( “STUDENT.IN”, “w” );

……………………

……………………

}

A new file with the name “STUDENT.IN” is created. If the file already exists, contents of the file are

deleted.

Example10.4: Open an existing file “STUDENT.IN” for data reading

#include<stdio.h>

void main( )

{

FILE *fp;

fp = fopen( “STUDENT.IN” , “r” );

………………

……………………

}

An existing file with the name “STUDENT.IN” is opened for reading data. If the file does not exist an

error will occur.

Example10.5: open the file “STUDENT.IN” for appending data

#include<stdio.h>

void main( )

{

FILE *fp;

fp = fopen( “STUDENT.IN” , “a” );

……………………

……………………

}

An existing file with the name “STUDENT.IN” is opened for appending data to it .If the file does not

exist a new file with the name “STUDENT.IN” is opened.

10.2.2 Closing a file

A file must be closed as soon as all operations on it have been completed. The function fclose() is used to

close the file that has been opened earlier.

fclose( ) is the counterpart of fopen( ). Closing file means delinking the file from the program and saving

the contents of the file. Its general form is

This would close the file associated with the file pointer fp.

fclose(fp);

fp

STUDENT.IN

fp

STUDENT.IN

fp

STUDENT.IN

Page 252: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 252

Example10.6

#include<stdio.h>

void main( )

{

FILE *p1 *p2;

p1=fopen (“Input”,”w”);

p2=fopen (“Output”,”r”);

….

fclose(p1);

fclose(p2);

}

In the above example two files are opened and will be closed after all operations on them have been

completed. Once a file is closed its file pointer can be used to open another file.

10.3 FILE INPUT/OUTPUT FUNCTIONS Input to a program may be through keyboard or from a file and output is to the screen or to a file.

Programs using files may involve the combinations of these different input/output operations and shown

as follows:

After a file is opened, we can read data stored in the file or write new data to it depending on the mode of

opening. C standard library supports a good number of functions which can be used for performing I/O

operations. File I/O functions are broadly classified into two types.

1. High level file I/O functions

2. Low level file I/O functions

Example1.c

#include<stdio.h>

void main( )

{

……………….

……………….

……………….

……………….

}

Output data

(On the screen)

Putchar(), puts(), printf()

Input data

(Through keyboard)

getchar(), gets(), scanf()

Input (Through file)

fgetc(), fgets(), fscanf()

Output (To the file)

fputc(), fputs(), fprintf()

x = 5

RESULT.DAT

5 7 10 11 13 14

INPUT.DAT

Page 253: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 253

High level file I/O functions are basically C standard library functions and are easy to use. Most of the C

programs handling files use these because of their simple nature. Low level file I/O functions are file

related system calls of the underlying operating system. These are relatively more complex in nature

when compared to high level file I/O functions but efficient in nature. The following are the high level

file I/O functions

Character data oriented functions

String data oriented functions

Mixed data oriented functions

`110.3.1 Character data oriented functions

fputc( ) : This function is used to write a single character to a file. Its general form is

Where the character/char-variable represents a character and fp is a pointer to the FILE. The function

writes the character or content of char-variable to the file pointed by fp.

Program10.1: Program to create a text file named TEXT.DAT

#include<stdio.h>

#include<conio.h>

void main()

{

FILE *fp;

char ch;

fp=fopen(“TEXT.DAT”,”w”);

if(fp==NULL)

{

printf(“file is not opened\n”);

exit(0);

}

while((ch=getchar())!=EOF)

fputc(ch,fp);

fclose(fp);

}

Text is read character by character from the keyboard and is written to the file. The end of the text is

indicated by entering an EOF character, which is control-Z in the DOS environment.(this may be control-

D on other environments).After the EOF is encountered the file is closed.

fgetc( ) : This function is used to read a single character from a file. Its general form is

The function reads a character from the file denoted by fp and returns the character value, which is

collected by the char-variable.

Program10.2: A file named TEXT.DAT is on the disk. Program to read the text from the file and

display the text on the monitor after converting to upper case.

fputc( character/char-variable, fp);

char-variable = fgetc( fp);

Page 254: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 254

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

void main()

{

FILE *fp;

char ch;

fp=fopen(“TEXT.DAT”,”r”);

if(fp==NULL)

{

printf(“Unable to open the file”);

exit(0);

}

printf(“The text stored on the disk after converting to upper case is \n”);

while((ch==fgetc(fp))!=EOF)

putchar(toupper(ch));

fclose(fp);

}

The file TEXT.DAT is opened for reading. The text is read character by character ,converted to upper

case and is displayed on the screen. Reading is terminated when fgetc() encounters the end of file mark

EOF.

Program10.3:A file named INTEXT contains a text .Program to copy the text from this file to the file

OUTTEXT.

#include<stdio.h>

void main()

{

File *fp1,*fp2;

char ch;

if((fp1=fopen(“INTEXT”,”r”))==NULLl)

{

prinf(“Unable to open the file INTEXT\n”);

exit(0);

}

if((fp2=fopen(“OUTEXT”,”w”))==NULL)

{

printf(“Unable to open the file OUTTEXT\n”);

exit(1);

}

while((ch=fgetc(fp1))!=EOF)

fputc(ch,fp2);

fclose(fp1);

fclose(fp2);

}

Program10.4: Program to count the number of words in a text stored in a file. Words are separated by

one or more whitespace charactersthat is ,by a space, a tab or a new line.

#include<stdio.h>

void main()

{

FILe *fp;

Page 255: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 255

char ch;infile[20];

int nw=0,flag=0;

printf(“enter the name of the file containing text:\n”);

gets(infile);

if((fp=fopen(infile,”r”))==NULL)

{

printf(“Unable to open the file\n”);

printf(“\n”);

}

while((ch=fgetc(fp))!=EOF)

{

if(ch==’ ’||ch==’\t’||ch==’\n’)

flag=0;

else

{

if(flag==0)

{

nw++;

flag=1;

}

}

}

printf(“the number of words=%d\n”,nw);

}

The variable flag is used to identify the previous character. If flag=0,previous character is white space

otherwise it is not white space. Previous character is white space and present character is non-white space

indicate the beginning of a word and hence word count nw is incremented by one.

Program 10.5 Program to count number of characters and lines in a text stored in a file.

#include<stdio.h>

void main()

{

int nc=0,nl=0;

FILE *fp;

char curch,prech;

if((fp=fopen(“TEXT”,”r”))==NULL)

{

print(“unable to open the file\n”);

exit(0);

}

while((curch=fgetc(fp))!=EOF)

{

if(curch!=’\n’)

++nc;

else

++nl;

prech=curch;

}

if(prech!=’\n’)

++nl;

printf(“number of characters=%d\n”,nc);

printf(“number of lines=%d\n”,nl);

Page 256: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 256

fclose(fp);

}

The variable curch represent the character read in and prech represent the previous character. The variable

prech is used to know whether the text ends with new line. If it does not end with new line after the

control exits from the loop nl must be incremented by1 to count the last line of the text.

The statement

if(prech!=’\n’)

++nl;

is written for this purpose.

10.3.2 String data oriented functions

fputs( ) : This function is used to write a string to a file. Its general form is.

Where the string/string-variable represents a string constant and fp is a pointer to FILE. The function

writes the string or content of string-variable to the file pointed by fp. Also, fputs() does not add a new

line to the end of the string. It must be included explicitly.

Program10.6: Program to create a file for writing strings to it using fputs( )

#include<stdio.h>

void main( )

{

FILE *fp;

char str[] = “NEW” ;

fp = fopen(“DATA.IN” , “w” );

fputs(str , fp);

fputc(“\n”,fp);

fputs(“OLD” , fp);

fputc(“\n”,fp);

fputs(“OLD OLD”, fp);

fputc(“\n”,fp);

fclose(fp);

}

The function fputs() writes the content of string variable str first and then the strings “OLD” and “OLD

OLD” to the file

fgets( ) : This function is used to read a string from a file. Its general form is

The function reads a string of n-1 characters from the file pointed by fp and returns the string value,

which is collected by the string-variable.

It will stop reading when any one of the following conditions is satisfied

It has read(n-1)characters

It encounters a new line character

It reaches the end of file

A read error occurs

fgets() automatically appends a null character to the string read.

fputs( string/string-variable, fp);

fgets(string-variable , n, fp);

NEW OLD

OLD OLD

DATA.IN

Page 257: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 257

Program10.7 Program to read strings from a file using fgets( ).

#include<stdio.h>

void main( )

{

FILE *fp;

char str1[ ], str2[ ];

fp = fopen(“DATA.IN” , “r” );

fgets(str1, fp);

puts(str1);

fgets(str2, fp);

puts(str2);

fclose(fp);

}

Initially the string “NEW” is read and stored in string variable str1 and next the string “OLD” is read

and stored in string variable str2.then theyare displayed on the screen.

10.3.3 Mixed data oriented functions

fprintf( ) :The function is used to write multiple data items which may (or may not) be of different

types to a file. Its general form is.

Where fp is a pointer to the file, “control-string” contains output specifications for the data to be written

and arg1, arg2 … are the arguments list. The function writes the data values of arg1, arg2… to the file

pointed by fp.

Program10.8: Program to write student details to a file using fprintf( )

#include<stdio.h>

void main( )

{

FILE *fp;

char name[30] = “RAMU”;

int rollno = 25;

float total_marks = 450;

fp = fopen(“STUDENT.IN” , “w” );

fprintf( fp, “\n%d\t%s\t%f”, rollno, name, total_marks);

fclose(fp);

}

The contents of rollno, name and total_marks are written to the file pointed by fp.

fscanf( ) :- This function is used to read multiple data items which may be of different types from a

file. Its general form is

NEW OLD

DATA.IN

fprintf( fp,“control-string”, arg1, arg2, arg3,…);

25 RAMU 450

STUDENT.IN

fscanf( fp,“control-string”, v1, v2, v3,…);

Page 258: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 258

The function reads data values in a given format from the file pointed by fp and returns the data values,

which are collected by the variable list.

Program 10.9: Program To read student data from the file ”STUDENT.IN” using fscanf()

#include<stdio.h>

void main( )

{

FILE *fp;

char name[30];

int rollno;

float total_mark ;

fp = fopen(“STUDENT.IN” , “r” );

fscanf( fp,“%d%s%f”, &rollno,name,&total_marks);

fclose(fp);

}

The data values from the file “STUDENT.IN” are read and the values are collected by rollno, name and

total_marks respectively.

10.4 PROGRAMS USING FILES

Example program on getw() and putw() functions

Program10.10: Program to read integers through key board and write to the file “DATA”. Later read the

integers from the file “DATA”, and write even numbers to the file “EVEN” and odd numbers to the file

“ODD”. Read data from the files “EVEN”, “ODD” and display on the screen

#include< stdio.h >

main()

{

FILE *f1,*f2,*f3;

int number,i;

printf(“Contents of the data file\n\n”);

f1=fopen(“DATA”,”w”);

for(i=1;i< 30;i++)

{

scanf(“%d”,&number);

if(number==-1)

break;

putw(number,f1);

}

fclose(f1);

f1=fopen(“DATA”,”r”);

f2=fopen(“ODD”,”w”);

f3=fopen(“EVEN”,”w”);

while((number=getw(f1))!=EOF) /* Read from data file*/

{

if(number%2==0)

putw(number,f3); /*Write to even file*/

else

25 RAMU 450

STUDENT.IN

Page 259: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 259

putw(number,f2); /*write to odd file*/

}

fclose(f1);

fclose(f2);

fclose(f3);

f2=fopen(“ODD”, ”r”);

f3=fopen(“EVEN”, ”r”);

printf(“\n\nContents of the odd file\n\n”);

while((number=getw(f2))!=EOF)

printf(“%d”,number);

printf(“\n\nContents of the even file”);

while((number=getw(f3))!=EOF)

printf(“%d”,number);

fclose(f2);

fclose(f3);

}

Program10.11: Program to read inventory data; item, number, price and quantity for three items and

writes the data to the file. Later read the data from the file and display on the screen with total value.

/*Program to handle mixed data types*/

#include< stdio.h >

main()

{

FILE *fp;

int num,qty,i;

float price,value;

char item[10],filename[10];

printf(“Input filename”);

scanf(“%s”,filename);

fp=fopen(filename,”w”);

printf(“Input inventory data\n\n”);

printf(“Item_name, number, price and quantity\n”);

for i=1; i< =3; i++)

{

scanf(”%s%d%f%d”, item, &number, &price, &quality);

fprintf(fp,”%s%d%f%d”, item, number, price, quality);

}

fclose (fp);

fp=fopen(filename,”r”);

printf(“\nItem_ name \t Number \t Price \t Quantity \t Value”);

for(i=1;i< =3;i++)

{

fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);

value=price*quantity;

printf(”\n%s \t %d \t %f \t %d \t %d”,item, number, price, quantity, value);

}

fclose(fp);

}

Page 260: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 260

Program10.12: Define a structure emp with members as empno, name and salary. Write a program to

read information for n number of employees and write this data to the file ‘EMP.DAT”. Later read the

data from the file and display on standard output

#include<stdio.h>

struct emp

{

int empno;

char name[30];

float salary;

}

void main( )

{

int n,i;

FILE *fp;

struct emp e;

fp = fopen(“EMP.DAT”, “w”);

printf(“\nEnter number of employees:”);

scanf(“%d”, &n);

printf(“\n Enter empno, name and sal for %d number of employees:\n”, n);

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

{

scanf(“%d%[^\n]%f”, &e.empno, e.name, &e.salary);

fprintf(fp, “\n%d\t%s\n%f”, e.empno, e.name, e.salary);

}

fclose(fp);

fp=fopen(“EMP.DAT”, “r”);

printf(“\nContents of the file EMP.DAT”);

while(!feof(fp))

{

fscanf(fp, “%d%[^\n]%f”, &e.empno, e.name, &e.salary);

printf(“\n%d\t%s\t%f”, e.empno, e.name, e.salary);

}

fclose(fp);

}

SUMMARY

Real life situations involve large volume of data and in such cases the console oriented I/O operations

pose two major problems. It becomes cumbersome and time consuming to handle large volumes of data

through terminals. The entire data is lost when either the program is terminated or computer is turned off.

Therefore, it is necessary to have more flexible approach where data can be stored on the disks and read

whenever necessary, without destroying the data. This method employs the concept of files to store data.

The concept of files enables us to store large amount of data permanently on the secondary storage

devices. A defined data type FILE is used to represent a file within program. It acts as an internal file

name for a file. Before performing any operation over a file, it has to be opened. The purpose of the

opened file may be for writing data or reading data or may be for appending data to the file. Once the

intended operation is over the file has to be closed. The file input/output operations are by using the

functions fgetc( ), fputc( ) which are the character oriented file I/O functions, fgets( ),fputs( ) are the

string oriented functions and fscanf( ) and fprintf() are the mixed data oriented functions.

Page 261: Chapter 1 PROBLEM SOLVING - WordPress.com · Problem solving 3 problem is more clearly defines. This approach of focusing on a particular problem can give us the foothold we need

File Processing 261

EXERCISES

Review Questions

10. 1 What is a file? Why do we need to store data in files?

10. 2 What are the most commonly performed operations on files?

10. 3 What are the different modes of opening a file?

10. 4 What is the difference between “w” and “a”?

10. 5 Mention character oriented file I/O functions and syntax of their usage

10. 6 Explain the syntax and usage of fprintf( ) and fscanf( )

10. 7 File is a named storage on the secondary storage device (TRUE / FALSE)

10. 8 A file should be first opened before performing any operation (TRUE / FALSE)

10. 9 When a file is opened in “w” mode, the previous contents remain intact (TRUE / FALSE)

10. 10 When a file is opened in “a” mode, the previous contents are lost(TRUE / FALSE)

10. 11 Identify the error

a) FILE fp;

fp = fopen(“text.dat”, “w”);

b) FILE *fin;

fin = fopen(“text.dat”, r );

c) FILE *fp1, *fp2;

fp1 = fopen(“text.dat”, “w”); fp2 = fopen(“text.dat”, “r”);

d) #include<stdio.h>

main()

{

FILE *fp1;

char c;

fp=fopen(“infile.txt”,”r”); fclose(infile);

}

10. 12 Distinguish between fgetc()and getchar() functions

10. 13 Distinguish between printf() and fprintf() functions

10. 14 What is the significance of EOF

Comprehensive Questions

10. 1 Define files. Explain any five operations on files.

10. 2 Write a program using a for loop to put the following numbers to a file named “record.dat”. 1

2 3 4 5 6 7 8 9 10

10. 3 Write a program to read the file “record.dat” created in the above problem and print its contents

to the standard output.

10. 4 Write a program to count the number of characters in a text file.

10. 5 Write a program to copy the content of one text file to another text file.

10. 6 A file contains a list of names. Write a program to sort the names read from the file and

display them.

10. 7 What are the three steps followed while accessing a file? Write a program to convert the case of

alphabets in a text file. Upper case letters should be converted to lower case and vice versa.

10. 8 Write a program to read student data consisting of Id.No, Name and marks in six subjects from

the keyboard , write it to a file called INPUT, again read the same data from the file INPUT, and

find the total and percentage marks of each student. Display the output in tabular form.

10. 9 Write a program that accepts inventory details item –name, number, price and quantity, stores

them in a file and prints the data on the screen.

10. 10 Write a program that reads an input text file and tabulate the number of times that each of the 128

ASCII characters appears.

10. 11 What are the three steps that are followed while accessing a file? Write a program to convert the

case of alphabets in a text file. Upper case letters should be converted to lower case and vice

versa.