You are on page 1of 285

$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

As per 2nd Semester, RTU Syllabus

FUNDAMENTAL
OF

COMPUTER PROGRAMMING
with more than 250 Lab Programs

J. K. Sharif

JHUNJHUNUWALA

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Fundamental of Computer Programming 1e


JK Sharif

Copyright © By JHUNJHUNUWALA

Information contained in this book has been obtained by author, from sources believes to be
reliable. However, neither Jhunjhunuwala nor its author guarantee the accuracy or completeness
of any information herein, and Jhunjhunuwala nor its author shall be responsible for any
error, omissions, or damages arising out of use of this information. This book is published with
the understanding that Jhunjhunuwala and its author are supplying information but are not
attempting to render engineering or other professional services.

MRP 360.00

JHUJHUNUWALA
55, Suryalok Complex, Abids, Hyderabad – 500001
Ph : +91  40  64582577,
www.jhunjhunuwala.com
email : info@jhunjhunuwala.com

Printed by Nodia and Company, Jaipur

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

SYLLABUS

206 FUNDAMENTAL OF COMPUTER PROGRAMMING

UNIT – 1
Programming in C: Structure of C Program, Concept of Preprocessor, Macro Substitution, Intermediate
code, Object Code, Executable Code. Compilation Process,
Basic Data types, Importance of braces ({ }) in C Program, enumerated data type, Identifiers, Scope of
Variable, Storage Class, Constants, Operators & Expressions in C, Type Casting, printf( ) and scanf ( )
with format specifires, reading single character.

UNIT – 2
Control Statements, Command Line Arguments, Arrays in C, Pointers, Using pointers to represent arrays,
Pointer & address arithmetic. Structures, using typedef.

UNIT – 3
Arrays of Structures & pointers, File Handling (fscanf, fprintf, feof, fopen, fclose, fread, fwrite only).
Dynamic memory Allocation.

UNIT – 4
Functions in C, Passing Parameters (By value & Reference), using returned data, Passing arrays,
structures, array of structures, pointer to structures etc., passing characters and strings, The void pointer.

UNIT – 5
Stored Program Architecture of Computers, Storage Device- Primary Memory and Secondary Storage,
Random, Direct, Sequential access methods. Concept of High-Level, Assembly and Low Level programming
languages. Representing Algorithms through flow chart, pseudo code, step by step.
Number System: Data Representation, Concept of radix and representation of numbers in radix r with
special cases of r=2, 8, 10 and 16 with conversion from radix r1 to radix r2. r’s and (r-1)’s complement,
Representation of alphabets.

Suggested Readings :

1. Ritchie & Kernighan, The C Programming language, 2nd Ed., PHI.


2. Dey & Ghosh, Computer Fundamentals and programming in C, Oxford.
3. Kamthane, Programming in C, 2nd Ed., Pearson.
4. Schildt, The Complete Reference, 4th Ed., TMH.
5. Balaguruswamy, Programming in ANSI C, 5th Ed., TMH.
6. V. Rajaraman, Fundamentals of Computers, 5th Ed. PHI, 2011.
7. Forouzan et.al, Computer Science, 3rd Ed. Cenage Learning.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

PREFACE

This book is written for B. TEch 2nd semester syllabus of RTU, Kota. This book Fundamental
of Computer Pgoramming contains some special features to aid you on your path to learn
about fundamental concepts of computer and later programming with C in easy way. Each
chapter provides concrete examples and explanation of concepts. Numerous sample programs
illustrate C’s features and concepts, so that you can apply them in your computer lab with
ease. Each chapter ends with section containing review questions relating to the chapter with
reference to old year questions asked in university exams. It contains programming output quiz.
That tests your knowledge of the concepts and helps you to prepare for aptitude test conducted
by various software companies at the time of recruitment. You won’t learn Computer
Fundamentals and C just by reading this books, however. If you want to be a good computer
programmer, you’ve got to write programs in lab sessions. You can use Lab Programs for that.
We recommend that you attempt each exercise. Writing C code is the best way to learn C.
Unlike most other C books, this books, this books offers many sample programs and exercises
with clear explanations and answers, which makes the concepts of the C languages easier to be
understood. After reading this book, you’ll be able to write C programs on your own.

J. K. Sharif

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

CONTENTS

1 BASIC CONCEPTS
1.1 Introduction 1
1.2 Stored Program Architecture 1
1.3 Primary and Secondary Memory 2
1.4 Access Mechanism 3
1.5 Basic Model of Programming 4
1.6 Steps for Program Development 5
1.7 Algorithm 6
1.8 Flowchart 8
1.9 Pseudo Code 10
1.10 Programming Language Classification 11
1.11 Machine Language 11
1.12 Assembly Language 12
1.13 High Level Language 14

2 INTRODUCTION TO C
2.1 Introduction 17
2.2 Uses of C 18
2.3 Structure of a C program 18
2.4 C Programming Rules 20
2.5 Writing the first C Program 20
2.6 Files Used in a C Program 21
2.7 Compiling and Executing C Programs 23

3 CONSTANT, VARIABLE AND DATA TYPE


3.1 Introduction 25
3.2 Character Sets 25
3.3 Tokens 26
3.4 Data Type 30
3.5 Constants 33
3.6 Variables 34
3.7 Const and Volatile Qualifires 36
3.8 Data Type Modifier 37
3.9 BackSlash Constant 39
3.10 Symbolic Constant 40
3.11 Delimiters 40

4. OPERATORS AND EXPRESSIONS


4.1 Introduction 42
4.2 Working with Operators 42
4.3 Unary Operators 42

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

4.4 Assignment Operators 43


4.5 Arithmetic Operator 46
4.6 Increment and Decrement Operators 47
4.7 Relational Operators 49
4.8 Logical Operators 50
4.9 Bitwise Operators 51
4.10 Conditional Operators 52
4.11 Special Operators 53
4.12 Operator Precedence in C 54
4.13 Type Conversion and Typecasting 57
4.14 Mathematical Functions in C 61
4.15 Header Files and Preprocessor Directives 62

5. INPUT AND OUTPUT OPERATIONS


5.1 Introduction 67
5.2 Input/Output Functions 67
5.3 printf() Function 68
5.4 printf() Place Holders 69
5.5 Escape Sequence 72
5.6 scanf() Function 73
5.7 scanf() Place Holders 74
5.8 getchar() Function 76
5.9 gets() Function 76
5.10 putchar() Function 77
5.11 puts() Function 78

6. DECISION MAKING
6.1 Introduction 82
6.2 If Statement 82
6.3 If Else Statement 86
6.4 Nested If 88
6.5 Using the If-Else Ladder 90
6.6 Switch Statement 91

7. ITERATION
7.1 Introduction 103
7.2 While Loop 105
7.3 Do While Loop 108
7.4 For Loop 109
7.5 Jump Statement 117

8. ARRAY
8.1 Introduction 129
8.2 Array 130
8.3 Type of Array 130
8.4 One Dimensional Array 130
8.5 Declaring One Dimensional Array 131
8.6 Storing Values in One Dimensional Arrays 132

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

8.7 Accessing Elements of One Dimensional Array 137


8.8 Address and Length of Array Elements 140
8.9 Two Dimensional Array 141
8.10 Multidimensional Array 146

9. STRINGS
9.1 Introduction 153
9.2 Understanding Strings in C 153
9.3 Declaring and Initializing a String 154
9.4 Reading and Displaying the Strings 155
9.5 Creating an Array of Strings 160
9.6 Performing String Operations 161
9.7 Using String Handling Functions 165

10. FUNCTIONS
10.1 Introduction 182
10.2 Function Declaration 184
10.3 Function Definition 185
10.4 Function Call 187
10.5 Passing Parameter to Function 189
10.6 Passing Array in Function 193
10.7 Recursive Function 197
10.8 Recursion vs Iteration 199
10.9 Storage Classes 200
10.10 Functions and Variables 202

11. STRUCTURE AND UNION


11.1 Introduction 212
11.2 Declaring a Structure 212
11.3 Structure Variables 213
11.4 Structure Initialization 214
11.5 Accessing Structure Members 214
11.6 Structure Assignment 216
11.7 Finding Size of the Structure 216
11.8 Array of Structures 217
11.9 Accessing Members of Structure Array 217
11.10 Structure Within Structure (Nested Structure) 219
11.11 Union 222

12. POINTERS
12.1 Memory Organization 229
12.2 Understanding Pointers 230
12.3 Declaring a Pointer Variable 230
12.4 Using the Address of (&) Operator 231
12.5 Initializing a Pointer Variable 233
12.6 Dereferencing a Pointer 234
12.7 Performing Operation on Pointer 236
12.8 Null and Void Pointer 240

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

12.9 Working with Functions and Pointers 241


12.10 Working with Arrays and Pointers 242
12.11 Pointers to String 244
12.12 Difference Between Array Name and Pointer 250
12.13 Pointers and Two Dimensional Array 252
12.14 Array of Pointers 256
12.15 Pointers to Function 259
12.16 Pointers to Structure 263
12.17 Drawback of Pointer 266
12.18 Dynamic Memory Allocation 266

13. FILE HANDLING


13.1 Introduction 274
13.2 Type of Files 274
13.3 Text Files 274
13.4 Performing File Operations 275
13.5 End of File Function 280
13.6 Variable Record Length Files 281
13.7 Fixed Record Length Files 285
13.8 Multiple File Operations 287

14. PREPROCESSOR DIRECTIVE


14.1 Introduction 292
14.2 File Inclusion Directives 293
14.3 Macro Substitution Directives 294
14.4 Compiler Control Directives 297

15 NUMBERS SYSTEMS
15.1 Number Systems 303
15.2 Number System Conversion 306
15.3 Summary of Number Conversion 316
15.4 Complements of Numbers 323
15.5 Data Representation in Binary 328
15.6 Floating Point data Representation 332
15.7 Representation of Alphabets 336

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

1
BASIC CONCEPTS

1.1 INTRODUCTION

Computation refers to the process of arriving at output from a given


program, a problem statement, or a given decision. This process of
computation should be logical and the process should follow a step by
step approach to arrive at a meaningful output or result. To achieve
the desirable output, you should follow the basic model of computation.

1.2 STORED PROGRAM ARCHITECTURE

All stored - program computer use the Von Neumann architecture. The
characteristics of stored-program machine are as follows :
• Consists of three hardware systems: A central processing unit (CPU)
with a control unit, an arithmetic logic unit (ALU), registers (small
storage areas), and a program counter; a main-memory system,
which holds programs that control the computer’s operation; and
an I/O system.
• Capacity to carry out sequential instruction processing.
ʇ NOTE
• Contains a single path, either physically or logically, between the This single path is often
main memory system and the control unit of the CPU, forcing referred to as the von Neumann
alternation of instruction and execution cycles. bottleneck.

Figure 1.1 show the architecture of this machine. This architecture


runs programs that is known as the von Neumann execution cycle
(also called the fetch-decode-execute ccycle), which describes how the
machine works. One iteration of the cycle is as follows:
• The control unit fetches the next program instruction from the
memory, using the program counter to determine where the
instruction is located.
• The instruction is decoded into a language the ALU can understand.
• Any data operands required to execute the instruction are fetched
from memory and placed into registers within the CPU.
• The ALU executes the instruction and places the results in registers
or memory.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 2 Basic Concepts Chapter 1

Figure 1.1 : Von Neuman Model

ʇ NOTE
1.3 PRIMARY AND SECONDARY MEMORY The primary memory itself
is implemented by two types
Primary memory, often called main memory, constitutes that device, of memory technologies. The
first is called Random Access
or group of devices, that holds instructions and data for rapid and
Memory (RAM) and the other
direct access by the computer’s central processing unit (CPU). The is read only memory (ROM).
processor or the CPU directly stores and retrieves information from A more appropriate name for
RAM is RWM (Read Write
it. This memory is accessed by CPU, in random fashion. That means Memory), the CPU can write
any location of this memory can be accessed by the CPU to either read and read information from
information from it, or to store information in it. any primary memory location
implemented using RAM. The
Secondary memory, also called auxiliary memory or mass storage, other part of primary memory is
consists of devices not directly accessible by the CPU. It stores the implemented using ROM which
data permanently unless it is erased. The secondary memory is usually stands for Read Only Memory.

available in the form of floppy disk storage media, hard disk, CD, DVD,
Pen drive (i.e. Mass storage devices), memory chips. The data on the
floppy disk is organized in terms of tracks and sectors. Hard disk can
have large capacity something like 80-300 GB’s or higher. Hard disk
itself is made up of, large number of platters. Hard disk is usually much
faster compared to floppy disk. CD can store up to 750 mb of data.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 3

Information on CD ROM is organized in terms of a spiral track. A DVD


is digital Versatile Disk and can store 4.6 Gigabyte of information. All
these CD disk are usually write ones and read many times (if the disk
is not multisession and re writable). So are the DVDs.

1.4 ACCESS MECHANISM

Technology and system requirements have produced a variety of


memory types having different access mechanisms. These are briefly
explained below :
1. Random Access Memory (RAM) : A memory for which any
location of relatively small size (specified as a word) has a unique
physically wired-in addressing mechanism and is retrieved in
one memory cycle time. The time to retrieve any given location
is same. Main storage, cache, etc. are typical illustrations of
random access memories used in a computer system.
2. Direct Access Storage Device (DASD) : A storage system for
which a location has a unique address, but it is not physically wired
in. Addressing is accomplished by a combination of direct access
ʇ NOTE
to reach a general vicinity and minimal sequential searching, A typical illustration of DASD
counting or waiting to access to the desired location that stores is the disk system.
a set of words referred to as a record. Time to retrieve data
from any given location is not fixed and depends on the physical
location of the record at any given time. This can vary from
record to record and even for a given record when accessed at
different times. Since the addressing is not wired in, the storage
medium must contain certain amount of addressing information
to assist in the location of data in the desired record.
3. Sequential Access Storage (SAS) : A memory for which a
location (that stores a record) does not have a unique address.
Records are stored/retrieved sequentially one after the other.
Inter-record gap (IRG) is used to separate records and assist in
retrieval. Such sequential accessing may require searching every
record in the storage medium by a specified key (a field in the
record) before the correct one is located.
A typical illustration is the tape system.
4. Content Addressable Memory (CAM) : This is also known as
Associative Memory where a location is accessed by a field of
data word stored in the memory rather than by any address.
It can be viewed as a random access type memory which in
addition to having a physically wired-in addressing mechanism
also has wired-in logic for bit comparison. This logic circuit
enables comparison of desired bit positions of all the words with
a specified input key. This comparison is done simultaneously
for all the words. The word(s) for which match occurs are then
sequentially accessed for read/write operation.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 4 Basic Concepts Chapter 1

1.5 BASIC MODEL OF PROGRAMMING

The basic model of computation includes a series of phases starting from


defining a problem, analysing that problem, designing and planning the
procedure to be followed, coding of the Let’s discuss these phases in
detail in the following sections.
ʇ NOTE
1.5.1 Defining the Problem (Phase 1) For example, if you need to solve
a quadratic equation, but it is
In this phase, the programmer has to define the task precisely and not specified whether to find
check for completeness. The defined problem should not be ambiguous, the value of roots of quadratic
equation or to find the nature
imprecise, or arbitrarily defined. of roots of quadratic equation,
or both. Then the problem
1.5.2 Analysing Problem (Phase 2) is incomplete. Therefore, the
different programmers may
In the problem definition phase, the programmer has to reflect all the program this problem as per
their understanding.
possibilities for decision-making. When the programmer defines the
problem, a proper analysis of that problem requires. As the problem
analysis helps in designing and coding for that particular problem.
In this phase, the programmer has to declare the computational
strategies to analyze the defined problem with the help of available
resources,such as database. Programming techniques including sequence,
selection, and iteration, can be used to develop the logic for the analysis
with the help of searching, sorting, inserting, and merging. Different
procedures that can be followed to analyze the problem are arithmetic,
logical, and relational.

1.5.3 Designing a Program (Phase 3)


After defining and analyzing the problem, you need to design the
solution for the problem. In this phase, the basic aspect is the selection
of suitable data structure, which depends on amount and nature of the
data that is to be stored. The suitable data structure in the designing
phase is an algorithm. It is the primary stage of the program that leads
to correct and efficient program designing.
Another way that can be followed to design a process for problem
solving is the top-down design approach. It is a strategy where the
problem is divided into a hierarchical structure. A separate sub-program
may be designed for each module. The top-down approach provides a
method of handling the inherent logical complexity. This allows the
programmer to build a solution in a step-wise manner. Flowchart is the
best example for the top-down design approach.

1.5.4 Coding a Program (Phase 4)


In this phase, the programmer needs to write a program with the help of
coding. However, before coding a program, the logic must be developed
by using the program development tools, such as algorithm and

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 5

flowchart. You can also divide a program into smaller sub-programs for
easier programming. This procedure is called refinement of the original
problem. You can define the data items, variables, and constants while
writing the code for the program.

1.5.5 Testing a Program (Phase 5)


After writing a program, programmer needs to test the program for
completeness, correctness,reliability, and maintainability. This phase
enhances the quality of the program. To test any program, it is important
to identify the available data based on the specific criteria of selection
and the level at which the data is tested.
Selection of Data for Testing Purpose
Testing of data is relevant only if the selection of data is accurate and
appropriate. Selected data can be either live data or artificial data. The
live data can be collected from the existing system, which is required
for a live project.
On the other hand, artificial data may be generated by some
other source that can be tested in the program.
Levels of Testing the Program
You can test a program at the following different levels:
(1) Unit testing refers to testing in which a complex program can
be divided into sub programs and each module can be tested
separately.
(2) Program testing refers to testing in which a program is sufficiently
small to test at once.
(3) Verification testing refers to the process of using a program in a
simulated environment and looks for the design specification.
(4) Validation testing refers to the process of using the program in
a live environment and looks for errors.
ʇ NOTE
1.5.6 Maintaining Program (Phase 6) Even the program must have
the security so that no one can
This phase includes either the improvement of the program or the access the program.
correction that arises during the execution of the program. Improvement
or amendment in the program requires proper documentation of the
program. If one programmer has developed the program and another
programmer is involved in its maintenance, then he/she must have
complete information about the data items and logical development of
that program.

1.6 STEPS FOR PROGRAM DEVELOPMENT

A program can be developed by using two main approaches including

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 6 Basic Concepts Chapter 1

algorithm and flowchart. Algorithm is used to develop a program that


follows a systematic approach to get the desired output. By converting
the logic of a program into the graphical form is called a flowchart. A
flowchart helps you to understand the concepts of program more easily.
By using any of the approaches, you can write down the code of
the program, compile, and execute the program.

1.7 ALGORITHM

Computers are basically used to solve complex problems in a systematic


and easy manner. In order to solve a problem systematically, the
solution should be written as a set of sequential steps. Each of these
steps specify some simple actions that need to be performed. Thus an
algorithm may be defined as a finite and ordered sequence of steps
which when performed lead to the solution of the problem in a definite
time. Ordered sequence implies that the execution takes place in the
same manner or order in which the statements are written i.e., each
step of the algorithm is written in such a way that the next instruction
follows automatically. The ordering is provided by assigning positive
integers to the steps. The words BEGIN and END normally refer to
the beginning and end of the algorithm. An algorithm must possess
following characteristics:
(1) Finiteness : Finiteness implies that the algorithm must have
finite number of steps. Also the time taken to execute all the
steps of the algorithm should be finite and within a reasonable
limit.
(2) Definiteness : By definiteness it is implied that each step of the
algorithm must specify a definite action i.e., the steps should not
be vague. Moreover, the steps should be such that it is possible
to execute these manually in a finite length of time.
(3) Input : The term input means supplying initial data for an
algorithm. This data must be present before any operations
can be performed on it. Sometimes no data is needed because
initial data may be generated within the algorithm. Thus the
algorithm may have no or more inputs. Generally, the initial
data, is supplied by a READ instruction or a variable can be
given initial value using SET instruction.
(4) Output : The term output refers to the results obtained when
all the steps of the algorithm have been executed. An algorithm
must have at least one output.
(5) Effectiveness : Effectiveness implies that all the operations
involved in an algorithm must be sufficiently basic in nature so
that they can be carried out manually in finite interval of time.

1.7.1 Expressing Algorithms

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 7

The procedure for expressing algorithm is quite simple. The language


used to write algorithms is similar to our day-to-day life language. In
addition, some special symbols are also used which are described below:
(a) Assignment Symbol ( ! ). The assignment symbol ( ! ) is used
to assign values to various variables. For example, let A be any
variable and B be another variable or constant or an expression.
Then the statement
A!B
is called assignment statement. The statement implies that A is
assigned the value stored in B. If A contains any previous value
then that value is destroyed and the new value is assigned.
(b) Relational symbols : The commonly used relational symbols for
algorithms are:
Symbol Meaning example
< Less than A<B
<= Less than or equal to A <= B
= Equal to A=B
! Not equal to A!B
> Greater than A>B
>= Greater than or equal to A >= B

(c) Brackets ({}). The pair of braces is used to write comments for
the purpose of documentation. For example,
(a) BEGIN {Start of the algorithm}
(b) Set N ! N + 1 {Increase the value of N by 1}
(c) END {End of the algorithm}

1.7.2 Basic Control Structures


The basic control structures needed for writing good and efficient
algorithms are:
(a) Selection : The selection structure is used when we have to
perform a given set of instructions if the given condition is TRUE
and an alternative set of instructions if the condition is FALSE.
The basic statement available for selection is IF-THEN-ELSE.
(b) Branching : The branching statement is required when we want
to transfer the control of execution from one part or step of the
algorithm to another part or step. The statement available for
branching is GOTO and its syntax is GOTO n where n is a
positive integer and specifies the step number where the control
of execution is to be transferred.
(c) Looping : The looping structure is used when a statement or a
set of statements is to be executed a number of times.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 8 Basic Concepts Chapter 1

Advantage of Algorithms
(1) It is simple to understand step by step solution of the problem.
(2) It is eacy to debug i.e., errors can be easily pointed out.
(3) It is independent of programming languages.
(4) It is compatible to computers in the sense that each step of
algorithm can be easily coded into its equivalent in high level
language.

1.8 FLOWCHART

A flowchart is a pictorial representation of the sequence of operations


necessary to solve a problem with a computer. The first formal flowchart
is attributed to John Von Neumann in 1945. The flowcharts are read
from left to right and top to bottom. Program flowcharts show the
sequence of instructions in a program or a subroutine. The symbols
used in constructing a flowchart are simple and easy to learn. These are
very important planning and working tools in programming.

1.8.1 Flowchart Symbols


Flowcharts have only a few symbols of different sizes and shapes for
showing necessary operations. Each symbol has specific meaning and
function in a flowchart. These symbols have been standardized by the
American National Standards Institute (ANSI). The basic rules that a
user must keep in mind while using the symbols are:
(1) Use the symbols for their specific purposes.
(2) Be consistent in the use of symbols.
(3) Be clear in drawing the flowchart and the entries in the symbols.
(4) Use the annotation symbol when beginning a procedure.
(5) Enter and exit the symbols in the same way.

1.8.2 Flowchart Symbols


Flowcharts have only a few symbols of different sizes and shapes for
showing necessary operations. Each symbol has specific meaning and
function in a flowchart. These symbols have been standardized by the
American National Standards Institute (ANSI). The basic rules that a
user must keep in mind while using the symbols are:
(1) First consider the main logic, then incorporate the details.
(2) Maintain a consistent level of detail for a flowchart.
(3) Do not include all details in a flowchart.
(4) Use meaningful descriptions in the flowchart symbols. These
should be easy to understand.
(5) Be consistent in using variables and names in the flowchart.
(6) The flow of the flowchart should be from top to bottom and
from left to right.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 9

(7) For a complex flowchart, use connectors to reduce the number


of flow lines. The crossing of lines should be avoided as far as
possible.
(8) If a flowchart is not drawn on a single page, it is recommended
to break it at an input or output point and properly labelled
connectors should be used for linking the portions of the flowchart
on separate pages.
(9) Avoid duplication so far as possible.
The flowchart symbols along with their purposes are given below:

Different Ways of Using Decision Symbol

Here, the criterion for making the decision is clearly indicated in


the decision box. The condition is properly identified and executed so
that the desired path will be chosen depending upon the result of the
execution.
Advantages of Using Flowcharts
(1) Communication: Flowcharts are a better way of communicating
the logic of a system to all concerned.
(2) Effective Analysis: With the help of flowcharts, problems can be
analyzed more effectively.
(3) Proper Documentation: Program flowcharts serve as a good

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 10 Basic Concepts Chapter 1

program documentation needed for various purposes.


(4) Efficient Coding: Flowcharts act as a guide or blueprint during
the systems analysis and program development phase.
(5) Proper Debugging : Flowcharts help in the debugging process.
(6) Efficient Program Maintenance : The maintenance of an
operating program becomes easy with the help of a flowchart.
Limitations of Using Flowcharts
(1) Complex Logic : Sometimes, the program logic is quite
complicated. In such a case, a flowchart becomes complex and
clumsy.
(2) Alterations and Modifications: If alterations are required, the
flowchart may need to be redrawn completely.
(3) Reproduction: Since the flowchart symbols cannot be typed in,
the reproduction of a flowchart becomes a problem.
(4) Loss of Objective: The essentials of what has to be done can
easily be lost in the technical details of how it is to be done

1.9 PSEUDO CODE

Pseudocode is a semiformal description of the steps to be carried out by


the computer, including steps that are to be repeated and decisions that
are to be made. There is more than one way of writing an algorithm in
pseudocode.
Pseudocode can’t be compiles and nor executed. It has no
standard syntax rule. Once, you have completed the pseudocode and it
is accepted, then it can be written in the syntax form of a programming
language.
A algorithm in flowchart is shown in figure. Another more detailed
and mathematical way of describing this algorithm in pseudocode would
be:

total ! 0.0
count ! 0
for each input data value found
If data value > 0 (precondition: a data value was found)
total ! total + data value
count ! count + 1
Endif
Endfor
average ! total/count (precondition: positive data value was found)
print average
Stop

Note that several assumptions have been made: that there is at


least one positive measurement, that the measurement is a real number
rather than an integer (total is initialized to 0.0 rather than 0), and

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 11

that a measurement of 0 doesn’t count.


The processing of a data value depends on the value being positive,
which in turn depends on an input value being found. This is shown by
the two levels of indentation in the pseudocode.
Convention for Writing Pseudocode
(1) Summations and counters must be initialized to zero, and other
variables that require initial values must also be initialized.
(2) Assignment of values is shown by an arrow pointing to the left.
(3) The beginning and the end of any selected calculation is indicated
as well as the basis for including or excluding it.
(4) The beginning and the end of any repetition is indicated, as well
as the basis for continuing and/or stopping the repetition.
(5) Conditional steps and repetition steps are indented.
(6) Either words or arithmetic operations may be used for arithmetic.
(7) The algorithm termination must be clearly indicated.

1.10 PROGRAMMING LANGUAGE CLASSIFICATION

A language is a medium for communication. The languages we speak are


called natural languages. A programming language is a subset of the set
of natural languages. It contains all the symbols, characters, and usage
rules that permit a human being to communicate with computers. A
variety of programming languages have been invented over the years of
computer history. However, every programming language must accept
certain types of written instructions that enable a computer system to
perform a number of familiar operations
The programming languages can be divided into two major
categories: Low Level and High Level languages. The low level languages
can be further divided into Machine Language and Assembly Language.
Thus, all Computer Languages can be classified in the following
three broad categories:
1. Machine Language
2. Assembly Language
3. High level Language
ʇ NOTE
1.11 MACHINE LANGUAGE Writing machine language
programs is a very cumbersome
Machine Language is the language directly understood by a computer. and complicated task because all
the information fed to computer
In other words, the binary language (the language of 0s and 1s) is
has to be in numeric form and
the Machine Language. This language is understood by the computer that too in binary language. So
without using a translation program. Any information or instruction in only experts can write machine
language programs.
this language is to be represented in terms of 0s and 1s, the symbol 0
standing for the absence of an electric pulse and 1 for the presence of
an electric pulse. As a computer is able to recognize the presence and
absence of an electric pulse, it is able to understand machine language.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 12 Basic Concepts Chapter 1

For example, a sequence of 0’s and 1’s such as 11001010 has a specific
meaning for a computer although it may appear as an ordinary binary
number to us.
Advantages of Machine Language
(1) Programs written in machine language can be executed very
fast by the computer because the instructions are understood
directly by the computer and no translating program is required.
(2) It is highly suited for small computers having limited memory.
Limitations of Machine Language
(1) Machine dependent. The machine language is machine dependent
i.e., it is different from computer to computer and depends
upon the actual design of the ALU (Arithmetic Logic Unit),
the Control Unit and the size as well as the word limit of the
memory unit.
(2) Difficult to use. It is difficult to understand and develop a
program using machine language. For any-body checking such a
program, it would be difficult to forecast the output when it is
executed. Nevertheless, computer hardware recognizes only this
type of instruction code.
(3) Error prone. It is hard to understand and remember the various
combinations of 1’s and 0’s representing data and instructions.
This makes it difficult for a programmer to concentrate fully on
the logic of the problem, thus frequently causing errors.
(4) Difficult to debug and modify. Checking machine instructions
to locate errors are about as tedious as writing the instructions.
Further, modifying such a program is highly problematic.
Following is an example of a machine language program for
adding two numbers.

1.12 ASSEMBLY LANGUAGE

When symbols such as letters, digits, or special characters are employed


for the operation, operand, and other parts of the instruction code,
the representation is called an assembly language instruction. Such
representations are known as mnemonic codes; they are used instead
of binary codes. A program written with mnemonic codes forms an
assembly language program. This is considered to be a second generation
language (2GL).
Machine and assembly languages are referred to as low-level
languages since the coding for a problem is at the individual instruction
level. Each computer has its own assembly language that is dependent
upon the internal architecture of the processor.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 13

Advantages of Assembly Language over Machine Language


(1) It is easier to understand and use because mnemonics are used
for operation codes and symbolic addresses or variables are used
for memory addresses.
(2) Fewer errors are committed while programming in Assembly
Language as compared to Machine Language programming.
Moreover, it is also easier to locate errors and hence correct
them.
(3) It is easier to modify programs written in Assembly Language
as compared to Machine Language programs. Moreover,
modification in one part do not require changes in subsequent
sections as in machine language.
(4) Besides being easier to read, write and understand the efficiency
of Assembly Language is almost the same as Machine Language
because there is one-one correspondence between the instructions
of an assembly language program and its corresponding machine
language program.
Disadvantages of Assembly Language
(1) It is machine dependent i.e., it is designed for a specific make
and model of the processor being used.
(2) An intermediate translating program is required to convert the
assembly language instructions into their binary form and this
increases the overhead.
(3) An assembly language program cannot be executed on small
sized computers.
(4) There is no standardization of assembly languages.
Assembler :
A computer can only understand machine language and no other
language. Hence, the programs written is other languages must be
translated into the machine language of the computer. Such translation
is performed with the help of a software. A program which translates
an assembly language program into a machine language program is
called Assembler. An Assembler which runs on a computer for which
it produces object codes (Machine code) is called a self Assembler
(or Resident Assembler). The Assembler is actually a complicated
program written in machine language. A program written in assembly
language is called Source Program. The assembler converts the source
program into machine language program known as object program. In
fact an Assembler is a look-up table which contains machine language
equivalent of the mnemonics and memory addresses used in assembly
language programs.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 14 Basic Concepts Chapter 1

Working of an Assembler :
An assembly language program i.e., the source program is fed to the
computer through an input device. The assembler program present in
the computer memory translates this source program to an equivalent
machine language program called the object program by translating
one instruction at a time.

Figure 1.2 : Working of Assembler

In fact the assembler reads the program twice. During first reading
it develops the table of names used in the source program, assigns and
stores the numerical address for each name. Then in the second reading
it translates the instructions into machine language and generates the
object program. The object program is stored on the disk. The errors
in the program like syntax errors are also pointed out during assembly
process. Such an assembler is called Two-Pass Assembler. There is also
One-Pass Assembler which reads the assembly program only once.

1.13 HIGH LEVEL LANGUAGE

With the development of assembly language, the process of writing


programs became easier. The programs were also easy to read and
understand. This was made possible by the use of mnemonics instead
of numeric codes and use of symbolic addresses instead of numeric
addresses. But even with these developments the assembly language
continued to be slow, inefficient and cumbersome (difficult to
understand). Therefore search for better languages continued.
We know that in order to write good computer programs the
programmer should basically be concerned with the logic of the
program. But while writing programs in machine language or assembly
language the programmer had to concentrate more on the internal
structure of the computer. So in order to facilitate the programmers to
use computers without the need to know in detail the internal structure
of the computer, High level languages were developed. So, the high level
languages enabled the programmers to concentrate more on the logic
and less on the intricacies of the computer. It is for this reason that
high level languages are also known as Problem-oriented languages.
High level languages are basically symbolic languages that use
English words and Mathematical symbols than mnemonic codes. This
makes programs written in high level languages easy to read, write and
understand. Every instruction which the programmer writes in a high
level languages is translated into many machine language instructions.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 1 Basic Concepts Page 15

This is one-to-many translation and not one-to-one as in the case of


assembly language. Few examples of high level languages are: Basic,
Cobol, Fortran, Pascal, C, C++.
Advantages of High Level Languages
(1) The high level languages being similar to commonly used
languages in our day-to-day work, are quite easy to learn and
use.
(2) High level languages are machine independent i.e., a program
written in a high level language can be run on many different
types of computers with very little or practically no effort.
(3) Fewer errors are committed while writing programs in high level
language because of the simplicity of syntax.
(4) It is easier to modify and maintain programs written in high
level languages.
Disadvantages of High level Languages
(1) Programs written in a high level language take more time to
run and require more storage. Hence, they are less efficient as
compared to machine or assembly language programs.
(2) High level languages are less flexible as compared to machine
or assembly language. Therefore, some tasks are not possible in
high level languages.
Compiler
We know that the computer only understands machine language. So
a program written in high level language needs to be translated into
machine language before it can be executed by the computer. This job
of translation is done with the help of a software program. This program
in case of a high level language is known as a compiler. A compiler is so
called because for every program instruction of a high level language,
it compiler is so called because for every program instruction of a high
level language, it compiles a set of machine language instructions. A
program written in a high level language is known as source program.
The program obtained after compilation is known as the object program.

Figure 1.3 : Working of Compiler

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 16 Basic Concepts Chapter 1

REVIEW QUESTIONS ALGORITHMS

1.1 What do you mean by a program? 1.21 Write a algorithms to find the biggest of three
1.2 Distinguish between system software and application numbers.
software. 1.22 Given three sides A, B, C of a triangle. Write a
1.3 State the advantages and disadvantages of machine algorithms to find the area (if possible). S denotes
language and assembly language. the semi perimeter.
1.4 Compare and contrast assembly language and high- 1.23 Draw a algorithm for solving a given quadratic
level language. equation.
1.5 What are different phase of basic model of
programming?
1.6 Explain different types of computer language in FLOWCHARTS
details.
1.7 What is pseudocode. Write the advantage ane 1.24 Draw a flowchart for swapping two numbers without
limitation of pseudocode. using a temporary variable.
1.8 State the advantages and disadvantages of machine 1.25 Draw a flowchart for checking a year for leap year.
language and assembly language. (If a year is divisible by 4 and not divisible by 100,
1.9 What is a translator? or, if the year is divisible by 400, it is a leap year)
1.10 What are the differences between a compiler and 1.26 Draw a flowchart to find out the biggest of three
an interpreter? numbers.
1.11 What is a structured code? 1.27 Draw a flowchart for printing the multiplication
table of an integer.
1.12 What is an algorithm?
1.28 Draw a flowchart for generating first n _n $ 2i
1.13 What is top-down analysis? Describe the steps
fibonacci terms (Fibonacci terms are 0, 1, 1, 2, 3,
involved in top-down analysis.
5, 8, 13, 21 ...).
1.14 What are the advantage and disadvantage of
1.29 Draw a flowchart for checking an integer for prime
flowcharts?
number.
1.15 What are the benefits of algorithms. Describe the
1.30 Draw a flowchart for solving a given quadratic
characteristic of good algorithms.
equation.
1.16 What is the difference between compiling and
1.31 Draw a flowchart for finding the area of a triangle
linking?
and its type (that is equilateral, isosceles or scalene).
1.17 What is bug?
1.32 Draw a flowchart for simulating a simple calculator
1.18 What do you mean by language translator. Explain (that is performing +, –, ×, /).
with example.
1.33 Draw a flowchart describing the process of creation
1.19 Differentiate ROM and PROM. to execution of a program.
1.20 List the most important differnece between 1.34 Draw a flowchart for finding the biggest and smallest
(1) Assembler, Compiler and Interpreter of given set of numbers in an array.
(2) Machine, Assembly and High Level Language 1.35 Draw a flowchart for addition of two matrices.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

2
INTRODUCTION TO C

2.1 INTRODUCTION

C is a versatile, flexible, and powerful programming language that was


designed and developed in 1972. It is a robust language whose rich
set of built-in functions and operators can be used to write complex
programs. The C compiler combines the features of assembly language
and high-level language which makes it best suited for writing system
software as well as business packages. Some basic characteristics of C
language that defines the language and have lead to its popularity as a
programming language are as follows.
(1) C is well suited for structured programming. C enables the
users to think of problem in terms of functions/modules where
the collection of all the modules makes up a complete program.
This feature facilitates easiness in program debugging, testing,
and maintenance.
(2) A high level programming language enables the programmer to
concentrate on the problem at hand and not worry about the
machine code on which the program would be run.
(3) C is a small language C has only thirty-two keywords (and
only about twenty of them are in common use). This makes it
relatively easy to learn compared to bulkier languages.
(4) C makes extensive use of function calls.
(5) It supports loose typing (as a character can be treated as an
integer and vice versa).
(6) It is stable language. ANSI C was created in 1983 and since
then it has not been revised.
ʇ NOTE
(7) C is quick. We can write codes which run quickly, and the A program written to increment
program can be very ‘close to the hardware’. By that, you a value from 0-15000 using
can access low level facilities in your computer quite easily, BASIC would take 50 seconds
whereas a C program would do
without the compiler or runtime system stopping you from the same in just 1 second.
doing something potentially dangerous.
(8) It facilitates low level (bitwise) programming.
(9) It supports pointers to refer computer memory, array, structures,
and functions.
(10) C is a core language as many other programming languages

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 18 Introduction To C Chapter 2

(like C++, Java, Perl, etc.) are based on C. If you know C,


learning other computer languages becomes much easier.
(11) C is a portable language. C program written for one computer
can be run on another computer with little or no modification.
(12) C is an extensible language. It enables the user to add his own
functions to the C library.
(13) Derived data types such as arrays, character strings, and
structures are available to handle complex data types. This
makes it possible to store sets of data in the computer so that
they can be processed repeatedly without reentering them.

2.2 USES OF C

C is a very simple language that is widely used by software professionals


ʇ NOTE
around the globe. C is often treated as the second best language for Basically, C was designed as
any given programming task. While the best language depends on the a programming language and
was not meant to be used as
particular task to be performed, the second best language, on the other a compiler target language.
hand, will always be C. The uses of C language can be summarized as Therefore, although C can be
follows. used as an intermediate language
it is not an not an ideal option.
(1) C has been so widely accepted by professionals that compilers, This led to the development of
libraries, and interpreters of other programming languages are C-based intermediate languages
often implemented in C. such as C– –.
(2) C language is primarily used for system programming. The
portability, efficiency, the ability to access specific hardware
addresses and low runtime demand on system resources makes
it a good choice for implementing operating systems and
embedded system applications
(3) For portability and convenience reasons, C is sometimes used
as an intermediate language for implementations of other
languages. Examples of compilers who use C this way are BitC,
Gambit, the Glasgow Haskell Compiler, Squeak, and Vala.
(4) C is widely used to implement end-user application.

2.3 STRUCTURE OF A C PROGRAM

A C program comprises different sections which are shown in figure 2.1.


(1) Preprocessor Directives : The preprocessor directive contain
ʇ NOTE
special instruction that indicate how to prepare the program All preprocessor commands
for compilation. One of the most important and commonly start with symbol hash (#).
used preprocessor command is include which tell the complier
that to execute the program, some information is needed from
the specified fiile. The file should be included using #include
directive as given below.
#include <stdio.h> or #include “stdio.h.”
In this example, <stdio.h> file is included, i.e. all the definitions

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 2 Introduction To C Page 19

and prototypes of function defined in this file are available in


the current program. This file is also compiled with original
program.
Preprocessor Directives
Global Declaration section
/* comments */
/****************************************************/
main()/*main function*/
{
/* comments */
Declaration part
Executable part
}

user_defined_funcion()
(
/* comments */
Declaration part
Executable part
}
/****************************************************/

Figure 2.1 : Structure of C Program

(2) Global Declaration: This section declares some variables that


are to be used in more than one function. These variables
are known as global variables. This section must be declared
outside of all the functions.
(3) Function main() : Program written in C language contains a
main() function. Arguments, if needed, are specified within the
parentheses following the function name main. The function
main() is a starting point of every C program. The execution
of the program always begins with the function main(). Except
the main() function, other sections may not be necessary.
The program execution starts from the opening brace } and
ends with the closing brace }. Between these two braces, the
programmer should declare declaration and executable parts.
(4) Declaration Part: The declaration part declares the entire
variables that are used in executable part. The initialization of
variables is also done in this section. The initialization means
providing initial value to the variables.
(5) Executable Part : This part contains the statements following
the declaration of the variables. It also contains a set of
statements or a single statement.
(6) User-defined function: The functions defined by the user are
called user-defined functions. These functions are generally
defined after the main() function. They can also be defined before

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 20 Introduction To C Chapter 2

main() function. This portion is not compulsory. Programmer


can follow this concept in the chapter on Functions.
(7) Comments : Comments are not necessary in the program.
ʇ NOTE
However, to understand the flow of programs, programmers can The user can frequently use
include comments in the program. They are to be inserted by any number of comments that
the programmer, and it is useful for documentation. The clarity can be placed anywhere in the
program.
of the program can be followed if it is properly documented.
Comments should be placed between the delimiters /* and */.
The compiler does not execute comments. Thus, we can say
that comments are not the part of executable programs.

2.4 C PROGRAMMING RULES

To write any C Program following rule must be keep in mind :


(1) Statements should be written in lower case letters. Upper case
letters are only used for symbolic constants.
(2) Blank spaces may be inserted between the words. This improves
the readability of the statements. However, it is not used while
declaring a variable, keyword, constant and functions.
(3) It is not necessary to fix the position of statement in the program,
i.e. the programmer can write the statement anywhere between
the two braces following the declaration part. The user can also
write one or more statements in one line separating them with
semicolon (;). The following statements are valid.
a = b+c;
d = d*c;
or
a = b+c;d=b*c;

(4) The opening and closing braces should be balanced, i.e. if


opening braces are four, then closing braces should also be
four.

2.5 WRITING THE FIRST C PROGRAM

To write a C program, we first need to write the code. For this, open
ʇ NOTE
a text editor. If you are a Windows user you may use Notepad Once Unix\Linux user can use emacs
the text editor is opened on your screen, type the following statements: or vi.

/*****************************************************************************/
#include <stdio.h>
int main()
{
printf(“\nWelcome to the world of C”);
return 0;
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 2 Introduction To C Page 21

 OUTPUT :
Welcome to the word of C

Description of different part is as follows:


ʇ NOTE
#include <stdio.h> The standard input/output
header file contains functions
This is a preprocessor command that comes as the first statement in for input and output of data
our code. The #include statement tells the compiler to include the like reading values from the
standard input/output library or header file (stdio.h) in the program. keyboard and printing the
results on the screen.
This file has some in-built functions. So simply by including this file in
our code we can use these functions directly.
int main()
int is the return value of the main function. After all the statements in
the program have been written, the last statement of the program will
return an integer value to the operating system.
{}The two curly brackets are used to group all the related
statements of the function main. All the statements between the braces
form the function body. The function body contains a set of instructions
to perform the given task.
printf(“/n Welcome to the world of C”);
The printf function is defined in the stdio.h file and is used to
print text on the screen. The message that has to be displayed on the
screen is enclosed within double quotes and put inside brackets.
The message is quoted because in C a text (also known as a string
or a sequence of characters) is always put between inverted commas.
The ‘\n’ is an escape sequence and represents a newline character. It
is used to print the message on a new line on the screen.
return 0;
This is a return command that is used to return the value 0 to the
operating system to give an indication that there were no errors during
the execution of the program.

2.6 FILES USED IN A C PROGRAM

Every C program has four kinds of files associated with it. These are
shown in figure 2.2.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 22 Introduction To C Chapter 2

Figure 2.2 : Files in a C Program

2.6.1 Source Code File


The source code file contains the source code of the program. The file
extension of any C source code file is .C. This file contains C source
code that defines the main function and other functions. The main() is
the starting point of execution when you successfully compile and run
the program.
ʇ NOTE
2.6.2 Header Files In C, the usual convention is to
give header files names that end
A header file is a file containing C declarations and macro definitions to with .h. It is most portable to
be shared between several source files. You request the use of a header use only letters, digits, dashes,
and underscores in header file
file in your program by including it, with the C preprocessing directive names, and at most one dot.
#include. Header files serve two purposes.
(1) System header files declare the interfaces to parts of the
operating system. You include them in your program to supply
the definitions and declarations you need to invoke system calls
and libraries.
(2) Your own header files contain declarations for interfaces
between the source files of your program. Each time you have a
group of related declarations and macro definitions all or most
of which are needed in several different source files, it is a good
idea to create a header file for them.
ʇ NOTE
Including a header file produces the same results as copying the Missing the inclusion of
header file into each source file that needs it. Such copying would appropriate header file in the C
be time-consuming and error-prone. With a header file, the related program will generate an error.
Such a program may compile
declarations appear in only one place. If they need to be changed, they but the linker will give an error
can be changed in one place, and programs that include the header message as it will not be able
file will automatically use the new version when next recompiled. to find the functions used in the
program
The header file eliminates the labor of finding and changing all the
copies as well as the risk that a failure to find one copy will result in
inconsistencies within a program.

2.6.3 Object Files


Object files are generated by the compiler as a result of processing the
source code file. Object files contain compact binary code of the function
definitions. Linker uses this object file to produce an executable file
(.exe file) by combining the of object files together. Object files have
a ‘.o’ extension, although some operating systems including Windows
and MS-DOS have a ‘.obj’ extension for the object file.

2.6.4 Binary Executable File


The binary executable file is generated by the linker. The linker links

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 2 Introduction To C Page 23

the various object files to produce a binary file that can be directly
executed. On Windows operating system, the executable files have
‘.exe’ extension.
ʇ NOTE
2.7 COMPILING AND EXECUTING C PROGRAMS While the C program is human-
readable, the executable file on
C is a compiled language. So once the C program is written, you must the other hand, is a machine-
readable file available in an
run it through a C compiler that can create an executable file to be run
executable form.
by the computer. The process of compilation and execution is shown
in figure 2.3.

Figure 2.3 : Compilation and Execution Process

Creating of Program :
The program should be written in C editor. The file name does not
necessarily include extension .C. The default extension is .C. The user
can also specify his own extension.
ʇ NOTE
Compilation and Linking a Program : All the given steps can be
performed using menu options
With alt-c keys, the source program statements should be translated of the editor.
into object program, which is suitable for execution by the computer.
The translation is done after correcting each statement as per C syntax.
If there is no error, compilation proceeds and translated program is
stored in another file with the same file name, but with an extension
.obj. If at all errors are there, the programmer should correct them.
The linking is also an essential process. It puts all other program files
and functions together that are required by the program. For example,
if the programmer is using pow() function, then the object code of
this function should be brought from math.h library of the system and
linked to the main() program.
Executing the Program :
After the compilation, the executable object code will be loaded in the
computers main memory and the program is executed. This is done
with keys alt-r.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 24 Introduction To C Chapter 2

REVIEW QUESTION definition.


2.5 Why do we include <stdio.h> in our programs?
2.1 What do you mean by a program? 2.6 Why do we need header files?
2.2 Distinguish between system software and application 2.7 What is library?
software.
2.8 What are the advantage and disadvantage of C
2.3 What are the rules for writing a c program? language?
2.4 Explain the difference between declaration and 2.9 Write the Structure of a C program.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

CONSTANT, VARIABLE AND DATA TYPE


3
3.1 INTRODUCTION

A programming language is designed to help process certain kind of data


consisting of numbers, character and string and to provide useful output
know as information. The task of processing of data is accomplished by
ʇ NOTE
executing a precise instruction called a program. These instruction are Every program instruction must
formed using certain symbols and words according to some rigid rule confirm precisely to the syntax
rules of the language.
known as syntax rule.
Similar to other programming languages, a C program also uses
data types, constants, variables delimiters, and data type modifiers to
execute the program. A variable is the basic entity of a program, and
can be defined as an arbitrary placeholder for storing data. A variable
must be assigned a data type, which specify the type of data that
the variable can store. For example a variable of int data type can
store integer values. However, in case you need to keep the value of a
constant, then you should declare the variable as constant by using the
const type quantifier. Similarly, data type modifiers either double the
size or use half the size of the data type during the execution of the
program. You can use delimiters in your program, which consists of one
or two tokens used to separate language variable.
ʇ NOTE
3.2 CHARACTER SETS Whitespaces are generally
ignored by the compiler, as
In the C programming language, characters play a very crucial role they are not the part of string
constant. Whitespaces can be
as you write a C program by using the set of characters in one or
used to separate words; however,
more source files. These set of characters are used to form the lexical they are not used between
elements. Table 3.1 lists the character sets available in the C language. keywords and identifiers.

TABLE 3.1 : The C Character Sets

Character Set Categories Name of the Character Set Symbol


Alphabet characters Upper case A to Z
Lower case a to z
Digits character Digits 0 to 9
Special characters Comma ,

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 26 Constant, Variable and Data Type Chapter 3

Character Set Categories Name of the Character Set Symbol


Period .
Semicolon ;
Colon :
Question mark ?
Apostrophe ‘
Quotation mark “
Underscore _
Hash/Number sign #
Dollar sign $
Percentage sign %
Pipeline character |
Slash /
Backslash \
Ampersand &
Tilde ~
Caret ^
Asterisk *
Plus sign +
Minus sign -
Less than <
Greater than >
Left parenthesis (
Right parenthesis )
Left bracket [
Right bracket ]
Left brace {
Right brace }

3.3 TOKENS

The C tokens refer to the smallest unit of a C program. In other words,


a token is the text provided in the source program that cannot be
broken down into elements. The following are the noteworthy C tokens:
(1) Keywords ( float, while )
(2) Identifiers ( amount, salary)
(3) Constants ( 100, -234 )

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 27

(4) Strings (“ABC”, “month” )


(5) Operators (+, -, * )
(6) Special Symbols ( {}, [] )
ʇ NOTE
3.3.1 Keywords You must keep in mind the C
keywords. while specifying a
Keywords are reserved words that cannot be used while naming a legal identifier.
variable or function. In other words, keywords are the words having
special meaning to the C compiler. Table 3.2 lists the keywords of the
C language along with their description.

TABLE 3.2 : Keywords of C

Keyword Description
Auto Defines a local variable having local lifetime
break Allows to pass the control out of block
case Used in switch statements to mark blocks of text
char Refers to a data type that holds characters
const Used to define constants
continue Sends control back to the top of a loop
default Specifies the default block of code in a switch statement
do starts a do-while loop
double Refers to a data type that holds 64-bit floating-point numbers
else Indicates an alternative branch in the if statement
enum Refers to a class of constants that represents fixed choices
extern Indicates that an identifier is defined elsewhere
float Represents a single precision floating point data type
for Provides iteration facility repeatedly
goto Used to jump the control from one part of program to another
if Used to execute specified statements if the specified condition is true
int Refers to a data type that holds integer type values
long Refer to a data type that holds the long type values
register Informs the compiler Ato store the variable that is declared in a CPU register
return Returns the value to calling function
short Refers to the type modifier
signed Refers to the type modifier that holds the signed type values of a data type
sizeof Returns the size (in bytes) of a specified parameter
static Preserves the value of a variable even after its scope ends
struct Groups variables in a single record

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 28 Constant, Variable and Data Type Chapter 3

Keyword Description
switch Represents multiple branching statement
typedef Assigns symbol name to data type definition
union Groups the variables sharing the same storage space
unsigned Refers to the type modifier that holds the unsigned type values of a data type
void Represents the empty data type
volatile Indicates that variable can be changed by background routine
while Repeats the execution of a block, if the condition remains true

ʇ NOTE
3.3.2 Identifiers Identifiers, as the name suggests
helps us to identify data and
Identifiers are basically the names given to program elements such as other objects in the program.
variables, arrays, and functions. Identifier may consist of an alphabet,
digit, or an underscore.
Rules for Forming Identifier Names :
Some rules have to be followed while forming identifier names. They
are as follows:
(1) Identifier name must begin with an alphabet or an underscore.
(2) It cannot have a C reserved keyword.
(3) It cannot include any special characters or punctuation marks
(like #, $, ^, ?, ., etc.) except the underscore ‘_’.
(4) There cannot be two successive underscores.
(5) The case of alphabetic characters that form the identifier name
is significant. For example, “FIRST” is different from ‘first’ and
‘First’.
 PROGRAMMING TIPS
(6) Identifiers can be of any reasonable length. They should not Although it is a good practice to
contain more than 31 characters. It can actually be longer than use meaningful identifier names,
31, but the compiler looks at only the first 31 characters of the it is not compulsory. Good
identifiers are descriptive but
name. short. To cut short the identifier,
As a general practice, if the identifier is a little long, then you may you may use abbreviations.
use an underscore to separate the parts of the name or you may use
capital letters for each part.
Examples of valid identifiers are:
roll_number, marks, name, emp_number, basic_pay,
ltc, hra, DA, dept_code, DeptCode, RollNo, EMP_NO
ʇ NOTE
Examples of invalid identifiers are: C is a case-sensitive language.
Therefore rno, Rno, RNo,
45_student, %marks, @name, #emp_no,
RNO are different considered as
basic.pay, -HRA, (DA), &dept_code, auto identifiers.

3.3.3 Constants

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 29

ʇ NOTE
A constant is a fixed value assigned to a variable, which cannot be Later we will discuss in details
modified in a program. It can be a number, character, or a character about constants.
string that may be used in a program. The constants are also known as
constant literals. In the C program, you can declare a constant by using
the const keyword, as shown in the following statement:
const int id_number = 2474;
In this statement, the id_number is a constant variable declared
by the const keyword and it is assigned as a fixed value, 2474. You
cannot modify the value of a constant in a program.

3.3.4 Strings
The string literals are the characters from the source character set and
are enclosed within the double quotation marks (“ ”). The following
statement shows a simple string literal:
char *display = “Computer Programming”;
In this statement, the char type pointer, display, is declared and
assigned the string Literal value.
ʇ NOTE
3.3.5 Operators We will discuss in detail about
operator in next chapter.
The word operator explains itself as something that is used to perform
some operation. Any expression consists of an operator and operand.
An operator acts upon the operand. In the C language, there are the
following three types of operators:
(1) Unary Operators: Consists of a unary operator pre-appended
with an operand.
(2) Binary Operators: Consists of two operands joined by the binary
operator.
(3) Ternary Operators: Consists of three operands joined by the
conditional expression operator.
Within the binary operators, the arithmetic operators are the most
commonly-used operators. The following are the arithmetic operators
used in a C program:

TABLE 3.3 : Arithmetic Operator in C Language

Operator Operation
* Multiply
+ Addition
/ Division
- Subtraction
% Modulus

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 30 Constant, Variable and Data Type Chapter 3

3.4 DATA TYPE

A data type defines the type of data that is stored in a variable. The
data in a variable can be of any type. For example, the data can be
either numeric or string. A data type determines how much storage
should be allocated to a variable. It also determines the permissible
operations on variables. C has some built-in data types for which the
programming language offers built in support. The built-in data types
are also called basic or primary data types. Table 3.4 lists the built-in
data types supported by C on a 16 bit machine.

TABLE 3.4 : Built - In Data Type in C

Types Data Type Description Size Range


(Keyword)
Character char Stores a single character 1 Byte Signed: -128 to +127
Unsigned: 0 to 255
Integer int Stores whole numbers 2 Bytes Signed: -32768 to +32767
Unsigned: 0 to 65535
Real float Stores real numbers 4 Bytes 3.4 e-38 to 3.4 e+38
(floating-point) that has single precision
floating-point
Double double Stores real numbers that 8 Bytes 1.7e-308 to 1.7e+308
precision has double precision
floating-point floating-point
Non-specific void Stores no value - -

Apart from these built-in data types, the C language also offers
other data types, which are called data type modifiers or data qualifiers.
The data modifiers provide precision to the data.
ʇ NOTE
3.4.1 char Data Type ASCII is acronym for the
American Standard Code for
The char data type is used to store character type data. A char data Information Interchange. It is
type takes 1 byte for storage. It can store data that can be either a a code for representing english
characters as numbers, with
character constant or a string constant. each letter assigned a number
A character constant is a single character enclosed within a from 0 to 127. For example, the
pair of single quotes. For example ‘A’, ‘s’, ‘@’, ‘4’. The character ASCII code for uppercase M is
77. Most computers use ASCII
constant can be either signed or unsigned. The signed characters are codes to represent text, which
those characters that have values in the range of -128 to +127 whereas, makes it possible to transfer
the unsigned characters have values in the range from 0 to 255. Each data from one computer to
another.
character constant contains an integer value, which is provided by
the ASCII (American Standard Code for Information Interchange)
character set. Table 3.5 lists some of the character constants along with
their corresponding ASCII values:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 31

TABLE 3.5 : Character Constants and their ASCII Values

Character Constant ASCII Value


‘a’ 97
‘s’ 115
‘M’ 77
‘D’ 68
‘1’ 49
‘3’ 51
‘@’ 64
‘?’ 63

A string constant is a sequence of characters enclosed within


a pair of double quotes. For example “software”, “Programming”,
“competitive”. A string constant should always be terminated by a
null character (\0). The null character indicates the end of a string
constant.

3.4.2 int Data Type


The int data type is used to store whole numbers, which are a set
of non-negative integers including 0. The range for an int data type
ʇ NOTE
depends on the word length defined for a computer. A word length refers to the
In case of an 8 - bit computer, the range of int data type can be number of bits of data a
computer is allowed to read or
 28  1 <= integer number <= 28  1  1 or write at a single time.
 128 <= integer number <= 127 .
This means that an 8-bit computer can have an input of maximum
integer value of either  128 or 127 . Similarly, a 16 bit computer can
have an integer range from  32768 to 32767.
Table 3.6 lists the valid and invalid integers for a 16 bit computer.

TABLE 3.6 : List of Valid and Invalid Integers

Valid Integer Invalid Integer


-250 4,442 (comma not allowed)
15053 -31.89 (decimal point not allowed)
28216 +3,728.2 (comma and decimal point not allowed)
+1800 88888888 (out of valid range of the int data type)
0
32763

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 32 Constant, Variable and Data Type Chapter 3

ʇ NOTE
3.4.3 float Data Type The scientific notation, also
called the mantissa-exponent
The float data type is used to store real numbers that have a single notation, is a method of writing
precision floating point. Floating-point numbers are numbers that numbers that holds values
that are too large or small to
contain a decimal point either to the left or to the right of an integer. be written easily in standard
These numbers can be expressed in decimal notation (in the form of decimal notation.
decimals) or in scientific notation. Table 3.7 lists some valid and invalid
floating-point numbers:

TABLE 3.7 : List of Valid and Invalid Floating-Point Numbers

Valid Invalid
-261.218 4,4 (comma not allowed)
2.43130E+02 -1.8.9 (two decimal points are not allowed)
0.0233333E+04 -999999999.999999 (out of valid range )
25313.8E+04 -+18.88 (two successive operators are not allowed)

In table 3.7, if you look at the Valid Floating-Point Number


column, the first example is in decimal notation and the rest of the
examples are in scientific notation. The character E stands for exponent.
You can use the scientific notation in situations where the given
data is either too large or too small. For example, if the specified
number is 0.000000000017, then you must use the scientific notation to
represent this number. In scientific notation, you can write the number
as either 1.7×10-11 or as 1.7E-11.

3.4.4 double Data Type


ʇ NOTE
The double data type is used to store real numbers that have a double- A float data type stores a
precision floating-point. The precision is related with the accuracy of maximum of 6 digits after the
decimal point whereas a double
data. When you require more accuracy in representing the floating- data type stores 16 digits after
point numbers, you must use the double data type. A double data type the decimal point. For example,
value is similar to a normal float data type value. However, the number 215.0000003456287654,
0.7384900076001239.
of digits stored after the decimal point is double the digits stored in
case of the float data type.

3.4.5 Void Data Type


The void data type stores no values and therefore you cannot perform
ʇ NOTE
any operations on a variable that is declared as void. It is the only Unlike all other data types, the
non-specific data type in C. It is typically used to return the result void data type neither has a size
nor any permissible range.
of a function that contains no return value. A function is a set of
instructions which performs some actions and returns a value to the
calling function. When a function returns no value, you can declare its
return type as void.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 33

3.5 CONSTANTS

A constant is an entity that does not change during the execution of


program. C support several type of constants is shown in figure 3.1

Figure 3.1 : Constant Type

3.5.1 Integer Constant


It represents a whole number. It displays a sequence of digits without
any decimal point. It can be prefixed with a plus (+) or a minus (-)
sign. Figure 3.2 displays the general form of an integer constant:

Figure 3.2 : Format of Integer

In figure 3.2, sign indicates the optional plus or a minus sign


where the plus sign indicates positive numbers and minus sign refers
negative numbers. Digits are a sequence of numbers. Examples of
integer constants are 240, 1, -3221, +12, -32010, 7773.

3.5.2 Floating-point Constants


It represents a number that has a decimal point. It displays a sequence
of digits preceded and followed by a decimal point. It can be with
either a plus or a minus sign. Figure 3.3 displays the general form of a
floating-point constant:

Figure 3.3 : Format of Floating Point

In figure 3.3, sign indicates the optional plus or minus sign. Integer
portion is a sequence of numbers prior to a decimal point. Decimal point

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 34 Constant, Variable and Data Type Chapter 3

is a period symbol and fractional portion is a sequence of numbers after


a decimal point.
Examples of floating-point constants are -221.06, +14.75,
0.0007, 52.0, 6664.231, -0.00174.

3.5.3 Character Constants


A single character constant or simply character constant contains a
single character enclosed within a pair of single quotes. Examples of
ʇ NOTE
character constants are The character constant ‘5’ is not
‘5’, ‘n’, ‘!’, ‘C’, ‘ ’ (blank space character). the same as the number 5.

Since each character constant represent an integer value, it is


possible to perform arithmetic operation on character constant.
ʇ NOTE
3.5.4 String Constants Note that character constant
(e.g. ‘X’ ) is not equivalent
A string constant is a sequence of characters enclosed within a pair of to the single character string
double quotes. Examples of string constants are constant (e.g. “X” ). Further, a
single character string constant
“Hello”, “2009”, “y+4”. does not have an equivalent
integer value while a character
constant has an integer value.
3.6 VARIABLES

A variable is an entity whose value changes during the execution of a


ʇ NOTE
program. The variables are the names provided to values to identify the As a variable is used to identify
programming elements. Variables also refer to a specific location in the a value, therefore, variables are
also called identifiers.
memory where data can be stored easily. Each variable has a name and
data-type. All the variables must have their type indicated so that the
compiler can record all the necessary information about them, generate
the appropriate code during translation, and allocate the required space
in the memory. You can use variables to represent constants, functions,
arrays, and the names of files. Examples of variable names are age,
name, address, marks, and area.
While providing variable names, follow the following naming
conventions for identifiers:
(1) Use a proper variable name to indicate the data it stores.
(2) Use an alphabet or an underscore (_) as the first character of
a variable name and all the succeeding characters as letters and
digits.
ʇ NOTE
(3) The case of alphabetic characters that form the identifier name Use lowercase variable names
is significant. For example, “FIRST” is different from ‘first’ and in C. However, you can also
‘First’. use both uppercase as well as
lowercase variable names.
(4) Blank spaces, keywords, and special characters are not allowed
to name a variable.
Table 3.8 lists some valid and invalid variable names:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 35

TABLE 3.8 : List of Valid and Invalid Variable Names

Valid Variable Name Invalid Variable Name


age 9xyz (variable name cannot start with a number)
ANNUAL_SALARY ANNUAL SALARY (Blank space not allowed)
net_salary_2012 netsalary,2012 (comma not allowed)
diameter_of_circle Diameter-of-circle (special characters not allowed)
str[45] Circle’s_Circumference (special character not allowed)

3.6.1 Declaring Variables


In a C program, prior to using a variable, you must first declare it.
Declaration does two things :
1. It tell the compiler what the variable name is.
2. It specify what type of data the variable will hold.
The syntax for declaring a variable in C is as follows:
data_type variable_list;
where, data_type refers to a built-in data type such as int, char, float,
or double and variable_list refers to a list of one or more variables
of data type data_type. In case there are more than one variable, then
they must be separated by commas.
You must always remember to terminate a variable declaration by
a semicolon (;). The following are the examples of declaring variables:
int age;
float diameter;
char chr;
double salary;
int a, b, c;
float arr[34];
char marks[10];
int color[4];

3.6.2 Assigning Values to Variables


Once you have declared a variable, the next step is to assign a value to
that variable. As you know, the variables hold some memory location
where the data is actually stored. You can assign a value to a variable
by using the (=) assignment operator. The syntax for assigning values
to a variable is as follows:
variable_name = value;
where variable_name refers to the name of the variable where the
value is actually stored and value refers to the value that is used to
initialize the variable. Here = is assignment operator.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 36 Constant, Variable and Data Type Chapter 3

You can assign a value to a variable by using two methods. In


the first method, you can specify an initial value to a variable within
the declaration part itself. When you initialize a variable within the
declaration part, it is called initialization. In the case, you must specify
a data type when you declare and initialize the variable. The following
are some examples of declaring and initializing a variable using a single
statement:
int y = 3;
float salary = 0.0;
char chr = ’A’;
double y = 0.1362;

In the second method, the value is assigned to the variable in


the execution section of the C program. The following are some of the
examples in which you can simply assigned the value to a variable that
was previously declared:
y = 4;
salary = 4000.00;
name = “james”;
chr = ‘N’;
a = b = c = 4;

Multiple Assignment :
You can assign a single initial value to multiple variables using a
single assignment statement. This type of initialization requires more
than one assignment operator. Therefore, such assignments are called
multiple assignments. Let’s now take an example in which you initialize
three variables a, b, and c of int data type with the value as 20.
The following statements snippet shows the initialization of the three
variables by using the single assignment statement:
int a = 20;
int b = 20;
int c = 20;

The following statement provides the same example by using the


multiple assignment operators:
int a = b = c = 20;
In the above statement, the multiple assignment operators is used
to initialize the three integer variables a, b, and c to 20.

3.7 CONST AND VOLATILE QUALIFIRES

American National Standards Institute (ANSI) C, which is a standard


defined for the C programming language, has introduced two new type
qualifiers called const and volatile. Both these type qualifiers are
independent of each other. The const type qualifier is used to specify

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 37

a constant value in a variable and the voltile type qualifier is used to


instruct the C compiler to alter the value of the variable by using some
outside factor.

3.7.1 const Type Qualifier


Using the const type qualifier, you can keep the value of a variable
as constant during the execution of a program. Once you declare a
variable by using the const type qualifier, you cannot change its value
later in the program. Any attempt to change its value would result in
an error. The following statements are the examples of using the const
type qualifier:
const float PI = 3.142;
const int size = 90;

The first example indicates the compiler that the value stored
in the float variable PI is 3.142, which you cannot change during
the execution of a program. Similarly, the second example instructs
the compiler that the constant value in the variable size must not be
changed during the program execution.

3.7.2 volatile Type Qualifier


Using the volatile type qualifier, you can instruct the C compiler
that the value in the variable might change at any time by any outside
factor. The following statements are the examples of using the volatile
type qualifier:
volatile int b;
volatile int y[30];

In the above statements, the first example indicates that the value
of the variable b can be changed any time by any external factor.
Similarly, the second example indicates that the values in the integer
array y can be changed in many ways, and by any factor undetected by
the C compiler.

3.8 DATA TYPE MODIFIER

All the built-in data types except the void data type can easily be
ʇ NOTE
modified by using a series of type modifiers. As you know, the double The data type modifiers are also
data type is used for accuracy in real numbers. Similarly, you can known as qualifiers.
obtain accuracy for integer type data by using some modifiers. The
data type modifiers are divided into the following four types:

3.8.1 Signed
It indicates that the value stored in a variable is capable of storing

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 38 Constant, Variable and Data Type Chapter 3

ʇ NOTE
negative values. The signed characters are those characters that have By default, in case a data type
values in the range of -128 to +127. The signed data type modifier also modifier is not specified, then
the signed data type modifier is
applies to a char data type to create a small integer. In some cases, char applied to all data types except
is declared unsigned, which means that it can contain integers from 0 the void data type.
to 255. The following statement declaring an int data type as signed is:
signed int y;

3.8.2 unsigned
It indicates that the value stored in a variable is capable of storing only
positive values. The unsigned characters are those that have values in
the range of 0 to 255. For example, the age of a person can never be
a negative number. Therefore, when you declare the variable age, the
following statement is used to declare the variable as unsigned:
unsigned int age;

3.8.3 long
In a C program you can increase the storage capacity of a variable from
the storage capacity of the basic data type. For that, you must use
the data type modifier long. Using the long data type modifier, you
can double the storage capacity of the data type that you are using
to declare a variable. For example, the following statement is used to
declare a variable salary of int data type with the long data type
modifier:
long int salary;
By default, an int data type has a storage capacity of 2 bytes,
but when you use a long data type modifier with the int data type the
storage capacity increases to 4 bytes. Therefore, in the above statement,
the variable salary now has a storage capacity of 4 bytes.

3.8.4 short
A short data type modifier reduces the storage capacity of a data type
to half of its basic storage capacity. Let’s again take the example of the
age variable. The following statement is used to declare the variable
age of int data type with the short data type modifier:
short int age;
With the above statement, the variable age now has a storage
capacity of 1 byte and has a data range of 128 to 127. Table 2.9 list
the storage capacity and the range of values these data type modifiers
have in combination with the data types on a 16 bit computer:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 39

TABLE 3.9 : Data Type Modifiers along with their Size and Range on a 16 bit Computer

Data Type Modifier Usage Size (in Bytes) Range of Values


int 2 -32768 to +32767
signed int 2 -32768 to +32767
unsigned int 2 0 to 65535
short int 1 -128 to 127
long int 4 -2147483648 to 2147483647
float 4 -3.4 E +38 to +3.4 E +38
double 8 -1.7 E +308 to +1.7 E +308
char 1 -128 to +127
signed char 1 -128 to +127
unsigned char 1 0 to 255
unsigned short int 1 0 to 255
unsigned long int 4 0 to 4294967295
long double 10 -3.4 E -4932 to +1.1 E +4932

3.9 BACKSLASH CONSTANT

A backslash constant is always a combination of two characters where


the first character is always the backslash (\) character and the second
character is one of the following: a, b, f, n, r, t, v, ‘, “,\, and 0. The
backslash character is also known as the escape sequence and used in
output statements. Table 3.10 lists the backslash character constants:
TABLE 3.10 : Backslash Character Constants

Backslash Character Constant Description


‘\a’ Represents a system alarm (bell)
‘\b’ Represents backspace
‘\f’ Represents form feed
‘\n’ Represents new line (line feed)
‘\r’ Represents carriage return (CR)
‘\t’ Represents horizontal tab (contains fixed set of space)
‘\v’ Represents vertical tab
‘\”’ Represents double quote
‘\’’ Represents single quote
‘\0’ Represents null character (end of string)
‘\\’ Represents back slash character (\) itself

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 40 Constant, Variable and Data Type Chapter 3

3.10 SYMBOLIC CONSTANT

A symbolic constant is a name that can be used as a substitute for


a numeric constant, a character constant or a string constant. For
example, while calculating the area of a circle, you use the formula
area = 3.142*circle_radius*circle_radius.
In the above statement formula, you can replace the numeric
constant 3.142 with the symbolic constant named PI. Therefore, the
formula can be written as:
area = PI*circle_radius*circle_radius
ʇ NOTE
In the above statement, you replace PI for a numeric constant. At Typically, a symbolic constant
the time of compilation, every occurrence of PI is replaced by the value should always be written in
of PI. You can use symbolic constants in your C program by defining uppercase. However, it is not
mandatory. You must define
it to use the preprocessor statement #define, as shown in the following symbolic constants at the
example: starting of a program that is
prior to the main() function of
#define PI 3.142; C program.
#define NAME “Harry”;
#define AGE 34;

3.11 DELIMITERS

A set of one or more characters that defines the boundary between


the basic programming elements is known as delimiters. They are also
referred as separators as they are used to separate constants, variables,
and statements. The commonly used delimiters are comma, semicolon,
double quotes, single quote, and blank space. Table 3.11 lists the
delimiters available in C:

TABLE 3.11 : List of Delimiters in C

Name of the Delimiter Symbol


Opening bracket (

Closing bracket )

Opening square bracket [

Closing square bracket ]

Opening braces {

Closing braces }

Comma ,

Semicolon ;

Colon :

Period .

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 3 Constant, Variable and Data Type Page 41

REVIEW QUESTIONS many type of variables are supported by C?


3.8 What are the rules for naming a variable? Explain
3.1 What are variables? with examples.
3.2 What does the data type of a variable signify? 3.9 What is a constant? Explain different types of
3.3 What do you understand by identifiers and constants available in C.
keywords? 3.10 What is a variable? How are keywords different
3.4 Explain the following: (i) Constants (ii) Variables from them?
(iii) Symbolic constants. 3.11 Explain different ways in which variables can be
3.5 What are the primary data types in C? Indicate assigned values.
the range for each one of them assuming a 16-bit 3.12 What is the purpose of the qualifiers const and
machine. volatile as per ANSI standard?
3.6 Why do we need signed and unsigned char? 3.13 What is the difference between a character constant
3.7 Explain the terms variables and constants? How and a string constant? Do string constants represent
numerical values?

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

OPERATORS AND EXPRESSIONS


4
4.1 INTRODUCTION

Operators in C are symbols, which are used to perform not only


arithmetic calculations such as, addition, subtraction, multiplication,
ʇ NOTE
or division but also logical computations. The operators specify the The values that are operated
type of operation that needs to be applied. on by operators are called
operands.
The combination of variable and constants along with the C
operators, create expressions. In other words, operators take more
than one expression or operand to perform arithmetic and logical
computations on it. The expressions are evaluated by using the operator
precedence rules, which determine the order in which the operators in
an expression are evaluated.

4.2 WORKING WITH OPERATORS

An operator is a symbol in C, such as +, -, &&, or ==, which helps


the user to perform several mathematical and logical computations.
As operator is used basically to work upon certain data and produce
an output as a result of the operation. The operators included in the
C programming language are used to operate not only on numbers
but also on data and variables. The operators in C are classified into
various types. They are:
1. Unary Operators
2. Assignment Operators
3. Arithmetic Operators
4. Increment and Decrement Operators
5. Relational Operators
6. Logical Operators
7. Bitwise Operators
8. Conditional Operators
9. Special Operators
10. Shorthand Assignment Operators

4.3 UNARY OPERATORS

The unary operators in C are used to act upon only one operand, to

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 43

produce a new value. The unary operators appear before the operand
and are associated with the operand from left to right. The most
commonly used unary operator in C is the unary minus operator. In
the unary minus operator, a minus sign precedes the operand assigning
a negative value to the operand. For example,
a = 3;
b = 4;
c = a + (-b);

In this case, the value of c, when calculated, is -1. This is because


b, which initially has a positive value, is changed to negative when
preceded by the unary minus operator. Let’s consider the Program 4.1
to understand the unary operator in C.

/*****************************************************************************/
/* Program 4.1 : Using the Unary Operator */
/*****************************************************************************/

#include <stdio.h>
void main()
{
int a , b;
int sub;
a = 5;
b = 3;
sub = a + -b;
printf(“The subtraction of a and b is = %d.“, sub);
getch();
}

/*****************************************************************************/

 OUTPUT :
The subtraction of a and b is 2.

 EXPLANATION :
When you run the Program 4.1, you get the output as 2. This is because, b. which is
a positive value, is assigned a negative unary operator.

ʇ NOTE
4.4 ASSIGNMENT OPERATORS Here you may be confused
by the statement a=a+c.
Assignment operators are used for assigning a new value to a variable. In programming this is not
equality. Here it mean that
The equal sign (=) is the assignment operator in C. When the C
we have assign a+c to a. For
compiler encounters an = sign, it processes the statement on the right example if value of a and c are
side of the operator and then assigns the result to the variable on the 4 and 5, then after execution of
this statement value of a will be
left side of the operator. 4+5=9.
The general format for an assignment operator is

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 44 Operators and Expressions Chapter 4

var = expression;
Some example of assignment operator are shown below
a = a + c; a = b + c*d;
i = i + 2; i = j + 2;

You can also use arithmetic operators in C to assign a single


value to multiple variables in one statement as shown in the following
expression:
i = j = k = 10;
which assigns the value 10 to i, j, and k. Let’s consider the Program
4.2 to understand the assignment operators in C.

/*****************************************************************************/
/* Program 4.2 : Using the Assignment Operators */
/*****************************************************************************/

#include<stdio.h>
main()
{
int a,b,c,d;
printf(“ENTER VALUES OF a,b, c, d :\n”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
a = a + b*c + d;
printf(“\na = %d”,a);
getch();
}

/*****************************************************************************/

 OUTPUT :
ENTER VALUES OF a,b, c, d :
5 5 7 8
a = 48

 EXPLANATION :
When you run the expression given in Program 4.2, you are asked to provide values
for a, b, c, and d. As you provide the values, a computed value of a is displayed. You
will get the value 48, which is evaluated in the following manner:
1. 5*7 gives 35.
2. 5+35+8 gives 48 which is assign to a.

Shorthand Assignment Operator


You can use the assignment operators of C in a compact manner in
an expression. These compact expressions are known as the shorthand
assignment operators. The shorthand way of working with operators is
also associated with arithmetic operators and bitwise operators. The
various shorthand assignment operators used in C are listed in Table 4.1:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 45

TABLE 4.1 : Shorthand Assignment Operators

Operator Assignment Shorthand Assignment


+ a = a + b a+= b;
- a = a - b a-= b;
* a = a *b a*= b;
/ a = a/b a/= b;
% a = a % b a%= b;
& a = a & b a&=b;
| a = a | b a|= b
^ a = a ^ b a^= b;

The use of shorthand assignment operator has three advantages :


(1) The statement is more concise and easier to read.
(2) The statement is more efficient
(3) What appear on the left-hand side need not be repeated and
therefore it becomes easier to write.
Let’s consider the Program 4.3 to understand the shorthand
assignment operators in C.

/*****************************************************************************/
/* Program 4.3 : Using the Shorthand Assignment Operators */
/*****************************************************************************/

#include <stdio.h>
void main()
{
int x, y, z;
printf(“\nEnter Values of x, y, z : ”);
scanf(“%d%d%d”,&x,&y,&z);
x+=y; /* Statement A */
y-=z; /* Statement B */
z*=x; /* Statement C */
printf(“\nx = %d”, x);
printf(“\ny = %d”, y);
printf(“\nz = %d”, z);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter Values of x, y, z: 5 8 10

x = 13
y = -2
z = 130

 EXPLANATION :

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 46 Operators and Expressions Chapter 4

Program ask to enter the values of x, y and z. After the statement A the value of
x(5+8) is 13. After the statement B the value of y (8-10) is -2. After the statement
C the value of z (10*13) is 130.

4.5 ARITHMETIC OPERATOR

C has all the basic type of arithmetic operators. They are listed in
Table 4.2.

TABLE 4.2 : Arithmetic Operator in C

Operator Example Function


+ a+b Addition or unary Plus
- a-b Subtraction or unary minus
* a*b Multiplication
/ a/b Division
% a%b Modulo Division

The +, -, *, and \ arithmetic operators perform the usual arithmetic


operations in a C program. However, the % (modulo) operator is
used to return the remainder value after dividing two integers. The %
operator cannot be used for float data type or double data type. If both
operands a and b are integers then the expression a/b provides integer
division. Even if the target is a floating point variable, it provides
ʇ NOTE
integer division. The arithmetic operators have the normal precedence During modulo division, the
rules as follows: sign of the result is always the
sign of the first operand (the
1. Unary operators like -, + are evaluated. dividend). That is
2. The multiplication (*) and division (/,%) operators are -17 % 4 = -1
evaluated. -17 % -4 = -1
-17 % -4 = -1
3. The addition (+) and subtraction (-) operators are evaluated. 17 % -4 = 1
4. The assignment operator is evaluated. 17 % 4 = 1

5. The expressions are evaluated from left to right for unary


operators.
Let’s consider the Program 4.4 to understand the arithmetic
operators in C.

/*****************************************************************************/
/* Program 4.4 : Using the arithmetic operators */
/*****************************************************************************/

#include<stdio.h>
main()
{
int a,b,c,d;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 47

int sum, sub, mul, rem;


float div;
printf(“Enter Values of b, c, d : ”);
scanf(“%d%d%d”, &b,&c,&d);
sum = b + c;
sub = b - c;
mul = b*c;
div = b/c;
rem = b%d;
a = b/c * d;
printf(“\nsum = %d, \nsub = %d, \nmul = %d, \ndiv = %f”, sum, sub, mul, div);
printf(“\nRemainder of division of b & d is %d.”, rem);
printf(“\n a = %d”,a);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter Values of b, c, d : 10 5 3
sum = 15
sub = 5
mul = 50
div = 2.000000
Remainder of division of b & d is 1.
a = 6

 EXPLANATION :
In Program 4.4 you have the expression a = b/c * d. In this expression both / and
* have the same priority. Since, the expression is evaluated from left to right, so first
b/c is evaluated. After evaluating the expression b/c * d, the value is assigned to a
because the assignment operator has an order of evaluation right to left, which implies
that the right expression in first evaluated.

4.6 INCREMENT AND DECREMENT OPERATORS

You can increment or decrement the value of a variable by using the


ʇ NOTE
increment (++) or decrement (--) operator. The increment operator Increment and Decrement
is used to add 1 to its operand and the decrement operator is used to Operators are unary operators
subtract 1 from its operand. In other words, the increment operator
increases the value of an integer by 1 and the decrement operator
decreases the value of the integer by 1. These operators can be applied
only to variables by using either the prefix form or the postfix form.
When prefix form is used, the value of the variable is either
incremented or decremented first and is then assigned. However, in
the postfix form, the value is used and only after the assignment
operator has performed the operation, that the value is incremented or
decremented.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 48 Operators and Expressions Chapter 4

The following are example of using the increment and decrement


operator in prefix form
a = ++b; i = --j;
The above both statement are equal to following assignment
statements:
b = b + 1; a = b;
j = j - 1; i = j;

The following are example of using the increment and decrement


operator in post form
a = b++; i = j--;
The above both statement are equal to following assignment
statements:
a = b; b = b + 1;
i = j; j = j - 1;

Let’s consider the Program 4.5 to understand the increment and


decrement operators:

/*****************************************************************************/
/* Program 4.5 : Using the Increment and Decrement Operators */
/*****************************************************************************/

#include<stdio.h>
void main()
{
int i, j, k, l, m, n;
i = 7;
j = 3;
k = i++ + -j;
l = ++i + -j;
m = i-- + -j;
n = --i + -j;
printf(“i = %d,\tj = %d”, i, j);
printf(“\nk = %d, \tl = %d, \tm = %d, \tn = %d”, k, l, m, n);
getch();
}

/*****************************************************************************/

 OUTPUT :
i = 7, j = 3,
k = 4, l = 6, m = 6, n = 4

 EXPLANATION :
In Program 4.5, first value of i = 7 is used and then incremented. So we get the
value of k as follows
k = 7 + -3 = 4
Now the value of i is 8. In next statement value of i first incremented and then used.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 49

So we get the following output


l = 9 + -3 = 6
Now the value of i is 9. In next statement value of i=9 is used then decremented. So
we get the following output
m = 9 + -3 = 6
Now the value of i is 8. In next statement value of i is first decremented and then
used. So we have the following output
n = 7 + - 3 = 4

4.7 RELATIONAL OPERATORS

The relational operators allow us to compare two values and check


if they are equal to each other, unequal, or if one is greater than the
other. The relational operators return a true or false value depending
upon whether the condition the two entities hold or not. The relational
operator also returns either zero or non zero values. The zero value is
taken as false while the non zero value is taken as true. The different
relational operators in C are shown in Table 4.3
ʇ NOTE
TABLE 4.3 : Relational Operator While using the == relational
operator, you should be
Operator Example Meaning very careful, as it can be
misunderstood with the =
< a<b a is less than b assignment operator. For
<= a <= b a is less than or equal to b example, if you want to compare
a and b for equality, then you
> a>b a is greater than b should write a == b, not a =
b because a = b means you are
>= a >= b a is greater than or equal to b assigning value of b to a.
== a == b a is equal to b
!= a != b a is not equal to b

Let’s consider the Program 4.6 to understand the relational


operators in C:

/*****************************************************************************/
/* Program 4.6 : Using the Relational Operators */
/*****************************************************************************/

#include <stdio.h>
void main()
{
int x, y;
printf(“\nEnter value of x and y :”);
scanf(“%d%d”,&x,&y);
if(x == y)
printf(“x and y are equal.\n”);
if(x < y)
printf(“x is less than y.\n”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 50 Operators and Expressions Chapter 4

if(x > y)
printf(“x is greater than y.\n”);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run 1
Enter value of x and Y : 56 78
x is less than y.

Run 2
Enter value of x and Y : 45 23
x is greater than y.

Run 3
Enter value of x and Y : 45 45
x and y are equal.

 EXPLANATION :
Program is self explanatory. Depending on the value of x and y, respective message
is displayed.

4.8 LOGICAL OPERATORS

You can combine the results of multiple relations or logical operations


by using logical operators. The logical operators are
&& meaning logical AND
|| manning logical OR
! meaning logical NOT
The logical operator && and || are used when we want to test
more than one condition and make decision. The AND operator returns
a value 1 if both expressions are true and the OR operator returns the
value 1 if either of the expression is true. The negation operator takes
only one operand and returns a false value if the operand is true and
vice-versa. It can be explained in a better way by using Table 4.4:

TABLE 4.4 : Logical Operators


R1 R2 R1 && R2 R1 || R2 ! R1
TRUE TRUE TRUE TRUE FALSE
TRUE FALSE FALSE TRUE FALSE
FALSE TRUE FALSE TRUE TRUE
FALSE FALSE FALSE FALSE TRUE

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 51

Let’s consider the program in Program 4.7 to understand the


logical operators in C.

/*****************************************************************************/
/* Program 4.7 : Using the Logical Operators */
/*****************************************************************************/

#include<stdio.h>
void main()
{
int x, y, z;
printf(“\nEnter Values of x, y and z : ”);
scanf(“%d%d%d”,&x,&y,&z);
if((x < y)&&(x < z))
printf(“\nx is less than y and z.”);
if(!(x < y))
printf(“\nx is greater than y.”);
if((x < y)||(x < z))
printf(“\nx is less than y or z or both.”);
getch();
}

/*****************************************************************************/

 OUTPUT :
RUN 1
Enter Values of x, y and z : 16 91 33
x is less than y and z.
x is less than y or z or both.

Run 2
Enter Values of x, y and z : 34 23 43
x is greater than y.
x is less than y or z or both

Run 3
Enter Values of x, y and z : 54 23 12
x is greater than y.

 EXPLANATION :
When you run the program in Program 4.7, you are asked to enter the values for x,
y, and z, based on which the result will be returned.

4.9 BITWISE OPERATORS

As the name suggest, bitwise operator are those operators that perform
operations at bit level. These bitwise operators assume operands as
ʇ NOTE
string of bits and the bit operations are done on this operand. The Bitwise operator may not be
different bitwise operators have been explained in detail in Table 4.5: applied to float or double.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 52 Operators and Expressions Chapter 4

TABLE 4.5 : Bitwise Operators in C

Operator Explanation
& Compares each bit of the first operand with the corresponding bit of the second
operand. If both bits are 1, then the corresponding bit is set to 1, else it is set to 0.
| Compares each bit of the first operand with the corresponding bit of the second
operand. If either of the bit is 1, the result is set to 1, otherwise the result is set to 0.
^ Compares each bit of the first operand with the corresponding bit of the second
operand. If one bit is 0 and the other bit is 1, the result is set to 1, otherwise the
result is set to 0.
~ Assigns every bit that is 1 in the operand as 0 in the result and vice-versa.
<< Shifts their first operand to its left.
>> Shifts their first operand to its right.

4.10 CONDITIONAL OPERATORS

Conditional operators, more commonly called the ternary operators


(? :) in C are used to return values that are based on the outcome of
relational expressions. For example, in case you want to return value 1
if the expression is True or return value 2 if the expression is False then
you can use Ternary operator. The syntax for conditional operators in
C is:
e1 ? e2 : e3
In the above syntax, first, e1 is evaluated, which if true, and then
e2 is evaluated, which then becomes the result of the expression. If e1
is false, then e3 is evaluated, which, then becomes the result of the
expression.
Let’s consider the Program 4.8 to understand the conditional
operator in C.

/*****************************************************************************/
/* Program 4.8 : Using the Conditional Operator */
/*****************************************************************************/
#include<stdio.h>
void main ()
{
int a = 35;
int b = 95;
int result1;
int result2;
result1 = a > b ? a : b;
result2 = a < b ? a : b;
printf(“The value of result1 is =%d\n”, result1);
printf (“The value of result2 is = %d\n”, result2);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 53

getch();
}

/*****************************************************************************/

 OUTPUT :
The value of result1 is = 95
The value of result2 is = 35

 EXPLANATION :
In this program a > b is false and a < b is true. So in first case b is selected and in
second case a is selected.

4.11 SPECIAL OPERATORS

Along with the preceding operators, there are also some special operators
that are used in C. The special operators in C are used to perform
certain special functions, for instance combining multiple expressions
into a single expression. The special operators in C are:
1. The comma operator
2. The sizeof() operator

4.11.1 The Comma Operator


The comma operator in C is used to combine multiple expressions
into a single expression. It can be used to link the related expression
together. A comma-linkded list of expressions are evaluated left to right
and the value of right most expression is the value of the combined
expression. For example
x = (a = 12, b = 22, a + b);
first assign the value 12 to a, then assign 22 to b, and finally
assigns 44 (i.e. 12 + 22) to x. Since comma operator has the lowest
precedence of all operator, the parentheses are necessary. Let’s consider
the Program 4.9 to clearly understand the comma operator in C.

/*****************************************************************************/
/* Program 4.9 : Using the Comma Operator */
/*****************************************************************************/
#include<stdio.h>
main()
{
int i, j, k;
k = (i = 4, j = 5);
printf(“i = %d , j = %d, k = %d”, i, j, k);
getch();
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 54 Operators and Expressions Chapter 4

 OUTPUT :
i = 4, j = 5, k = 5

 EXPLANATION :
Here, the expression is evaluated from left to right, that is i = 4 is evaluated first,
then j = 5 is evaluated. The value of right most expression is specified as output;
therefore, k will get the value 5.

4.11.2 The sizeof() Operator


The sizeof() operator in C is used to determine the size of the operand.
The operand in this case, can be a constant, a variable, or a data type.
The basic functioning of the sizeof() operator is to determine the
size of arrays and structures in C. Let’s consider the Program 4.10 to
understand the sizeof() operator in C.

/*****************************************************************************/
/* Program 4.10 : Using the sizeof() Operator */
/*****************************************************************************/

#include <stdio.h>
void main()
{
int x;
float y;
x = 1000;
y = 800.0;
printf(“size of x = %d\n”, sizeof(x));
printf(“Size of y = %d\n”, sizeof(y));
getch();
}

/*****************************************************************************/

 OUTPUT :
size of x = 2
size of y = 4

 EXPLANATION :
Since x is integer so it require 2 bytes of storage and y is float which require 4 byte,
so the output is 2 and 4.

4.12 OPERATOR PRECEDENCE IN C

C operators have two properties: priority and associativity. When an


expression has more than one operator then it is the relative priorities

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 55

of the operators with respect to each other that determine the order in
which the expression will be evaluated.
Associativity defines the direction in which the operator having the
same precedence acts on the operands. It can be either left-to-right or
right-to-left. Priority is given precedence over associativity to determine
the order in which the expressions are evaluated. Associativity is then
applied, if the need arises.
Table 4.6 lists the operators that C language supports in the order
of their precedence (highest to lowest). The associativity indicates the
order in which the operators of equal precedence in an expression are
evaluated.

TABLE 4.6 : Operator Precedence in C

Category Operator Operation Precedence Associativity


Highest () Function call 1 L –> R
precedence [] Array subscript (left to right)
-> C indirect component selector
:: C scope access/resolution
. C direct component selector
Unary ! Logical negation (NOT) 2 R –> L
~ Bitwise (1’s) component (right to left)
+ Unary plus
- Unary minus
++ Preincrement or postincrement
-- Predecrement or postdecrement
& Address
* Indirection
sizeof (return size of operand, in bytes)
Member access .* Dereference 3 L –>R
–>* Dereference
Multiplication * Multiply 4 L –> R
/ Divide
% Remainder (modulus)
Additive + Binary plus 5 L –> R
- Binary minus
Shift << Shift left 6 L –> R
>> Shift right
Relational < Less than 7 L –> R
<= Less than or equal to
> Greater than
>= Greater than or equal to
Equality == Equal to 8 L –> R
!= Not equal to
Bitwise AND & Bitwise AND 9 L –> R
Bitwise XOR ^ Bitwise XOR 10 L –> R

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 56 Operators and Expressions Chapter 4

Category Operator Operation Precedence Associativity


Bitwise OR | Bitwise OR 11 L –> R
Logical AND && Logical AND 12 L –> R
Logical OR || Logical OR 13 L –> R
Conditional ?: (a?x:y means “if a then x, else y”) 14 R –> L
Assignment = Simple assignment 15 R –> L
*= Assign product
/= Assign quotient
%= Assign remainder (modulus)
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
Comma ‘ Evaluate 16 L –> R

The program 4.11 illustrate the some operator precedence.

/*****************************************************************************/
/* Program 4.11 : Calculation of simple interest and compound interest */
/*****************************************************************************/
#include <stdio.h>
#include <math.h> /* For the function pow */
void main()
{
float p, t, r, ncmp_year;
float simple, compound, cmp_amount;
printf(“\nPrincipal : ”);
scanf(“%f”, &p);
printf(“Rate : ”);
scanf(“%f”,&r);
printf(“Time : ”);
scanf(“%f”, &t);
printf(“Compoundings per year : ”);
scanf(“%f”, &ncmp_year);
simple = p * t * r/100;
/* Calculate the amount resulting from compound interest. */
cmp_amount = p * pow(1 + r/(ncmp_year*100), ncmp_year * t);
/* Compute the compound interest from the amount and principal */
compound = cmp_amount - p;
printf(“\nThe simple interest is: %f”, simple);
printf(“\nThe compound interest is: %f”, compound);
getch();
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 57

 OUTPUT :
Run 1:
Principal : 2000
Rate : 12
Time : 3
Compoundings per year : 4
The simple interest is : 720.000000
The compound interest is : 851.521729

ʇ NOTE
4.13 TYPE CONVERSION AND TYPECASTING Type conversion is implicit
type conversion, also known as
Till now we have assumed that all the expressions involved data of the coercion. It is an automatic type
conversion by the compiler
same type. But what happens when expressions involve two different
whereas, typecasting has to
data types, like multiplying a floating point number and an integer. be done explicitly by the
Such type of situations are handled either through type conversion or programmer.
typecasting.
Type conversion or typecasting of variables refers to changing a
variable of one data type into another. Type conversion is done implicitly
whereas, typecasting has to be done explicitly by the programmer.

4.13.1 Type Conversion


Type conversion is done when the expression has variables of different
data types. To evaluate the expression, the data type is promoted from
lower to higher level where the hierarchy of data types (from higher
to lower) can be given as: double, float, long, int, short, and char.
Figure 4.1 shows the conversion hierarchy of data types.

Figure 4.1 : Conversion hierarchy of data types

Type conversion is automatically done when we assign an integer

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 58 Operators and Expressions Chapter 4

value to a floating point variable. Consider the code given below in


which an integer data type is promoted to float. This is known as
ʇ NOTE
promotion (when a lower level data type is promoted to a higher type). In some cases, when an integer
float x; is converted into a floating point
number, the resulting floating
int y = 5; point number may not exactly
x = y; match the integer value. This
is because the floating point
Now, x = 5.0, as automatically integer value is converted into number format used internally
its equivalent floating point representation. Let us summarize how by the computer cannot
accurately represent every
promotion is done:
possible integer number. So even
(1) char or short operands whether signed or unsigned are converted if the value of x = 4.99999995,
to int. you must not worry. The loss of
accuracy because of this feature
(2) float operands are converted to double.
would be always insignificant
(3) If any one operand is double, the other operand is also converted for the final result.
to double. Hence, the result is also of type double.
(4) If any one operand is long, the other operand is also converted
to long. Hence, the result is also of type long.
Figure 4.2 exhibits type conversions in an expression.

Figure 4.2 : Type Conversion


ʇ NOTE
Consider the following group of statements. Similarly, if we convert an
float flt = 4.5; integer to a short integer or a
long int to int, or into to char,
int i; the compiler just drops the
i = flt; extra bits

The statement i = flt results in flt to be demoted to type int, i.e.,


the fractional part of flt will be lost and i will contain 4 (not 4.5). In
this case demotion takes place, i.e., a higher level data type is converted
into a lower type. Whenever demotion occurs, some information is
 PROGRAMMING TIPS
lost. For example, in this case the fractional part of the floating point No compile time warning
number is lost. message is generated when
information is lost while
demoting the type of data.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 59

4.13.2 Typecasting
Typecasting is also known as forced conversion. Typecasting an
ʇ NOTE
arithmetic expression tells the compiler to represent the value of the Typecasting is done to make a
expression in a certain way. This cast is under the programmer’s control variable of one data type to act
like a variable of another type.
and not under compiler’s control. For example, if we need to explicitly
type cast an integer variable into a floating point variable, then the
code to perform type casting can be given as,
float salary = 10000.00;
int sal;
sal = (int) salary;

When floating point numbers are converted to integers (as in type


conversion), the digits after the decimal are truncated. Therefore, data
is lost when floating-point representations are converted to integral
representations. So in order to avoid such type of inaccuracies, int type
variables must be typecast to float type.
As we see in the code, typecasting can be done by placing the
destination data type in parentheses followed by the variable name that
ʇ NOTE
has to be converted. Typecasting is also done in arithmetic operations We can also typecast integer
to get correct result. For example, when dividing two integers, the values to its character equivalent
result can be of floating type. Also when multiplying two integers the (as per ASCII code) and vice
versa.
result can be of long int. So to get correct precision value, typecasting
can be done. For instance:
int a = 500, b = 70;
float res;
res = (float) a/b;

Let us look at some more examples of typecasting.


res = (int) 9.5;
9.5 in converted to 9 by truncation and then assigned to res.
res = (int) 12.3/(int) 4.2;
It is evaluated as 12/4 and the value 3 is assigned to res.
res = (double) total/n;
total is converted to double and then division is done in floating
point mode.
res = (int) (a+b);
The value of a + b is converted to integer and then assigned to
res.
res = (int) a + b;
a is converted to int and then added with b.
res = cos ((double)x);
It converts x to double before finding its cosine value. Program
4.12 and 4.13 illustrate the typecasting.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 60 Operators and Expressions Chapter 4

/*****************************************************************************/
/* Program 4.12 : To convert a floating point number into the integer */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
main()
{
float f_num;
int i_num;
clrscr();
printf(“\nEnter any floating point number : ”);
scanf(“%f”, &f_num);
i_num = (int)f_num;
printf(“\nThe integer variant of %4f is = %d”, f_num, i_num);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter any floating point number : 63.45
The integer variant of 63.450000 is = 63

/*****************************************************************************/
/* Program 4.13 : To convert a floating point number into the integer */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
main()
{
float f_num;
int i_num;
clrscr();
printf(“\nEnter any integer: “);
scanf(“%d”, &i_num);
f_num = (float)i_num;
printf(“\nFloating point variant of %d is = %f”, i_num, f_num);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter any integer: 24
Floating point variant of 24 is = 24.00000

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 61

4.14 MATHEMATICAL FUNCTIONS IN C

You can also perform basic mathematical functions in C, which are


defined in the math.h header file. This file contains several static
functions to perform basic mathematical functions, such as, calculating
sine and logarithms. This header file should be used to avoid incorrect
answers while performing mathematical functions in C. Table 4.7 lists
some of the commonly used mathematical functions included in the
header file:

TABLE 4.7 : Mathematical Function

Function Action
abs(ival) Returns the absolute value of ival
acos(x) Returns the cos value of x [cos-1 (x)]
asin(x) Returns the sin value of x [sin-1 (x)]
atan(x) Returns the tan value of x [tan-1 (x)]
atan2(x, y) Returns the tan value of x/y [tan-1 (x/y)]
cos(x) Returns the cos value of x
cosh(x) Returns the hyperbolic cos value of x
exp(x) Returns the e to the power x value
fabs(x) Returns the absolute value of x
floor(x) Returns the nearest round value of x
fmod(x, y) Returns the floating point reminder value of x/y
log(x) Returns the logarithm value of x
log 10(x) Returns the logarithm value with base 10 of x
pow(x, y) Returns x to the power y
sin(x) Returns the sin value of x
sqrt(x) Returns the square root value of x
tan(x) Returns the tan value of x

Let’s consider the Program 4.14 to understand the use of


mathematical functions in C:

/*****************************************************************************/
/* Program 4.14 : Using Mathematical Functions */
/*****************************************************************************/

#include <stdio.h>
#include <math.h>
void main ()
{

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 62 Operators and Expressions Chapter 4

float x, y;
float square;
float sinx;
float cosx;
float tanx;
printf(“Enter value of x in Degree < 90 : “);
scanf(“%f”, &x);
square = sqrt(x);
y = x*(3.142/180.0);
sinx = sin(y);
cosx = cos(y);
tanx = tan(y);
printf(“\nSquare root of x = %f”, square);
printf(“\nsine value of y = %f”, sinx);
printf(“\ncosine value of y = %f”, cosx);
printf(“\nTangent value of y = %f”, tanx);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter value of x in Degree < 90 : 60
Square root of x = 7.745967
Sine value of y = 0.866093
Cosine value of y = 0.499882
Tangent value of y = 1.732954

4.15 HEADER FILES AND PREPROCESSOR DIRECTIVES

The header files in C are used to contain C declarations and are included
in the head of your C program. The header files have a .h extension.
The header file contains prototypes of the different library functions
included in C. For example, the prototypes for all the mathematical
functions are stored in the math.h header file and all the declarations
for the input and the output functions are included in stdio.h header
file. The commonly used header files in C are listed in Table 4.8.

TABLE 4.8 : Header File in C

Header File Description


stdio.h Used for input/output functions
math.h Used for mathematical functions
string.h Used for string manipulation functions
malloc.h Used for memory allocation\deallocation functions
stdlib.h Used for standard library functions

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 63

Header File Description


ctype.h Used for character manipulation functions
time.h Used for computing time functions
graphics.h Used for graphics functions
dos.h Used for DOS functions

The header file are included in a C program by using the #include


statement. This statement is a preprocessor directive. The preprocessor
directives are executed before the C program is compiled. The different
preprocessor directives included in a C program are listed in Table 4.9.

TABLE 4.9 : Preprocessor Directives in C

Preprocessor Directives Description


#include Includes the content of a file
#define Replaces a macro with a string value
#if Tests whether the compile-time condition is true
#undef Removes a name previously created with #define
#else Specifies an alternative action, when a test fails
#endif Ends the #if directive

The syntax of using the preprocessor directive and the header file
in a C program is:
#include <stdio.h>
You observe that the header file is enclosed within angular (<>)
brackets. You can also include the header file within a pair of double
quotes (“ ”). as shown in the following syntax:
#include “stdio.h”
The difference between the two is that, when the header file is
included within a pair of angular brackets, the file is searched only in
standard directives. When the header file is included within a pair of
double quotes, the file is first searched within the specified directory
and then in the standard directories.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 64 Operators and Expressions Chapter 4

REVIEW QUESTIONS #include<conio.h>


main ()
{
4.1 “C supports a rich set of operators”. Justify. /* Calculates the area of a circle.*/
float area;
4.2 Write a short note on operators available in C int radius=5;
language. area=3.14*radius**2;
4.3 Explain the arithmetic, relational and modulo printf(“%f“,area);
}
operators used in C.
4.4 Explain how a logical expression can be constructed. 4.3 Identify the error in the following code.
Bring out its use with a simple example. #include<stdio.h>
#include<conio.h>
4.5 Discuss the concept of precedence of arithmetic main()
operators (including parenthesis) in C with example. {
char name;
4.6 Discuss the function of the following operators in C: name=‘Hello’;
(i) conditional operators (ii) Bitwise operators (iii) printf(“%c”, name);
comma operator. }

4.7 Describe bitwise operators in C. Each with an 4.4 Identify the errors in the following code.
example. #include<stdio.h>
4.8 List the different type of operators in C. Discuss the #include<conio.h>
main()
following with examples. (a) Conditional operators {
(b) Relational operators. int a=6,c=7,d=8,n=9;
4.9 Discuss the concept of precedence of operators in C float ans;
ans=l0.2/a+(2*a+(3c+4)/a*d/(12/n);
language with examples. clrscr();
4.10 Give the operator precedence chart. printf(“%f”, ans);
getch();
4.11 Explain various unary operators in C. }
4.12 What do you understand by type casting? Give 4.5 The following program is not displaying the correct
example of explicit and implicit type casting. output. Identify the errors.
4.13 Differentiate between typecasting and type #include<stdio.h>
conversion. #include<conio.h>
main()
4.14 When will you use cast operator? Illustrate its use.
{
int num;
clrscr();
printf(“Enter a number: ”) ;
PROGRAM OUTPUT scanf(“%d”, &num) ;
(num=1?printf(“The number entered is 1”);
printf(“The number entered is not 1”));
4.1 The following code is not displaying the correct getch();
output, which is 3600. Identify the error. }

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


#include<conio.h> #include<stdio.h>
main() void main()
{ {
/ * Program calculates the simple interest */ int i=5,j=8,k=0;
int p,t,sim_int; int p;
float r; p=(i,k,j);
p=10000; printf(“%d”,p);
t=3;
}
r=12;
sim_int = p*t*r/100; 4.7 What is the output of the following program?
clrscr();
printf(“%f”,sim_int); #include<stdio.h>
getch(); void main()
} {
unsigned int ii=-1;
4.2 Identify the error in the following code. printf(“%d\n”,ii) ;
printf(“%u\n”,ii * -1);
#include<stdio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 4 Operators and Expressions Page 65

} printf(“%u”, i-*i);
getch();
4.8 What is the output of the following code?
}
#include<stdio.h>
void main() 4.15 What is the output of the program?
{ #include<stdio.h>
int var=6234.5678; #include<conio.h>
printf(“%d”, var); void main()
} {
int i=4;
4.9 What is the output of the following code? clrscr();
#include<stdio.h> printf(“%d”, i++*i++);
void main() printf(“\n%d”, ++i*++i);
{ getch();
int var1=15,var2=10,p,q; }
p=var1>14;
q=var1>8 && var2==8;
4.16 What is the output of the program?
printf(“p=%d q=%d”, p,q); #include<stdio.h>
} #include<conio.h>
void main()
4.10 What is the output of the following code? {
#include<stdio.h> int i=6, j=9;
main() clrscr();
{ j = j || (i++ && printf(“HELLO RTU”));
int var=--4; printf(“%d%d\n”, i, j);
printf(“var = %d”,var); getch();
} }

4.11 What is the output of the following code? 4.17 What is the output of the program?
#include<stdio.h> #include<stdio.h>
main() #include<conio.h>
{ void main()
float flt=l5,g=10; {
enum{var1=l0,var2=20,var3=50}; int x;
printf(“%d\n”,++var3); clrscr();
printf(“%f\n”,flt<<2); x=~!printf;
printf(“%lf\n”,flt%g) ; printf(“%x”,x);
printf(“%lf\n”,fmod (flt,g)); getch();
} }

4.12 What is the output of the following code? 4.18 What is the output of the program ?
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int var=6; short m=8, n=0, p=0;
printf(“%d”, var=++var==7); p+=n+=m;
p+=n+=m+=-p;
}
printf(“m=%d n=%d p=%d”, m, n, p);
4.13 What is the output of the following code? }

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


main() #include<stdio.h>
{
main()
int var1=5,var2=10;
{
var1=var1&=var2&&10; int i=12, j=5, m, n;
printf(“%d%d”,var1,var2); m=i > 8;
} n = j>2 && j!=2;
printf(“m=%d, n=%d”,m, n);
4.14 What is the output of the program?
}
#include<stdio.h>
#include<conio.h> 4.20 What is the output of the following program ?
void main() #include<stdio.h>
{ #include<conio.h>
unsigned int i=-1; int i=2, j, k=2;
clrscr{); main()

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 66 Operators and Expressions Chapter 4

{ printf(“%d”,++j);
int i; }
clrscr();
printf(“i=%d\n”,i); 4.26 What is the output of the following program ?
printf(“j=%d\n”,j); #include<stdio.h>
printf(“k=%d”,k); #include<conio.h>
} main()
{
4.21 What is the output of the following program ? int j = 0xff;
#include<stdio.h> clrscr();
#include<conio.h> printf(“j=%d”, j<<2);
main() }
{
int i=6; 4.27 What is the output of the following program ?
clrscr(); #include<stdio.h>
i++= 1; #include<conio.h>
printf(“%d”, i); void main()
} {
4.22 What is the output of the following program ? float j=‘A’;
clrscr();
#include<stdio.h> printf(“j=%d\n”,j%2);
#include<conio.h> }
void main()
{ 4.28 What is the output of the program ?
char a=200; #include<stdio.h>
signed char b=200; main ()
unsigned char i=200; {
char j=200; int num1 = 10, num2 = 20;
clrscr(); num2=num1, num2?(num1,num2)?num1:num2:num2;
printf(“i=%d j=%d\n”, i, j); printf(“%d %d”,num1,num2);
printf(“a=%d b=%d”, a, b); }
}

4.23 What is the output of the following program ?


#include<stdio.h> LAB PROGRAMS
#include<conio.h>
main()
{
4.1. Write a program to illustrate the variable
const int a;
clrscr(); declarations and assignments.
a=6; 4.2. Write a program to swap (interchange) two numbers
printf(“%d”,a);
using a temporary variable
}
4.3. Write a program to swap two integer numbers
4.24 What is the output of the following program?
without using temporary variable.
#include<stdio.h>
#include<conio.h> 4.4. Write a program to calculate simple interest.
main()
{
4.5. Write a program that accepts two numbers and
float f=10.00; display division of these numbers.
clrscr(); 4.6. Write a program to calculates the area of rectangle
printf(“%g, %0.2g, %0.4g, %f”, f, f, f, f);
} 4.7. Write a program to calculate surface area and
volume of a cube.
4.25 What is the output of the following program ?
#include<stdio.h>
4.8. Write a program which convert given number in
#include<conio.h> years, weeks and days (ignore leap year).
#define j 6 4.9. Write a program to calculate the sum and average
void main()
{
of five numbers
clrscr(); 4.10. Write a program to use conditional operator ( ? )

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

INPUT AND OUTPUT OPERATIONS


5
5.1 INTRODUCTION

In any programming language, an interface plays a very important role.


It takes data from the user and displays the output. One of the essential
operations performed in C programs is to provide input values to the
ʇ NOTE
program and output the data produced by the program to a standard Input can also be provided
output device. Input refers to entering some data into the program and directly in the program by
assigning the values to the
output refers to displaying some data on the screen, printer or in any variables.
file. You can provide input in the form of file or as a command from the
command prompt. C programming language provides a set of built-in
functions to read the given input and output the required data.

5.2 INPUT/OUTPUT FUNCTIONS

The C language provides several input-output functions that can


perform input/output operations. These functions are collectively
known as standard input/output Library. This library is denoted by
stdio. The stdio.h is the header file that contains the stdio functions.
In C programming language, some of the standard input/output
functions are:
(1) scanf(): Reads input from the standard input device
(2) printf(): Displays information on the screen
(3) getchar(): Reads a single character
(4) putchar(): Writes characters one at a time
(5) gets(): Reads a string
(6) puts(): Prints a string

These functions can be categorized into formatted and unformatted


I/O functions. Formatted I/O functions enable the user to specify the
types of data and the way in which it should take input and printed
the output. On the other hand, the unformatted I/O functions do not
specify the types of data and the way it should be read or written.
Table 5.1 shows the list of formatted and unformatted I/O functions:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 68 Input and Output Operations Chapter 5

TABLE 5.1 : Formatted and Unformatted I/O Functions

Type Input Function (s) Output function (s)


Formatted scanf() printf()

Unformatted getchar(), gets() putchar(), puts()

5.3 PRINTF() FUNCTION

The printf() function is used to display information on the screen. It


returns the number of characters printed by printf() function, or a
negative value if an output error occurs.
The syntax for printf() function is:
printf(“control_character”, variable_list);
where control_character determines the type and format of the
values to be displayed and variable_list is the list of variables that
you want to display.
Let’s see some example where, we have used the printf() function:
printf(“Rajasthan Technical University”);
printf(“%d”, var1);
printf(“%f %f”, m, n);
printf(“Sum of four numbers are=%d”, sum);
printf(“\n A=%d, B=%d”, a, b);

First statement displays text enclosed within the pair of double-


quotes. Second statement displays the value of var1. Third statement
displays the value of variables m and n. Fourth statement displays the
message and then displays the value of sum variable next to it. Fifth
statement displays the value of variables a and b next to A= and B=.
The following program shows how to use the printf() function:

/*****************************************************************************/
/* Program 5.1 : Using the printf() Function */
/*****************************************************************************/

#include <stdio.h>
int main()
{
int i = 0;
i = printf(“\nabcde”); /* statetment A */
printf(“\nTotal characters printed %d.”, i); /* statetment B */
return 0;
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 69

 OUTPUT :
abcde
Total characters printed 6.

 EXPLANATION :
In this program, Statement A prints 6 characters and return 6 which is assign to i.
Statement B prints the value of i as 5. Here note that 5 character are printed but
compiler also recognise \n as newline character. So it return 6. If we remove \n, it
will return 5.

The general format for the printf() statement has a string


argument followed by additional arguments. In statement B, “Total
characters printed %d\n” is the first string argument, i is the second
argument. You can have multiple arguments but it depends on the value
of the variable that you want to print. For each additional argument
you need a place holder. Each place holder begins with %. In statement
B, %d is the place holder. For second argument i, the place holder is
%d. So when you want to add an integer value, you have to use %d.
For each data type place holders are given. For example, if you want
to print i and j then you may have to use two place holders. Any
characters in the first string argument, other than the place holder and
the characters, represent escape sequences. In the above example, the
escape sequence character is \n, which is not printed but it acts as a
directive. For example, \n directive indicates that the next statement
should be printed in a new line.

5.4 PRINTF() PLACE HOLDERS

Place holders are used to print the values of arguments specified in the
printf() function. The directives in place holders control printing. The
general form of a place holder is:
% flags field_width precision type_prefix type_identifier

5.4.1 Type Identifiers


The type identifier specifies the type of value to be displayed. If the
specified identifier is invalid, the unpredictable output will be displayed.
Table 5.2 lists the type-identifiers:

TABLE 5.2 : Description of Type Identifiers

Type-identifiers Description
d, i Represents signed integers.
o Represents unsigned integers displayed in octal form
u Represents unsigned integer in decimal form

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 70 Input and Output Operations Chapter 5

Type-identifiers Description
x Represents unsigned integer in hexadecimal form and hexadecimal
characters such as a, b, c, d are printed in lowercase.
X Represents unsigned integer in hexadecimal form form and hexadecimal
characters such as A, B, C, D are printed in uppercase.
c Converts any value to an unsigned char and displays it. It is used mainly
for printing characters.
s Converts the argument into a character array and prints it; last null in
the string characters
f Prints floating point
e, E Represents floating point in exponential form. It has one digit to the left
of the decimal point; the number of digits on the right side of decimal
point depends on the required precision.
g, G Prints a floating point number in exponential form. The exponential
form is used if the exponent is less than -1. However, these both are
slightly different in functionality.
n Prints the number of characters, which are printed so far by printf
function.
p Specifies the value of a pointer.

5.4.2 Type Prefixes


Prefixes specify that the value to be displayed should be interpreted as
short, long or double long. Table 5.3 lists the types of prefixes:

TABLE 5.3 : Description of Prefixes

Prefixes Type Description


h Appears before type indicators d, i, o, u, x and X and indicates that the value
to be displayed should be interpreted as short. For example, short integer
(hd), short unsigned integer (hu).
l Appears before type-identifiers d, i, o, u, x and X and indicates that the value
to be displayed should be interpreted as long. For example, long integer (ld),
long unsigned integer (lu).
l, L Indicates that a value should be specified as long double and is available for
type-identifiers e, E, f, g and G.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 71

5.4.3 Field-width
Field-width indicates the least number of columns that are allocated to
the output. For example, if you write %4d to i and the value of i is 10
then 4 columns are allocated for i and 2 blanks are added on left side
of the value of i, so the output is bb10. Here, we are representing b
to indicate blank space. If the value is more than the specified column
then field-width is ignored and the number of columns used is equal to
the number of columns required by the arguments. So if i is 12345 then
5 columns are used even if %4d is specified. The output width is not
shortened because of the field-width. If you specify * instead of field-
width then you have to specify additional arguments.
For example:
printf (“%*d”, 5, 20); /* statetment A */
printf (“%*d”, 20, 5); /* statetment B */

In statement A, 5 is substituted for * and it indicates putting the


value 20 in 5 columns. In statement B, 20 is substituted for * and it
indicates putting the value 5 in 20 columns.

5.4.4 Precision
Precision indicates the number of minimum digits printed for integers,
i.e. for type integers d, o, u, x and X. For example,
printf(“%10.4d”, 35);
Here 10 is the field-width and 4 is the precision, so 10 columns
ʇ NOTE
are used for the output and the output is 4-digit. To divide 35 in 4 For floating arguments,
digits, 00 are padded on left side to make it as 0035. To print 0035 in precision indicates the number
10 columns, blanks are added to make the output bbbbbb0035. of digits that are printed after
decimal points.
If precision is more than the number of digits on the right side
of decimal point then 0’s are padded on the right side. If precision
indicates very few digits then it is ignored and the number of digits are
printed as required.

5.4.5 Flags
Flag characters are used to provide directives for the output. You can
use multiple flag characters in any order. Following are flag characters:
1. - indicates that the output is left justified.
printf(“%-10.4”, 25);
It prints 0025bbbbbb, thus blanks are padded on right side. In
the absence of flag, it is printed as bbbbbb0025.
2. + indicates that i number is printed using sign character + or -.
printf(“%+d”, -25);
printf(“%+d”, 25);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 72 Input and Output Operations Chapter 5

It causes printing as
-25
+25

3. Space indicates a space for positive values so that positive values


and negative values are aligned. For example:
printf(“% d”, 25);
printf(“%d”, 25);

It causes printing as
b25
25

In first case, blank is displayed.


4. # indicates that the value should be converted to another form
before displaying. For example, for hexadecimal values you can
indicate 0X; for the floating data type, presence of # indicates
that the decimal point should always be included in output.
5. 0 pads 0’s to complete the field-width. This is used for whole
and real numbers. If the precision is specified as 0 then the flag
is ignored; if 0 and - flag are specified then 0 flag is ignored and
-flag is considered.

5.5 ESCAPE SEQUENCE

These are the special directives used to format printing. Table 5.4 shows
the escape sequences:

TABLE 5.4 : List of Escape Sequence

Escape Sequence Results


\a Produces beep or flash; the cursor position is not changed
\b Moves the cursor to the previous column of the previous line
\f Moves the cursor to the beginning of next page
\n Moves the cursor to the new line
\r Moves the cursor to the first column of current line
\t Moves the cursor to the next horizontal tab stop on the line
\v Moves the cursor to the next vertical tab stop on the line
\\ Prints \
\” Prints “
%% Prints %

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 73

5.6 SCANF() FUNCTION

The scanf() function is a formatted function in C that is used to


read information from standard input device, such as keyboard. The
scanf() function is used to enter the numeric that contains the first
string argument and it may have additional arguments. The additional
arguments must be pointers (to implement call by reference).
The syntax for scanf() function is as follows:
scanf(“control_character”, address_list);
where control_character is a sequence of one or more control
characters. Control character decides the type of values that need to be
provided to the variables. Control characters are preceded by a % sign.
address_list determines the address of memory locations where
the values of input variables should be stored.
Rules to Remember :
Following rules should be kept in mind before using the scanf()
function:
1. A pair of double quotes is used within the control character for
example:
scanf(“%d”, &b);
2. For every input variable, there must be a control character.
scanf(“%d %d %d”, &m, &n, &p);
3. Multiple numbers of character groups can be allowed within the
control character.
scanf(“%d %f %c”, &a, &b, &c);
4. Use ampersand (&) symbol followed by the input variable in the
address_list.
scanf(“%c”, &a);
5. Use commas to separate input variables.
scanf(“%f %d”, &m, &n);
6. Use comma to separate control_characters and address_list.
scanf(“%u %d”, &var1, &var2);
The following program helps you to understand the use of scanf()
function:

/*****************************************************************************/
/* Program 5.2 : Using the scanf() Function */
/*****************************************************************************/

#include<stdio.h>
int main()
{
int m;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 74 Input and Output Operations Chapter 5

int i, j, k;
printf(“\nEnter Three Integer : ”);
m = scanf(“%d %d %d”, &i, &j, &k); /* statement A */
printf(“Total values inputted : %d\n”, m);
printf(“The input values are : %d %d %d\n”, i, j, k);
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run1 :
Enter Three Integer: 34 56 43
Total values inputted : 3
The input values are : 34 56 43

Run2:
Enter Three Integer: 45 38 a
Total values inputted : 2
The input values are : 34 56 4923

In the above program statement A indicates scanf(), it is used


for inputting values for i, j, k. The first argument is always a string
argument having place holders. During execution of the scanf() the
ʇ NOTE
input is processed and it is matched against the string argument, the scanf() returns the number of
process is continued till the matching is over. When the first place values, which are successfully
holder is encountered in the string argument, a value of specific type entered.

of the first element constitutes a match. it is repeated for each place


holder. If there is one or more white space characters in the first string
argument between the place holders, then any sequence of one or more
white space characters in the input are matched. If there are other
characters in a string argument then the input should have the same
character in the same sequence to be matched. When matching is not
done then the function is terminated. Matching fails if the expected
input is missing. In the preceding example, when we enter 45 38 a
as input, then matching fails for the variable k. Therefore, scanf()
function returns 2. So it prints the value of i and j, and k gets a junk
value.

5.7 SCANF() PLACE HOLDERS

The scanf() place holder consists of % at the beginning and type


indicator at the end. Apart from that it can have *, maximum field-
width indicator and type indicator modifier. For example:
scanf(“%10.2f %10d”, &a, &b);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 75

5.7.1 Type Indicators


Type indicator is character specifying the type of data to be read.
Table 5.5 shows the description of type indicators:

TABLE 5.5 : Description of Type Indicator

Type Indicator Result


d, i Reads signed integers; the expected argument should be a pointer to int.
However, these are slightly different in functionality.
o Reads unsigned integer in octal form
u Reads unsigned integer in decimal form
x, X Reads unsigned integer in hexadecimal form
E, e, f, g, G Reads floating-point values. However, these are slightly different in
functionality.
S Reads character string. It matches a sequence of non-white space characters
terminated by an end of line or end of file character. The additional argument
should be a pointer to char and should point to an area. Which is large
enough to hold the specified number of characters.
N Writes the number of characters so far in the target variable but it does not
read any input.

5.7.2 Use of *
The * is used to suppress the input. For example, %*d, if your input
consists of 5 values and you want to ignore middle 3 values then you
can write:
scanf(“%d %*d %*d %*d %d”, &i, &j);

So, if your input is


10 20 30 40 50

then i gets the value 10 and j gets the value 50, this is useful
when you are getting the input from the file.

5.7.3 Field-width
It indicates the maximum number of characters that are read into the
variables. It is a string of non-space characters. It extends to the next
inappropriate character or until the field-width limit (if specified) is
reached.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 76 Input and Output Operations Chapter 5

5.8 GETCHAR() FUNCTION

The getchar() function reads a single character from the standard


input device. getchar() returns the character it reads, or, the special
value EOF (end of file), if there are no more characters available. The
syntax of getchar() function is as follows:
var_char = getchar();
where var_char is a character type variable.
The following program shows how to use the getchar() function:

/*****************************************************************************/
/* Program 5.3 : Using the getchar() Function */
/*****************************************************************************/

#include<stdio.h>
void main()
{
char var1;
printf(“\nType a character : ”);
var1 = getchar();
printf(“\nYou typed : %c”, var1);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run 1
Type a character : a
You typed : a

Run 2
Type a character : F
You typed : F

5.9 GETS() FUNCTION

The gets() function reads a string of characters from the user until a
<newline> is read or an end-of-file condition is encountered. It stores
the string of characters in a set of consecutive memory locations, which
is called an array. The example for this function is as follows:
char string[50];
gets(string);

The following program shows how to use gets() functions:

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 77

/* Program 5.4 : Using the gets() Function */


/*****************************************************************************/

#include<stdio.h>
int main()
{
char string1[100];
printf(“\nType Something : ”);
gets(string1);
printf(“You typed : %s\n”, string1);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Type Something : Rajasthan Technical University
You typed : Rajasthan Technical University

5.10 PUTCHAR() FUNCTION

The putchar() function writes a single character to the standard output


stream, stdout. The putchar() function is specified in C language’s
standard library header file stdio.h. The character to be printed is fed
into the function as an argument, and if the writing is successful, the
argument character is returned. Otherwise, end-of-file is returned.
The following program shows how to use putchar() function:

/*****************************************************************************/
/* Program 5.5 : Using the putchar() Function */
/*****************************************************************************/
#include<stdio.h>
int main()
{
char var1;
printf(“\nType a character : ”);
var1 = getchar();
printf(“\nYou typed : ”);
putchar(var1);
getch();
}
/*****************************************************************************/

 OUTPUT :
Type a character : N
You typed : N

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 78 Input and Output Operations Chapter 5

5.11 PUTS() FUNCTION

The puts() function displays a string of text and appends a newline


character (‘\n’) to it. The syntax for this function is:
puts(string);

The following program shows how to use puts() function:

/*****************************************************************************/
/* Program 5.6 : Using the puts() Function */
/*****************************************************************************/
#include<stdio.h>
int main()
{
char string1[100];
printf(“\nType Something : ”);
gets(string1);
printf(“You Typed : ”);
puts(string1);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Type Something : Rajasthan Technical University
You typed : Rajasthan Technical University

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 79

REVIEW QUESTIONS main()


{
char name[20];
5.1 Explain the function scanf() alongwith format printf(“Enter your Full Name : \n”) ;
conversions with examples. scanf(“%s”,name);
printf(“%s”,name);
5.2 Give the syntax and explain the semantics of }
formatted input/output functions.
5.3 What is the output of the program?
5.3 Explain the function printf() alongwith “format
string” and “format specifier” with examples. #include<stdio.h>
#include<conio.h>
5.4 For what purpose the return value of the scanf() main()
function can be used? {
float f=10, width_f=3;
5.5 Explain the getchar() and putchar() functions with clrscr();
examples. printf(“%*.2f”,width_f,f);
getch();
5.6 When printing a float or double with %f, how many
}
digits after decimal does printf() output? Does
printf() round or truncate the value? 5.4 What is the output of the program?
5.7 What functions may be used for input and output #include<stdio.h>
of a single character? #include<conio.h>
main()
5.8 What is a formatting string which is used as an
{
argument of the functions printf() and scanf()? float a=20.123;
5.9 How would you use printf() function for mixed data int width_a;
clrscr();
type?
printf(“Using indirect width specification to
5.10 How would you use scanf() function to read (i) an display.”);
integer, (ii) a character, (iii) a double type value, printf(“\nEnter the field width off:”);
scanf(“%d”,width_a);
and (iv) a string?
printf(“%f”,width_a,a);
5.11 Which functions may be used for reading string getch();
objects? }

5.12 What is the advantage of the using function gets( ) 5.5 What is the output of the program ?
over scanf( ) for reading strings?
#include <stdio.h>
5.13 What is the difference between the digit 8 and #include <Conio.h>
character ‘8’ ? main ()
{
5.14 How many digits after decimal are displayed using char text[40];
format specifier % f ? puts(“Enter a line of text”);
gets(“%s”,text);
puts(text);
getch();

PROGRAMMING OUTPUT QUIZ


}

5.6 What is the output of the program?


#include<stdio.h>
5.1 What is the output of the program? #include<conio.h>
#include<stdio.h> void main()
#include<conio.h> {
main() int x, y, i=1, j=-1;
{ clrscr();
char name[20]; x=printf(“%d\n”,i);
printf(“Enter your name”); y=printf(“%d\n”,j);
scanf(“%s”,name); printf(“%d\n”,x);
putchar(name); printf(“%d\n”,y);
} getch();
}
5.2 What is the output of the program?
#include<stdio.h> 5.7 What is the output of the program?
#include<conio.h> #include<stdio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 80 Input and Output Operations Chapter 5

#include<conio.h> main()
#include<stdlib.h> {
void main() printf(“computer\nScience\n”);
{ printf(“Computer\rScience”);
int i; }
clrscr();
scanf(“%d”,printf(“\d\n”,scanf(“%d”,&i))); 5.14 What is the output of the following code ?
/* input 30 * /
getch(); #include<stdio.h>
main()
}
{
printf(“Computer\b\b\b\b\b”);
5.8 What is the output of the program? printf(“Hi!\b\b\bScience”);
#include<stdio.h> }
#include<conio.h>
void main() 5.15 What is the output of the following code?
{
int y; #include<stdio.h>
clrscr(); main()
y=printf(“HI\n”); {
printf(“%d”,printf(“HELLO\n”),y); char str=‘\ni’;
/* input: 30 */ printf(“str=%c“,str);
getch(); }.
}
5.16 What is the output of the following code?
5.9 What is the output of the program? #include<stdio.h>
#include<stdio.h> #include<conio.h>
void main() main()
{ {
static int y=0xB; char ch, ch1;
printf{“%d”,getch(y)); /* input: 0 */ clrscr();
scanf(“%c”,&ch); /* input: ab */
}
scanf(“%1c”,&ch1);
printf(“ch=%c,ch1=%c\n”,ch,ch1);
5.10 What is the output of the program? printf(“ch=%1c,ch1=%1c\n”,ch,ch1);
#include<stdio.h> printf(“ch %1s,ch1=%1s\n”,ch,ch1);
#include<math.h> getch();
void main() }
{
static int x; 5.17 What is the output of the following code?
printf(“%d”, x=(pow(printf(“hi\b”),-~x)));
#include<stdio.h>
}
#include<conio.h>
void main()
5.11 What is the output of the following code ? {
#include<stdio.h> int f;
main () clrscr();
{ f=‘%’;
float PI=3.14; printf(“%cd”,f,f);
printf(“\nPI=%f”,PI); }
printf(“\nPI=%6.2f”,PI);
printf(“\nPI=%6.0f”,PI); 5.18 What is the output of the following code ?
}
#include<stdio.h>
#include<conio.h>
5.12 What is the output of the following code? main()
#include<stdio.h> {
main() int a,b;
{ clrscr();
printf(“%20s\n”,”Computer”); scanf(“%d”+scanf(“%d %d”,&a,&b));
printf(“%20s\n”,”Computer Science!”); /* input 21 45 */
} printf(“a=%d b=%d\n”,a,b);
printf(“\%\n”);
5.13 What is the output of the following code? printf(“\\%\n” );
printf(“%%\n”);
#include<stdio.h> printf(“\%%\n”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 5 Input and Output Operations Page 81

clrscr();
}
printf(“a=%s, b=%s”,a,b);
}
5.19 What is the output of the following code ?
#include<stdio.h>
#include<conio.h>
main() LAB PROGRAMS
{
unsigned int a=l28;
clrscr();
5.1. Write a program that reads a character from the
printf(“%d”,a);
{ standard input device, i.e. keyboard and displays
char a=l28; it on the screen.
printf(“%d”,a);
}
} 5.2. Write a program that reads a character from the
standard input device, i.e. keyboard and displays
5.20 What is the output of the following code? it on the screen using the putchar() function.
#include<stdio.h>
#include<conio.h> 5.3. Write a program that accepts an age of person from
main() the keyboard using scanf() function and displays it
{ on the screen.
char a[]=”\\?/”;
char b[]=”\/?\”; 5.4. Write a program that accept the value of two
integer numbers and display them.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

DECESION MAKING
6
6.1 INTRODUCTION

A conditional statement is a control structure that allows you to select


one or more execution paths in a program. It causes a program to
execute a block of code after evaluating a given conditional expression.
If the conditional expression comes out to be true, the accompanying
block of code is executed; otherwise, the block of code is bypassed. The
following is the list of the conditional statements supported by C.
(1) if statement
(2) if-else statement
(3) Nested if statements
(4) if-else ladder
(5) switch statement

6.2 IF STATEMENT

The if statement executes a simple or compound statement, depending


on whether or not an expression is true. The syntax to use the if
ʇ NOTE
statement is given in figure below. Here statementBlock1 may be
simple statement. For simple
statement you need not to use
opening and closing braces.

Figure 6.1 : Syntax and Flow chart of if Statement

In the above, a statementBlock1 is executed when the test_


expression given in the if statement is turn out to be true. Otherwise,
the program control passes to the statementX. If the test_expression

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 83

is false then the C compiler does not do anything. Note that the test_
expression given in parentheses, must be evaluated as true (non-zero
value) or false (zero value). Some examples of using a test_expression
in the if statements are given as follows:
if(7) /* a non-zero value returns True*/
if(0) /* zero value returns False*/
if(i==0) /* True if i=0 otherwise False*/
if(i = 0) /* False because value of the expression is zero*/

The following example shows the use of if statement along with


a simple statement:
if(a>b)
i = i + 1; /* statement A*/
j = j + 1; /* statement B*/

In the above example, when the conditional expression a > b is


true, the statement A is executed otherwise not.
The following example shows the use of the if statement along
with a compound statement. If the conditional expression a>b is true,
both statements marked as A and B are executed.
if(a>b)
{
i = i + 1; /* statement A*/
j = j + 1; /* statement B*/
}

Program 6.1 to 6.3 shows the examples to use the if statement:

/*****************************************************************************/
/* Program 6.1 : Using the if Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int age;
clrscr();
printf(“\nEnter your age : ”);
scanf(“%d”,&age);
if(age<18)
printf(“\nYou are not eligible to give vote.\n”);
if(age>=18)
printf(“\nYou are eligible to give vote.\n”);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 84 Decesion Making Chapter 6

Run 1
Enter your age : 17
You are not eligible to give vote.
Run 2:
Enter your age : 18
You are eligible to give vote.

 EXPLANATION :
In this program you have to enter your age at the runtime. If the entered age is less
than 18, You are not eligible to give vote. message appears; and if the entered age
is greater than 18, You are eligible to give vote. message appears.

/*****************************************************************************/
/* Program 6.2 : Program to find the largest of three numbers */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int a, b, c, big;
printf(“\nInput a b c : ”);
scanf(“%d %d %d”, &a, &b, &c);
/* computing the largest of three numbers */
big = a; /* statement A*/
if(b > big) /* statement B*/
big = b;
if(c > big) /* statement C*/
big = c;
printf(“Largest of the three numbers = %d \n”,big);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run1:
Input a b c : 15 20 55
Largest of the three numbers = 55

Run2:
Input a b c : 88 198 102
Largest of the three numbers = 198

 EXPLANATION :
In this program first 3 input is provide. By Statement A, a is assigned to big. Now in
statment B, big is compared with b. If b is greater than big, then big is assigned b.
In statement C, big is compared with c. If c is greater than big, then big is assigned
c. Thus big has biggest of a, b and c.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 85

/*****************************************************************************/
/* Program 6.3 : To calculate the Total Pay of a Employee
/*****************************************************************************/

#include<stdio.h>
main()
{
int empno, ltc;
float bpay, bonus, hra, total=0.0;
char category;
printf(“\nGive Category : ”);
scanf(“%c”, &category);
printf(“\nGive Employee Number : ”);
scanf(“%i”, &empno);
printf(“\nGive Basic Pay : ”);
scanf(“%f”, &bpay);
if(category == ’r’)
{
bonus = bpay*50.00/100.00;
ltc = 5000;
hra = bpay *25.0/100.0;
total = bpay + bonus + ltc + hra;
}
else
{
bonus = bpay*30.0/100.00;
ltc = 2000;
hra = bpay*10.0/100.0;
total = bpay + bonus + ltc + hra;
}
printf(“\nBasic Salary = %g”, bpay);
printf(“\nBonus = %g”,bonus);
printf(“\nLTC = %i”, ltc);
printf(“\nHouse rent = %g”, hra);
printf(“\nTotal salary = %g”, total);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run 1:
Give Category : r
Give Employee Number : 23
Give Basic Pay : 4000
Basic Salary = 4000
Bonus = 2000
LTC = 5000
House Rent = 1000
Total Salary = 12000

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 86 Decesion Making Chapter 6

Run 1
Give Category : a
Give Employee Number : 13
Give Basic Pay : 10000
Basic Salary = 10000
Bonus = 3000
LTC = 2000
House Rent = 1000
Total Salary = 16000

 EXPLANATION :
Here program ask the user for category. If category is r, statement block following if
is executed. If category is any other, statement following else are executed.

6.3 IF ELSE STATEMENT

The if-else statement executes a simple or compound statement when


the test expression provided in the if statement is true. It executes
another simple or compound statement, followed by the else statement,
when the test expression is false.
The syntax of the if-else statement is shown below

Figure 6.2 : Syntax of if else statement

In the above syntax, when the test_expression specified in


the if clause is true, the statementBlock1 is executed; otherwise,
statementBlock2 is executed.
The following example illustrate the use of if-else statement:
if(a>b)
printf(“Big number is %d”, a); /* statement 1*/
else
printf(“Big number is %d”, b); /* statement 2*/

In the above example, if the value stored in the a variable is


more than the value stored in the b variable, statement marked as 1 is
executed; otherwise, the statement marked as 2 is executed.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 87

Program 6.4 and 6.5 shows the use of an if-else statement:

/*****************************************************************************/
/* Program 6.4 : Checking the Age for Vote */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
int age;
clrscr();
printf(“\nEnter your age : ”);
scanf(“%d”,&age);
if(age<18)
printf(“\nYou are not eligible to give vote\n”);
else
printf(“\nYou are eligible to give vote\n”);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run 1:
Enter your age : 24
You are eligible to give vote

Run 2:
Enter your age : 15
You are not eligible to give vote.

 EXPLANATION :
In above program, you have to enter your age at the runtime. If the entered age is less
than 18, You are not eligible to give vote. message appears; otherwise, You are
eligible to give vote. message appears.

/*****************************************************************************/
/* Program 6.5 : Checking the number for Nonzero */
/*****************************************************************************/

#include <stdio.h>
void main()
{
int input;
printf(“\nInput an integer : ” );
scanf(“%d”, &input );
if(input)
printf(“\nIt is non-zero.”); /* Statement A */

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 88 Decesion Making Chapter 6

else
printf(“\nIt is zero.” ); /* Statement B */
getch();
}

/*****************************************************************************/

 OUTPUT :
Run1:
Input an integer: 12
It is non-zero.

Run2:
Input an integer: 0
It is zero.

 EXPLANATION :
In this program you have to enter a number. If it is nonzero, statement A is executed
otherwise statement B is executed.

6.4 NESTED IF

The term nested if statements means one if statement contains


another if statement. The control of a program moves into the inner
if statement when the outer if statement is evaluated to be true. The
following syntax is used to create the nested if statement:
if(test_expression1)
{
statment1;
if(test_expression2)
{
statement2;
}
}

In the above syntax, test_expression1 is executed first, and


when it evaluates to true, statement1 gets executed and the control of
program passes to the inner if statement. statement2 gets executed
when test_expression2 of the inner if statement is true. Program 6.6
shows an example of the nested if statements.

/*****************************************************************************/
/* Program 6.6 : Program 3: Using Nested if Statements */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 89

int num;
clrscr();
printf(“\nEnter a number gerater than 0 : ”);
scanf(“%d”,&num);
if(num>0)
{
if(num>50)
{
if(num>100)
{
if(num>500)
printf(“\nThe number is greater than 500.”);
printf(“\nThe number is greater than 100.”);
}
printf(“\nThe number is greater than 50.”);
}
printf(“\nThe number is greater than 0.”);
}
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run 1:
Enter a number greater than 0 : 200
The number is greater than 100.
The number is greater than 50.
The number is greater than 0.

Run 2 :
Enter a number greater than 0 : 76
The number is greater than 50.
The number is greater than 0.

 EXPLANATION :
In Program 6.6, num is integer variable, which is initialized at runtime by user. The
if statements are used four times, which are nested one into another. The first if
statement checks whether the entered value of num variable is greater than 0. If the
value of num variable is greater than 0, then the second if statement checks whether
the entered value of num variable is greater than 50. When second if statement also
comes out to be true, the third if statement checks whether the num variable is
greater than 100. When third if statement also comes out to be true, the fourth if
statement checks whether the num variable is greater than 500. At each level of the if
statement, the corresponding message is displayed by using the printf() function. In
our case, we have entered the number, 400, at runtime, so the corresponding messages
are displayed.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 90 Decesion Making Chapter 6

6.5 USING THE IF-ELSE LADDER

When more than one if-else statements are used in a sequence, it is


called as if-else ladder. The syntax to use the if-else ladder is:

Figure 6.3 : Syntax of If else Ladder

If test_expression1 is true then the statement1 is executed.


If test_expression1 is false and test_expression2 is true then the
statement2 is executed. This process goes up to the test_expressionN,
where N is a real number. You should note that depending on the test
expression, only one statement is executed. When all the N conditions
become false, then the final else containing the default statement will
be executed.
Program 6.7 shows an example of an if-else ladder.

/*****************************************************************************/
/* Program 6.7 : Using the if-else Ladder */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
char alphbt;
clrscr();
printf(“\nEnter an alphabet : ”);
scanf(“%c”,&alphbt);
if(alphbt == ‘a’)
printf(“It is a vowel.”);
else if(alphbt == ‘e’)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 91

printf(“It is a vowel.”);
else if(alphbt== ‘i’)
printf(“It is a vowel.”);
else if(alphbt == ‘o’)
printf(“It is a vowel.”);
else if(alphbt == ‘u’)
printf(“It is a vowel.”);
else
printf(“It is not a vowel.”);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run 1:
Enter an alphabet : e
It is a vowel.

Run 2:
Enter an alphabet : g
It is not vowel.

 EXPLANATION :
In this program alphbt is a character variable and its value is provided at runtime.
The character supplied at runtime is tested successively across the multiple if-else
statements until a match is found. In our case, we provide the e character, which
displays the It is a vowel message.

The program created by using if-else ladders is difficult to read


and maintain as it becomes more complex to understand. C provides
switch statements to overcome the difficulties and complexities in
understanding a program, which is discussed next.

6.6 SWITCH STATEMENT

A switch statement is a conditional statement that tests a variable


against different values. If the value is matched, the corresponding
group of statements is executed. A switch statement begins with the
switch keyword that is followed by a value expression in the parenthesis
(). It is a combination of multiple case labels that must be separated by
the break statement. Every case label contains a constant value that is
matched against the value, which is specified in the switch expression.
If the value is matched, the statements of that case label are executed.
In addition, you can specify the default label, which is executed when
the value specified in the switch expression, does not match with the
given case labels. The syntax to use a switch statement is:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 92 Decesion Making Chapter 6

Figure 6.4 : Syntax and Flow Chart of switch Statement

In the above syntax, the value of the variable is compared against


the various constants in the case labels. If the value of the variable
matches with one of the values of the case constants, the code associated
with that case constant is executed. If the execution reaches a break
statement, the switch statement ends. If there is a default statement,
and variable does not match with any value of case constants, the code
in the default statement is executed.
Following program shows an example of the switch statement.

/*****************************************************************************/
/* Program 6.8 : Using the switch Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char alphbt;
clrscr();
printf(“\nEnter an alphabet : ”);
scanf(“%c”,&alphbt);
switch(alphbt)
{
case ‘a’:
printf(“It is a vowel”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 93

break;
case ‘e’:
printf(“It is a vowel”);
break;
case ‘i’:
printf(“It is a vowel”);
break;
case ‘o’:
printf(“It is a vowel”);
break;
case ‘u’:
printf(“It is a vowel”);
break;
default:
printf(“It is not a vowel”);
}
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run 1:
Enter an alphabet : e
It is a vowel

Run 2:
Enter an alphabet : g
It is not vowel

 EXPLANATION :
In program 6.8, the value supplied by you at runtime is stored as an alphbt variable.
This variable is used as a parameter to the switch clause and is compared against the
various constants in the case labels. Statements following the case label are executed
whose constant is equal to the value of the expression in the switch statement. The
default label is executed when none of the case labels matches with the value stored
in the switch expression.

The Program 6.9 computes the roots of a quadratic equation.


Note the use of break at the end of each case statement to transfer the
control out of the switch statement.

/*****************************************************************************/
/* Program 6.9 : Roots of a quadratic equation */
/*****************************************************************************/

#include<stdio.h>
#include<math.h>
main()
{

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 94 Decesion Making Chapter 6

float a,b,c, real, num, imag, root1, root2, disc;


int k;
printf(“\nThis program compute the roots of Quadratics Equation.”);
printf(“\n******************************************************”);
printf(“\nInput a b c : ”);
scanf(“%f %f %f”, &a, &b, &c);
if(a!=0)
{
disc = b*b - 4*a*c;
printf(“\nDiscriminant = %5.2f”,disc);
if(disc<0) k = 1;
else if(disc == 0) k = 2;
else if (disc > 0) k = 3;
switch (k)
{
case 1 :
printf(“\nRoots are imaginary.”);
real = -b/(2*a);
disc = -disc;
num = pow((double) disc, (double) 0.5);
imag = num/(2*a);
printf(“\nRoot1 = %5.2f +j%5.2f”,real, imag);
printf(“\nRoot2= = %5.2f -j%5.2f”, real, imag);
break;
case 2:
printf(“\nRoots are real and equal.”);
root1 = -b/(2*a);
printf(“\nRoot1 = Root2 = %7.2f\n”,root1);
break;
case 3:
printf(“\nRoots are real and unequal.”);
root1 = (-b + sqrt ((double)disc))/(2*a);
root2 = (-b - sqrt ((double)disc))/(2*a);
printf(“\nRoot1 = %7.2F Root2 = %7.2f \n”,root1, root2);
} /* End Switch */
} /* end-if */
else
printf(“Equation is linear.\n”);
getch();
}
/*****************************************************************************/

 OUTPUT :
Run1 :
Input a b c : 1 2 1
Discriminant = 0.00
Roots are real and equal.
Root1 = Root2 = -1.00

Run2 :
Input a b c : 1 2 7
Discriminant = -24.00

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 95

Roots are imaginary.


Root1 = -1.00 +j2.45
Root2 = -1.00 -j2.45

Run 3:
Input a b c: 0 4 7
Equation is linear.

Comparison Between If - else and switch


Table 6.1 compares general form of a switch statement with that of an
if-else statement.

TABLE 6.1 : Comparison Between the switch and if-else construct

Generalized Switch statement Generalized if-else Statement


switch(x) { if(exp1)
case 1: /* do this */ {/* do this */ }
case 2: /* do this */ else if(exp2)
case 3: /* do this */ {/* do this */ }
... else if(exp3)
default: /* do this */ } {/* do this */ }

The power of nested if-else statements lies in the fact that it


can evaluate more than one expression in a single logical structure.
Switch statements are mostly used in two situations:
(1) When there is only one variable to evaluate in the expression.
(2) When many conditions are being tested for.
When there are many conditions to test, using the if and else-if
construct becomes a bit complicated and confusing. Therefore, switch
case statements are often used as an alternative to long if statements
that compare a variable to several integral values (integral values are
those values that can be expressed as an integer, such as the value of
a char). Switch statements are also used to handle the input given by
the user.
Comparison with Program
Consider a program that is required to automate an interplanetary
travel agent. The program must display a list of destinations and
prompt the customer to press the number corresponding to his list.
Depending on the number entered, it must give information about the
destination. To see how a switch statement can make program-writing
easier, first consider the solution to the above problem by using nested
if-else constructs.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 96 Decesion Making Chapter 6

/*****************************************************************************/
/* Program 6.10 : Demonstration of if else construct */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int choice;
printf(“\nChoice of Destinations: \n” );
printf(“\t1 - Mercury\n” );
printf(“\t2 - venus\n”);
printf(“\t3 - Mars\n”);
printf(“Enter the number corresponding to your choice : ”);
scanf(“%i”, &choice );
printf(“\n”);
if( choice == 1)
{
puts(“Mercury is closest to the sun.”);
puts(“So the weather may be quite hot there.”);
puts(“The journey will cost you 5200 IGCs.”);
}
else
if(choice == 2 )
{
puts(“Venus is the second planet from the sun.”);
puts(“The weather may be hot and poisonous.”);
puts(“The journey will cost you 3200 IGCs.”);
}
else
if( choice == 3)
{
puts(“Mars is the closest planet to the earth.”);
puts(“The weather has been excellent till now.”);
puts(“The journey will cost you 1200 IGCs.”);
}
else
puts(“\nUnknown destination, Unpredictable IGCs.”);
puts( “\nNote: IGC = Inter-Galactic Currency” );
getch();
}
/*****************************************************************************/

 OUTPUT :
Choice of Destinations:
1 - Mercury
2 - Venus
3 - Mars
Enter the number corresponding to your choice : 2

Venus is the second planet from the sun.


The weather may be hot and poisonous.
The journey will cost you 3200 IGCs.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 97

Note: IGC = Inter-Galactic Currency

The above nested if-else construct in essence, intends to print


information about the destination if a valid destination number is
selected, or a message,
Unknow destination. Unpredictable IGCs.

Now the same example, using the switch statement is given below:

/*****************************************************************************/
/* Program 6.11 : Program to demonstrate the use of switch statement */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int choice;
printf(“\nChoice of destinations:\n” );
printf(“\t1 - Mercury\n”);
printf(“\t2 - venus\n” );
printf(“\t3 - mars\n” );
printf(“Enter the number corresponding to your choice :” );
scanf(“%i”, &choice );
printf(“\n”);
switch( choice )
{
case 1:
puts(“Mercury is closest to the sun.”);
puts(“So the weather may be quite hot there.”);
puts(“The journey will cost you 5200 IGCs.”);
break;
case 2:
puts(“Venus is the second planet from the sun.”);
puts(“The weather may be hot and poisonous.”);
puts(“The journey will cost you 320 IGCs.”);
break;
case 3:
puts(“Mars is the closest planet to the earth.”);
puts(“The weather has been excellent till now.”);
puts(“The journey will cost you 1200 IGCs.”);
break;
default:
puts(“Unknown destination. Unpredictable IGCs.”);
break;
}
puts(“\nNote: IGC = Inter-Inter-Galactic Currency”);
getch();
}
/*****************************************************************************/

The above program generates exactly the same result as the


program that used the nested if-else construct, but as you might have

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 98 Decesion Making Chapter 6

noticed, this program is easier to write and read.


ʇ NOTE
Rules for Switch Statement : Default is also a case that is
executed when the value of the
To summarize the switch case construct, go through the following variable does not match with
rules: any of the values of the case
(1) Case labels must end with a colon. statement.
(2) Each case label should be following with a constant or a constant
expression.
(3) Two case labels may have the same set of actions associated with
it.
(4) Every case label must evaluate to a unique constant expression
value.
(5) The control expression that follows the keyword switch must be
of integral type (i.e., either be an integer or any value that can
 PROGRAMMING TIPS
be converted to an integer. Keep the logical expressions
(6) The default label can be placed anywhere in the switch simple and short. For this, you
statement. But the most appropriate position of default case is may use nested if statements.

at the end of the switch case statement.


(7) There can be only one default label in a switch statement.
(8) The default label is optional and is executed only when the
value of the expression does not match with any labelled constant
expression. It is recommended to have a default case in every
switch case statement.
(9) C permits nested switch statements, i.e., a switch statement
within another switch statement.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 99

REVIEW QUESTIONS #include<stdio.h>


#include<conio.h>
void main()
6.1 Compare the use of if-else construct with that of {
ternary operator. float a=3.8;
clrscr();
6.2 When will you prefer to work with a switch switch(a)
statement? {
case 1: printf(“\n I am in U.S”);
6.3 Explain the general syntax of a switch statement getch();
and with simple example explain its use in break;
programming. case 25: printf(“\n I am in India”);
break;
6.4 Write down the flowchart of a nested if in C. case 3.8: printf(“I am in China”);
6.5 What is the purpose of the break statement? break;
default: printf(“I am at home”);
Explain with a suitable example.
}
6.6 What is a selection statement? Which selection getch ();
statements does C provide? }
6.7 What is the effect of absence of break in switch
6.3 Find out the error in the following program.
statement?
#include<stdio.h>
6.8 In a control structure switch-case, explain the #include<conio.h>
purpose of using default. void main()
{
6.9 Explain the importance of a switch case statement.
int num;
In which situations is a switch case desirable? Also clrscr();
give its limitations. printf(“Enter a number”) ;
scanf(“%d”, &num);
6.10 Why should we not use floating point numbers for if(num%2==0)
equality in expressions? goto even:
6.11 Give the syntax of a switch statement and also else
{
write an equivalent ladder it statement. printf(“Number is odd.”);
6.12 What are case labels? What type of expression getch() ;
must be used for it? }
even:
printf(“Number is even.”);
getch();

PROGRAMMING OUTPUT QUIZ


}

6.4 What is the output of the program?


#include<stdio.h>
6.1 What is the output of the following code? main()
#include<stdio.h> {
void main() int var1=12;
{ int var2=6;
char arr[]=“\0”; if(var1=5)
if(printf(“%s\n”,arr)) var2++;
printf(“Nothing\n”); printf(“%d %d\n”, var1, var2++);
else }
printf(“Something\n”);
} 6.5 What is the output of the following code?
#include<stdio.h>
 OUTPUT :
main()
Nothing
{
int var1=0;
 EXPLANATION : int var2=30;
printf will return an integer, depending on the number of char num1=1;
characters that are printed. char num2=15;
if(var1, var2, num1, num2)
6.2 Find out the error in the following code. printf(“Computer”);
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 100 Decesion Making Chapter 6

main()
6.6 What is the output of the following program?
{
#include<stdio.h> int k=1;
main() switch(k)
{ {
int var1, var2=2, num=50, a; case 1 : goto label;
if(var1=var2%2) case 2 : printf(“\nHello...“);
num=2; break;
printf(“%d %d”, num, var1); }
} printf(“\nHi ... “);
label:
6.7 What is the output of the program ? }
#include<stdio.h>
main() 6.12 What is the output of the following code?
{ #include<stdio.h>
float num=1.5; #include<conio.h>
switch(num) main()
{ {
case 1: printf(“1”); char k=4;
case 2: printf(“2”); clrscr();
default: printf(“0“); switch(k)
} {
} default:printf(“LAST\n”);
case 4:printf(“FOUR\n”);;
6.8 What is the output of the program ? case 1:break;
printf(“ONE\n”);
#include<stdio.h> case 2:printf(“TWO\n”);
#include<conio.h> break;
void main() }
{ getch();
static char k;
}
clrscr();
while(k<=10)
k>0?k++:k--; 6.13 What is the output of the following code?
if(printf(“%d\n”,k)) #include<stdio.h>
printf(“Hi Jaipur”} ; #include<conio.h>
getch(); main()
} {
int i=1,j=2;
6.9 What is the output of the program? clrscr();
switch(i,j)
#include<stdio.h> {
void main (int) default :
{ printf(“LAST”);
int y=1; break;
if(“%d=hello”, y); case 3 :
} printf(“THREE\n”);
break;
6.10 What is the output of the program? case 2:
printf(“TWO\n”) ;
#include<stdio.h>
break;
#include<conio.h>
case 1:
void main()
printf(“ONE\n”) ;
{
break;
int i=1,j=-1;
}
clrscr();
if((printf(“%d\n”, i)) <(printf(“%d\n”, j))) }
printf(“%d\n”,i);
else 6.14 What is the output of the following code?
printf(“%d\n”,j); #include<stdio.h>
getch(); #include<conio.h>
} main()
{
6.11 What is the output of the following code ? int j=4;
clrscr();
#include<stdio.h>
switch(j)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 6 Decesion Making Page 101

{ printf(“\nPractice makes man Perfect”);


default : }
printf(“LAST”); }
case 1 :
printf(“FIRST”); 6.19 What would be the output of the following program?
case 2 :
printf(“SECOND”); #include<stdio.h>
case 3 : main()
printf(“THIRD”); {
} float b=0.7;
if(b <= 0.7)
}
printf(“C”);
else
6.15 What is the output of the following code ? printf(“C++”);
#include<stdio.h> }
main()
{ 6.20 What would be the output of the following program
int y=16;
if(!!y)
?
printf(“y=%d”, !y); #include<stdio.h>
else main()
printf(“y=%d”, y); {
} float b=0.7;
if(b<=0.7f)
6.16 What is the output of the following code ? printf(“C”);
else
#include<stdio.h> printf(“C++);
main()
}
{
if(‘A’<‘a’)
printf(“Hi...”);
6.21 What is the output of the following code ?
else #include<stdio.h>
printf(“Hello...”); #include<conio.h>
} main()
{
6.17 What is the output of the program ? clrscr();
if(!!(1&&0)+!!(1 || 0))
#include<stdio.h>
print£ {“HI”);
#include<conio.h>
else
main()
printf(“HELLO”);
{
}
int m=12;
float n=12.51
clrscr();
6.22 What is the output of the following code ?
if(m=n) #include<stdio.h>
printf(“m and n are equal, m=%d, n=%:f”, m, n); #include<conio.h>
else void main()
printf(“m and n are not equal, m%d, n=%:f”,m,n); {
} int a=0,i=0;
clrscr();
6.18 What would be the output of the program ? if(a++==i++==1==!1==i)
printf(“Hi”);
#include<stdio.h> else
main{) printf(“Hello”);
{ printf(“\n%d”,a);
int num=4; }
switch(num)
{ 6.23 What is the output of the following code ?
default:
printf(“\ncomputer Science”); #include<stdio.h>
case 1 : #include<conio.h>
printf(“\n Rajasthan Technical University”); main()
break; {
case 2 : int i=1;
printf(“\nExperience makes man Exact”); int a=2;
break; clrscr();
case 3 : if(scanf(“%d”,(i==3)>&a)) /*input: 1*/
printf(“%d\n”,a);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 102 Decesion Making Chapter 6

}
6.3. Write a program for leap year checking.
6.24 What is the output of the following code? 6.4. Write a program to check an integer for perfect
#include<stdio.h> square.
#include<conio.h>
main() 6.5. Write a program to find biggest of three numbers.
{
6.6. Write a program to check the category of the
int i=4;
int s=2; entered character.
clrscr(); 6.7. Write a program to find summation of the series a+
switch(i)
{
ar + ar^2 + ... + ar^(n-1)
case s*s : printf(“\nABCDEF”); 6.8. Write a program to find grade of a student.
break;
case 2+3+1: printf(“\nGHIJKL”); 6.9. Write a program to find area of a triangle and it’s
break; type.
}
6.10. Write a program to find roots of a quadratic
}
equation.
6.11. Write a program to print all possible combinations
of 3 digits.
LAB PROGRAMS
6.12. Write a program to which accepts input a number
from 1-7 and display corresponding day of week
using switch .. case control structure.
6.1. Write a program to find smallest of three numbers. 6.13. Write a program to simulate a simple calculator.
6.14. Write a program to print first n natural numbers in
6.2. Write a program to calculate sum of first n natural ascending/descending order
numbers using goto.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

7
ITERATION

7.1 INTRODUCTION

The versatility of the computer lies in its ability to perform a set


of instructions repeatedly. This involve repeating some portion of
the program either a specified number of times or until a particular
condition is being satisfied. This repetitive operation is done through a
loop control instruction.
ʇ NOTE
7.1.1 Bounded and Unbounded Loop Iteration is also called loop.

A loop allows one to execute a statement or block of statements repeatedly.


There are mainly two types of iterations - unbounded iteration and
bounded iteration. In bounded iteration, repetition is implemented by
constructs that allow a determinate number of iterations. Bounded
loops should be used when we know, ahead of time, how many times
we need to loop. C provides for loop as bounded loop.
There are also many occasions when one doesn’t know, ahead
of time, how many iterations may be required. Such occasions require
unbounded loops. C provides two types of unbounded loop: while
loop and do... while loop. These types of loops are also known as
indeterminate or indefinite loop.

7.1.2 Pretest and Post test


A loop can either be a pre-test loop or be a post-test loop. In a pre-test
loop, the condition is checked before the beginning of each iteration.
If the test expression evaluates to true, the statements associated with
the pre-test loop are executed and the process is repeated till the test
expression becomes false. On the other hand, if the test expression
evaluates to false, the statements associated with the loop are skipped
and the statement next to the loop is executed. So for such a loop, the
statements associated with the loop may not be executed even once.
In the post-test loop, the code is always executed once. At the
completion of the loop code, the test expression is tested. If the test
expression evaluates to true, the loop repeats; if the expression is false
the loop terminates. The flowcharts in fig. 7.1 illustrate these loops.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 104 Iteration Chapter 7

Figure 7.1 : Pretest and Post-test Loop.

C has three loop structure: while, for, and do-while. The first
two are pre-test loops and do-while is a post-test loop.

7.1.3 Initialising and Updating


In addition to the test expression, two other processes are associated
with almost all loops. These are initialization and updating. The test
expression always involves a variable, which is known as a loop control
variable.
Initialization is something that initializes the loop. That is the
statement that assigns the initial value of the loop control variable.
Now, how can the test expression, that controls the loop, be true for a
while then changes to false? The answer is that something must happen
inside the loop so that the test expression becomes false. The action
that changes the test expression from true to false so that the loop is
terminated is the updating statement. This involves updating the value
of the control variable. Updating is done in each iteration. Comparison
between a pre-test and post-test loop is given in Table 7.1.

TABLE 7.1 : Comparison between a pre-test and post-test loop

Pre-test loop Post-test loop


Initialization once once
Number of tests n+1 n
Actions executed n n
Updating executed n n
Minimum iteration not even once at least once

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 105

7.1.4 Event Controlled or Count Controlled


A loop can be characterized as either event controlled or counter
controlled. In an event-controlled loop, an event changes the test
expression of the loop from true to false. When the number of repetitions
is known, then a counter-controlled loop is used. Here it is needed to
initialize the counter, test it, and update it. All the loops used in C are
either event controlled or counter controlled.

7.2 WHILE LOOP

A while loop executes statements until the condition of the while


loop evaluates to true. The loop gets terminated when the condition
becomes false. The syntax to use a while loop is shown below :

Figure 7.2 : Syntax and Flow chart of while loop


ʇ NOTE
In above syntax, the test_expression is executed. If the The statement, which is
test_ expression is true, the statements within the body of the while executed on the basis of a
loop are executed. These statements are executed repeatedly until the conditional expression, can be
either simple or compound.
test_ expression is true. Whenever the test_expression evaluates to The simple statement is written
false, the loop gets terminated. immediately after the while
We demonstrate the use of while loop with a simple statement in statement, and without using
the curly braces. However, the
program 7.1. compound statement is specified
within the curly braces.
/*****************************************************************************/
/* Program 7.1 : Using the While loop with a Simple Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int num=10;
clrscr();

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 106 Iteration Chapter 7

while(num>0)
printf(“%d\t”, num--);
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
10 9 8 7 6 4 3 2 1

 EXPLANATION :
In this program, integer variable, num is initialized with the number 10. The while
loop checks in the num variable, and decreases the value of num by using the decrement
(--) operator. The while loop stops executing, when the value of num variable become
zero.

Program 7.2 shows an example of the while loop along with a


compound statement.

/*****************************************************************************/
/* Program 7.2 : Using the While loop with a Compound Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int value,temp;
double factorial = 1;
clrscr();
printf(“\nEnter a number : ”);
scanf(“%d”, &value);
temp = value;
while(temp>0)
{
factorial*= temp;
temp--;
}
printf(“%d! = %.0f”, value, factorial);
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
Enter a number : 5
5! = 120

 EXPLANATION :
In above program, the statement Inside the while loop continues to execute until the
value stored In the temp variable becomes zero, When the value stored in the temp
variable becomes zero, then the while loop exits and displays the factorial of number

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 107

5.

A while statement can also be nested, which means a while loop


can contain another while loop in its body. Program 7.3 shows a nested
while loop:

/*****************************************************************************/
/* Program 7.3 : Creating a Nested while loop */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int num1=1, num2, num3;
clrscr();
printf(“\nEnter a number between 1 to 10: ”);
scanf(“%d”, &num3);
while(num1<= num3)
{
num2 = 1;
while(num2<=num1)
{
printf(“%d\t”, num2);
num2++;
}
printf(“\n”);
num1++;
}
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
Enter a number between 1 to 10: 6
1
1 2
1 2 3
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6

 EXPLANATION :
In Program 7.3, three integer variable, num1, num2 and num3 are declared. The num1 and
num2 variables are initialized with the number 1. You have to enter a number from 1
to 10 for the num3 variable at runtime. The outer while loop keeps track of the entered
number of the num3 variable, and the inner while loop displays the numbers stored in
the num2 variable.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 108 Iteration Chapter 7

7.3 DO WHILE LOOP

The do-while loop is used when you want to execute the loop body at
least once. It executes the statement specified in the loop body, first,
and then evaluates the condition. The do-while loop executes a group
of statements as long as the specified condition is true. If the condition
becomes false, the flow of execution comes out of the do-while loop.
The syntax to use the do-while loop is shown below :

Figure 7.3 : Syntax and Flowchart of do while loop

In above syntax, the do keyword is followed by simple or compound


ʇ NOTE
statement, and then followed by the while statement having a test_ When the do-while loop is
expression. The simple or compound statement represents the loop constructed with a simple
body of the do-while loop. The do-while loop is executed at least statement, the body of the
loop is not represented by curly
once, without depending upon the condition specified in the loop. If the braces.
condition specified in the while statement is turn out to be true, the
loop is executed again; otherwise, the loop is exited.
A sample program that inputs an integer and checks whether it
is a palindrome is given below. The program also sums up the digits of
the given number.

/*****************************************************************************/
/* Program 7.4 : To check for a palindrome */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int n, num, digit, sum = 0, rev = 0;
printf(“\nInput the number : ”);
scanf(“%d”,&num);
n = num;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 109

do
{
digit = num % 10;
sum += digit;
rev = rev * 10 + digit;
num /= 10;
}while(num!=0);
printf(“\nSum of the digits of the number = %d”,sum);
printf(“\nReverse of the number = %7d”,rev);
if(n == rev)
printf(“\nNumber is a palindrome.”);
else
printf(“\nNumber is not a palindrome.”);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run1:
Input the number: 1234
Sum of the digits of the number = 10
Reverse of the number = 4321
Number is not a palindrome.

Run2:
Input the number: 1221
Sum of the digits of the number = 6
Reverse of the number = 1221
Number is a palindrome.

 EXPLANATION :
The program checks for a palindrome using a do-while construct. Note the use of mod
operator%.

7.4 FOR LOOP

The for loop iterates over a fixed number of times and consists of three
parts, such as initialization, test expression, and updation. The syntax
of the for loop is shown in figure 7.4.
ʇ NOTE
The initialization part initializes the variable with a value. The Note that when the for loop
initialization part executes only once, which is followed by the test_ is constructed with a simple
expression. If the test_expression evaluates to true, then the body of statement, the curly braces
in the body of the loop is not
the for loop is executed. If the test_expression evaluates to false, the necessary.
the statement following the for loop is evaluated. The updation is used
to increment or decrement or updating a counter variable controlling
the loop. The for loop continues to execute until the test_expression
evaluates to false. The statementblock represents the loop body of the
for loop.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 110 Iteration Chapter 7

Figure 7.4 : Syntax and Flow chart of for loop

Following program illustrate the use of for loop.

/*****************************************************************************/
/* Program 7.5 : Using the for Loop with a simple Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
int i;
printf(“First ten even numbers are as follows:\n”);
for(i=2;i<=20;i=i+2)
printf(“%d\t”,i);
getch();
}
/*****************************************************************************/

 OUTPUT :
First ten even numbers are as follows:
2 4 6 8 10 12 14 16 18 20

 EXPLANATION :
In this program, the first 10 even numbers are displayed with the help of the for
loop. The i variable is initialized with the value 2, and incremented by 2 to display
even numbers on each iteration. The evaluation becomes false when the value of the
i variable exceeds 20 and the loop terminates.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 111

Consider another program that finds the sum, and the sum of
squares of the first 15 positive, even numbers.

/*****************************************************************************/
/* Program 7.6 : Program to illustrate the sum of the squares */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int i, n;
int sum = 0, sum_of_squares = 0;
printf(“\nEnter the Number : ”);
scanf(“%d”,&n);
for(i=2; i<=n; i+=2)
{
sum+= i;
sum_of_squares+= i*i;
}
printf(“\nSum of first positive even numbers till %d : %d”, n, sum );
printf(“\nSum of their squares : %d”, sum_of_squares );
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the Number : 14
Sum of first positive even numbers till 14 : 56
Sum of their squares : 560

Observe how, the loop variable is incremented by 2 using the


update expression
i+= 2;
The body of the loop consists of multiple statements and is,
therefore, contained within braces, forming a compound statement.
The following example uses the for loop to compute the sine series

/*****************************************************************************/
/* Program 7.7 : To compute the sine series SIN(X)=X-X^3/3!....X^N/N! */
/*****************************************************************************/
#include<stdio.h>
#include<math.h>
void main()
{
float x, t, sum;
int i, n, singn = 1;
printf(“\nInput X in degree and N : ”);
scanf(“%f%d”,&x,&n);
x*= 3.1412/180; /* Convert x into radians */
sum = t = x;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 112 Iteration Chapter 7

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


{
singn*=-1;
t = (singn*x*x)/(2*i*(2*i+i));
sum+= t;
}
printf(“SIN(X) = %6.2f\n”,sum);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run1:
Input X and N
90.00 10
SIN (X) = 1.00

Run2:
Input X and N
60.00 12
SIN(X) = 0.86

Let’s write a program to take roll number and marks of 5 students


and print the details of that student, who secured highest marks.

/*****************************************************************************/
/* Program 7.8 : Displaying Highest Marks from 5 Students */
/*****************************************************************************/
#include<stdio.h>
main()
{
int i, roll, roll_higest, marks;
int big = 0;
clrscr();
printf(“This program find the highest marks between 5 students.\n”);
for(i=0; i<5; i++)
{
printf(“\nGive roll number : ”);
scanf(“%i”,&roll);
printf(“Give marks : ”);
scanf(“%i”,&marks);
if(marks>big)
{
big = marks;
roll_higest = roll;
}
}
printf(“\nHighest marks %i secured by roll no %i.”, big, roll_higest);
getch();
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 113

/*****************************************************************************/

 OUTPUT :
This program find the highest marks between 5 students.
Give Roll number : 1001
Give marks : 23

Give Roll number : 1002


Give marks : 47

Give Roll number : 1003


Give marks : 14

Give Roll number : 1004


Give marks : 73

Give Roll number : 1005


Give marks : 57

Highest marks 73 secured by roll no 1004.

Points to Remember :
1. In a for loop, any or all the expressions can be omitted. In
case all the expressions are omitted, then there must be two
semicolons in the for statement.
2. There must be no semicolon after a for statement. If you do
that, then you will get some unexpected results. Consider the
following code.
#include <stdio.h>
main()
{
int j;
for(j=0; j<20; j++);
printf(“ %d”, j);
return 0;
}

In this code, the loop initializes j to 0 and increments its value.


Since a semicolon is placed after the loop, it means that loop does not
contain any statement. So even if the condition is true, no statement is
executed. The loop continues till j becomes 20 and the moment j=20,
the statement following the for loop is executed and the value of j(20)
is printed on the screen.
When we place a semicolon after the for statement, then the
compiler will not generate any error message. Rather it will treat the
statement as a null statement. Usually such type of null statement is
used to generate some time delays. For example, the following code
produces no output and simply delays further processing.
#include <stdio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 114 Iteration Chapter 7

main()
{
int j;
for(j=100000; j>0; j--);
printf(“%d”, j);
return 0;
}

3. Multiple initialization must be separated with a comma operator


as shown in the following code segment.
#include <stdio.h>
main()
{
int k, sum;
for(k=0, sum=0; k<10; k++)
sum+= k;
printf(“%d”, sum);
return 0;
}

4. If there is no initialization to be done, then the initialization


 PROGRAMMING TIPS
statement can be skipped by giving only a semicolon. This is Although we can place the
shown in the following code. initialization, testing and
updating the loop control
#include <stdio.h> variable outside the for loop,
main() but try to avoid it as much as
{ possible.
int j = 0;
for(;j<10; j++)
printf(“%d”, j);
return 0;
}

5. Multiple conditions in the test expression can be tested by using


the logical operator (&& or ||).
6. If the loop controlling variable is updated within the statement
block, then the third part can be skipped. This is shown in the
code given below.
#include <stdio.h>
main()
{
int k = 0;
for(;k<10;)
{
printf(“%d”, k);
k = k + 1;
}
return 0;
}

7. Multiple statements can be included in the third part of the for


statement by using the comma operator. For example, the for

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 115

statement given below is valid in C.


for(i=0, k=10; i<k; i++, k--)
8. The controlling variable can also be incremented/decremented
by values other than 1. This is shown in the code below which
prints all odd numbers from 0 to 20.
#include <stdio.h>
main()
{
int j;
for(j=1; j<=20; j+=2)
printf(“%d\t”, j);
return 0;
}

9. If the for loop contains nothing but two semicolons, that is


no initialization, condition testing and updating of the loop
control variable then the for loop may become an infinite loop
if no stopping condition is specified in the body of the loop. For
example, the following code will infinitely print Fundamental of
Computer Programming on the computer screen.
#include <stdio.h>
main()
{
for(;;)
printf(“Fundamental of Computer Programming”);
return 0;
}

10. Never use a floating point variable as the loop control variable.
This is because floating point values are just approximations and
therefore may result in imprecise values and thus inaccurate test
for termination. For example, the following code will result in an
infinite loop because of inaccuracies of floating point numbers.
#include <stdio.h>
main()
{
float j;
for(j = 100; j>=10;)
{
printf(“ %f”, j);
j = (float)j/10;
}
return 0;
}

Nested for loop


When a for loop contained another for loop, it is called a nested for
loop. In the nested for loop, execution starts from the outer for loop

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 116 Iteration Chapter 7

and the control passes to the inner for loop. The inner for loop then
continues execution till the condition of inner for loop evaluates to true.
When the inner for loop is completed, the flow of execution is passed
to the outer for loop to continue to next iteration and then again the
inner for loop is executed. This implies that for the each iteration
of the outer loop, the inner loop is executed completely. Program 7.9
shows an example of the nested for loop.

/*****************************************************************************/
/* Program 7.9 : Nesting for Loop */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int x, y, sum;
clrscr();
for(x=1;x<=2;x++)
for(y=1;y<=3;y++)
{
sum = x+y;
printf(“\nx: %d\t”,x);
printf(“y: %d\t”,y);
printf(“Sum: %d”,sum);
}
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
x: 1 y: 1 Sum: 2
x: 1 y: 2 Sum: 3
x: 1 y: 3 Sum: 4
x: 2 y: 1 Sum: 3
x: 2 y: 2 Sum: 4
x: 2 y: 3 Sum: 5

 EXPLANATION :
In this program, the execution begins with an outer for loop in which the x variable is
initialized to 1. Now, the execution enters into the inner for loop where the y variable
is set to 1. The sum of two numbers (x and y) gets printed.
The inner for loop continues to execute until the condition, y<=3, becomes false.
In this way, the inner for loop is executed three times, with the changing value of
the y variable from 1 to 3. When the inner for loop is completed, the execution goes
to the outer for loop and the x variable is set to 2. This time, the inner for loop is
executed again and the statements following this loop are executed thrice. In this way,
the outer for loop and inner for loop are in the code.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 117

7.5 JUMP STATEMENT

Jump statements are the statements that transfer control from one part
of the program to another. The jump statements supported by C are
follows:
(1) break statement
(2) continue statement
(3) goto statement

7.5.1 Break Statement


 PROGRAMMING TIPS
In C, the break statement is used to terminate the execution of the The break statement is used to
nearest enclosing loop in which it appears. We have already seen its terminate the execution of the
nearest enclosing loop in which
usage in the switch statement. The break statement is widely used with it appears.
for loop, while loop and do-while loop. When compiler encounters a
break statement, the control passes to the statement that follows the
loop in which the break statement appears. Its syntax is quite simple,
ʇ NOTE
just type keyword break followed with a semicolon. In switch statement if the
break; break statement is missing then
every case from the matched
The program given below shows the manner in which break case label till the end of the
statement is used to terminate the statement in which it is embedded. switch, including the default, is
executed.
#include <stdio.h>
int main()
{
int k = 0
while(k<=10)
{
if(k==5)
break;
printf(“\n %d”, k);
k = k + 1;
}
return 0;
}

The above code is meant to print first 10 numbers using a while


loop, but it will actually print only numbers from 0 to 4. As soon as
i becomes equal to 5, the break statement is executed and the control
jumps to the statement following the while loop.
Hence, the break statement is used to exit a loop from any point
within its body, bypassing its normal termination expression. When the
break statement is encountered inside a loop, the loop is immediately
terminated, and program control is passed to the next statement
following the loop. Figure 7.5 shows the transfer of control when the
break statement is encountered.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 118 Iteration Chapter 7

Figure 7.5 : Use of break statement in loop

Let’s write a program that explain the use of break statement.

/*****************************************************************************/
/* Program 7.10 : Using the break Statement */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
int j = 0;
clrscr();
while(“true”)
{
j = j+2;
if(j>10)
break;
printf(“%d\n”, j);
}
return 0;
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 119

 OUTPUT :
2
4
6
8
10

 EXPLANATION :
In this program, the j variable is initialized with zero value and the while loop is
used to display even numbers from 2 to infinity. However, the program displays even
numbers up to 10. This is because, an if statement checks whether the number
stored in the i variable is greater than 10; and if is greater than 10, the while loop
is terminated by the break statement.

7.5.2 Continue Statement


Like the break statement, the continue statement can only appear in
the body of a loop. When the compiler encounters a continue statement
then the rest of the statements in the loop are skipped and the control
is unconditionally transferred to the loop-continuation portion of the
 PROGRAMMING TIPS
nearest enclosing loop. Its syntax is quite simple, just type keyword When the compiler encounters
continue followed with a semicolon. a continue statement, then the
rest of the statements in the
continue; loop are skipped and the control
is unconditionally transferred to
Again like the break statement, the continue statement cannot
the loop-continuation portion of
be used without an enclosing for, while, or do-while statement. When the nearest loop.
the continue statement is encountered in the while loop and in the do-
while, the control is transferred to the code that tests the controlling
expression. However, if placed with a for loop, the continue statement
causes a branch to the code that updates the loop variable. For example,
look at the following code.
#include <stdio.h>
int main()
{
int k;
for(k=0; k<=10; k++)
{
if(k==6)
continue;
printf(“\t %d”, k);
k = k + 1;
}
return 0;
}
 PROGRAMMING TIPS
The code given here is meant to print numbers from 0 to 10. But As far as possible, try not
as soon as i becomes equal to 6, the continue statement is encountered, to use goto, break, and
so rest of the statements in the for loop are skipped and the control continue statement as they
violate the rules of structured
passes to the expression that increments the value of k. The output of programming.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 120 Iteration Chapter 7

this program would thus be


0 1 2 3 4 5 7 8 9 10
Note that there is no 6 in the series. It could not be printed, as
continue caused early incrementation of k and skipping of the statement
that printed the value of i on screen.
Figure 7.6 illustrates the use of continue statement in loops.

Figure 7.6 : Use of continue statement in loop

Hence, we see that the continue statement is somewhat the


opposite of the break statement. It forces the next iteration of the
loop to take place, skipping any code in between itself and the test
condition of the loop. The continue statement is usually used to restart
a statement sequence when an error occurs.
Programs given below demonstrate the use of break and continue
statement.

/*****************************************************************************/
/* Program 7.11 : To calculate square root of a number */
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 121

#include <stdio.h>
#include <math.h>
main()
{
int num;
do
{
printf(“\nEnter any number. Enter 999 to stop : ”);
scanf(“%d”, &num);
if(num == 999)
break; /* quit the loop */
if (num < 0)
{
printf(“\nSquare root of negative numbers is not defined.”);
continue; /* skip the following statements */
}
printf(“\n The square root of %d is %.2f.”,num, sqrt(num));
}while(1);
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter any number. Enter 999 to stop : 49
The square root of 49 is 7.00.
Enter any number. Enter 999 to stop : -34
Square root of negative numbers is not defined.
Enter any number. Enter 999 to stop : 81
The square root of 81 is 9.00.
Enter any number. Enter 999 to stop : 999

/*****************************************************************************/
/* Program 7.12 : Using the continue Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
for(i=2;i<=20;i=i+2)
{
if(i==6 || i==14)
continue;
printf(“%d\t”,i);
}
getch();
return 0;
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 122 Iteration Chapter 7

/*****************************************************************************/

 OUTPUT :
2 4 8 10 12 16 20

 EXPLANATION :
In Program 7.12, first 10 even numbers are shown, excluding 6 and 14 from the result.
This is done with the help of the continue statement inside an if condition, which gets
executed in case the value of i variable becomes either 6 or 14. In the output of this
program, even numbers are shown successfully until the value of i becomes 6 or 14.
When the value of i becomes 6, the control of execution quits from the current loop
and returns back to the for loop. The next iteration then displays the remaining even
numbers till the value of i becomes 14. Then, the control of execution again quits
the current loop and returns back to the for loop. The next iteration displays the
remaining even numbers.

7.5.3 Goto Statement


The goto statement is used to transfer control to a specified label.
However, the label must reside in the same function and can appear
only before one statement in the same function. The syntax of goto
ʇ NOTE
statement is as shown in figure 7.7. Computer scientists usually
avoid this statement in favour
of the ‘structured programming’
paradigm. Some scientists think
that the goto statement should
be abolished from higher-
level languages because they
complicate the task of analysing
and verifying the correctness
of programs (particularly those
involving loops).
Figure 7.7 : Use of goto statement

Here, label is an identifier that specifies the place where the


branch is to be made. Label can be any valid variable name that is
followed by a colon (:). The label is placed immediately before the
statement where the control has to be transferred.
The label can be placed anywhere in the program either before or
after the goto statement. Whenever the goto statement is encountered
the control is immediately transferred to the statements following the
label. Therefore, goto statement breaks the normal sequential execution
of the program. If the label is placed after the goto statement, then
it is called a forward jump and in case it is located before the goto
 PROGRAMMING TIPS
statement, it is said to be a backward jump. It is good programming style
The goto statement is often combined with the if statement to to use the break, continue, and
cause a conditional transfer of control. return statement in preference
to goto whenever possible.
if(condition)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 123

goto lable;

The code given below demonstrates the use of a goto statement.


The program calculates the sum of all positive numbers entered by the
user.

/*****************************************************************************/
/* Program 7.13 : Calculates the sum of all positive numbers entered */
/*****************************************************************************/

#include <stdio.h>
main()
{
int num, sum=0;
printf(“\nThis program find the sum of all positive number entered.”);
read: /* label for goto statement */
printf(“\nEnter the number. Enter 0 to end : ”);
scanf(“%d”, &num);
if(num!=0)
{
if(num < 0)
goto read; /* jump to label - read */
sum+= num;
goto read; /* jump to label - read */
}
printf(“\nSum of the all positive numbers entered by the user is %d.”, sum);
printf(“\nProgram End. Press any Key”);
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
This program find the sum of all positive number entered.
Enter the number. Enter 0 to end : 23
Enter the number. Enter 0 to end : 34
Enter the number. Enter 0 to end : 78
Enter the number. Enter 0 to end : -45
Enter the number. Enter 0 to end : 67
Enter the number. Enter 0 to end : 0
Sum of the all positive numbers entered by the user is = 202
Program End. Press any Key

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 124 Iteration Chapter 7

REVIEW QUESTIONS }
while(i<4);
getch();
7.1 Write a short not on iterative statements that C }
language supports.
7.3 The following code is written to get the sum of all
7.2 Give the syntax of for loop and explain how it the even integer numbers between 1 to 10. Identify
works, with an example. the error.
7.3 Give the points of similarity and differences between #include<stdio.h>
a while loop and a do-while loop. #include<conio.h>
void main()
7.4 Distinguish between the break and the continue
{
statement. int i, j=0;
7.5 Write a short note on goto statement? Why should clrscr();
for(i=0;i<10;);
it be avoided?
{
7.6 Write a program which demonstrates the use of j =j+i;
goto, break, and continue statements. i+=2;
}
7.7 In what situation will you prefer to use for, while printf(“Sum of first 10 even numbers is:%d” ,j);
and do-while loop? getoh();
}
7.8 Can we use a for loop when the number of iterations
is not known in advance? If yes, give a program that 7.4 Find out the error in the following program.
illustrates how this can be done. #include<stdio.h>
7.9 Explain the difference between break and continue #include<conio.h>
statements of C language. void main()
{
int i;
printf(“Enter the value of i :”);
scanf(“%d”, &i);
PROGRAMMING OUTPUT QUIZ if(i<7)
{
i++;
continue;
7.1 We require a code to print the integer values from
}
0 to 9. Identify the error ? printf(“Final value of i is: %d”, i);
#include<stdio.h> getch();
#include<conio.h> }
void main()
{ 7.5 What is the output of the following code?
static int i;
#include<stdio.h>
clrscr();
main()
for(;i<=9;);
{
{
int var=0;
printf(“\nvalue is: %d”,i);
for(;var++;printf(“%d”, var));
i++;
printf(“%d”,var);
}
}
getch();
}
7.6 What is the output of the following program?
7.2 Find the output of the following code ? #include<stdio.h>
void main()
#include<stdio.h>
{
#include<conio.h>
while(1)
void main()
{
{
if(printf(“%d”,printf(“%d”)))
int i;
break;
printf(“Enter the value of i : “);
else
scanf(“%d”,&i); /* input: 5 */
continue;
clrscr();
}
do
}
{
i++;
printf(“\nHello User”);
7.7 What is the output of the following code ?

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 125

#include<stdio.h> break;
#include<conio.h> case 3:printf(“%d”,i);
main() case 4:printf(“%d”,i);
{ }
int i; }
clrscr();
for(i=1;i<10, printf(“Hi ... “);i++) 7.13 What is the output of the program?
{
#include<stdio.h>
if(i<5)
#include<conio.h>
break;
void main()
break; continue; break;
{
break;
int i=1,j=1;
printf(“Hello ... “);
clrscr();
}
while(++i <= 15)
}
{j++;}
printf(“%d%d”,i,j);
7.8 What is the output of the following code ? getch();
#include<stdio.h> }
main()
{ 7.14 What is the output of the program ?
signed char i=0;
#include<stdio.h>
for(;i>=0;i++);
#include<conio.h>
printf(“%d\n”,i);
void main()
}
{
int i=5;
7.9 What is the output of the following program? clrscr();
#include<stdio.h> for(;i;printf(“%d”,i--));
main() getch();
{ }
unsigned char var=0;
for(;var>=0;var++); 7.15 What is the output of the following code?
printf(“%d\n”,var);
#include<stdio.h>
}
main()
{
7.10 What is the output of the following program? char j;
#include<stdio.h> for(j=1;100;j++)
main() printf(“%d\n”,j);
{ }
int var=3;
for(;var++=0;) 7.16 What is the output of the following code ?
printf(“%d”,var);
#include<stdio.h>
}
main()
{
7.11 What is the output of lhe program? int j;
#include<stdio.h> for(j=0;j++ <= 4; printf(“%d”,j));
void main() }
{
signed char var; 7.17 What is the output of the following code ?
for(var=0;var<=127;var++)
#include<stdio.h>
printf(“%c%d \n”,var,var);
#include<conio.h>
}
main()
{
7.12 What is the output of the program ? char i=128;
#include<stdio.h> clrscr();
main() while(i)
{ {
int i; printf(“%d\n”,i);
for(i=1;i<4;i++) i=i+l;
switch(i) }
{ }
case 1:printf(“%d”,i);
break; 7.18 What is the output of the following code ?
case 2:printf(“%d”,i);
#include<stdio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 126 Iteration Chapter 7

#include<conio.h>
7.22 Find out the error in the following code.
main()
{ #include<stdio.h>
int i==2; #include<conio.h>
clrscr(); void main()
do {
{ int x, y, Z;
printf(“%d\n”, i); clrscr();
}while(i=0); for(x=y=0;x<10;x++;y+=2)
printf(“%d”, i); {
} if((y-x)<=2)
{
7.19 What is the output of the following code ? printf(“\n\n %d”,(z=y-x));
getch();
#include<stdio.h> }
#include<conio.h> else
main() {
{ printf(“\n\n\n %d”, x);
clrscr(); getch();
switch(0) }
printf(“A”); }
while(0) }
printf(“B”);
if(0)
7.23 What is the output of the following code ?
printf(“C”);
for(;0;) #include<stdio.h>
printf(“D”); #include<conio.h>
do main()
{ {
printf(“E”); int a=0;
}while(0); clrscr();
} for(a=0;a<=3;a++)
{
7.20 What is the output of the following code ? switch(a)
{
#include<stdio.h> case 0 : a+=1;
#include<conio.h> case 1 : a+=2;
main() case 2 : a+=3;
{ default : a+=4;
unsigned char i; break;
clrscr(); }
for(i=~10;i<-1;i++) printf(“%d\n”,a);
printf(“%d\n”,i); }
printf(“%d\n”,i); }
}

7.21 Find out the error in the following code.


#include<stdio.h> LAB PROGRAMS
#include<conio.h>
void main()
{ 7.1. Write a program to print first n natural numbers
int i=1,j; and their sum using while loop.
clrscr();
do 7.2. Write a program to generate fibonacci terms upto
{ a specific limit.
for(j=1;;j++)
{ 7.3. Write a program which count number of l’s in the
if(j>2) binary representation of an integer.
break;
if(i==j) 7.4. Write a program to generate first n fibonacci terms.
continue; 7.5. Write a program to find GCD and LCM of two non
printf(“\n%d%d”,i,j);
}
negative integers
i++; 7.6. Write a program to which display the reverse of
}while(i<3)
given integer and check it for palindrome.
getch();
} 7.7. Write a program to generate primes upto a specific

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 7 Iteration Page 127

limit and display their number. positive integers.


7.8. Write a program to calculate area of circle until 7.30. Write a program to display the numbers and their
radius 0 is entered. sum between 100 and 200 which are divisible by 7.
7.9. Write a program to check a number for Amstrong 7.31. Write a program to display sum of even and odd
It is a number which wquals the sum of cubes of numbers from 1 to N.
it’s digit. 7.32. Write a program to calculate the value of sin(x)
7.10. Write a program to display first n prime numbers. using the series x- x^3/3! + x^5/5! ... upto N terms
7.11. Write a program to find the occurences of positive accuracy without using the user defined functions
numbers, negative numbers and zeros in a stream and display sin(x) using library function also
of data terminated by some specific value. 7.33. Write a program to calculate the value of cos(x)
7.12. Write a program to check a number for prime. using the series 1- x^2/2! + x^4/4! ... upto N terms
accuracy without using the user defined functions
7.13. Write a program to check a number for fibonacci and display cos(x) using library function also
term
7.34. Write a program to generate the following pyramid
7.14. Write a program to compare the number of vowels of numbers.
and non vowels. Terminate the input with character 1
‘?’. 232
34543
7.15. Write a program to display sum of first n even/odd 4567654
numbers in ascending/descending order. 567898765
67890109876
7.16. Write a program to calculate sum of digits of a 7890123210987
number and display the reverse of it. 890123454321098
90123456765432109
7.17. Write a program to print first n natural numbers
0123456789876543210
and their sum using do-while loop.
7.35. Write a program generate the following pyramid
7.18. Write a program to calculate the area of either 1
circle or rectangle or triangle depending upon the 121
user’s choice. 12321
1234321
7.19. Write a program to display the prime factors of a 123454321
positive integer. 12345654321
7.20. Write a program to display number of days in a 7.36. Write a program to display the following pattern
month. * * * * *
* * * *
7.21. Write a program to convert centigrade temperature * * *
to fahrenheit and vice versa. * *
*
7.22. Write a program to find the sum of series
x+(x^2)+(x^3)+(x^4)+(x^5)+ ......... 7.37. Write a program to display the following pattern
1
7.23. Write a program to display multiplication table of 1 2
a given number. 1 2 3
1 2 3 4
7.24. Write a program to display first n natural numbers 1 2 3 4 5
and their sum using for loop. 1 2 3 4 5 6
7.25. Write a program to display the factorial of a 7.38. Write a program to display the following pattern
number. 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
7.26. Write a program to read N numbers iteratively and 1 2 3 4 5 6
display biggest and smallest of these numbers. 1 2 3 4 5
1 2 3 4
7.27. Write a program to display all divisors of a positive 1 2
integer. 1
7.28. Write a program to check a number for perfect 7.39. Write a program to display the following pattern
number. 1
2 2
7.29. Write a program to read 10 integers from the 3 3 3
keyboard and display number of negative and 4 4 4 4

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 128 Iteration Chapter 7

5 5 5 5 5 1+2+3+4+5+6+7+8+9+10+11+12+13=91
6 6 6 6 6 6 1+2+3+4+5+6+7+8+9+10+11+12+13+14=105

7.40. Write a program to display the pattern of digits. 7.43. Write a program to display the following pattern of
1234567 n lines using nested loops
123456 A
12345 ABC
1234 ABCDE
123 ABCDEFG
12 ABCDEFGHI
1 ABCDEFGHIJK
12
123 7.44. Write a program to display the following pattern
1234 of digits.
12345 6
123456 6 5 6
1234567 6 5 4 5 6
6 5 4 3 4 5 6
7.41. Write a program to display the following pattern 6 5 4 3 2 3 4 5 6
7 6 5 4 3 2 1
6 5 4 3 2 1 2 3 4 5 6
6 5 4 3 2 1
6 5 4 3 2 3 4 5 6
5 4 3 2 1
6 5 4 3 4 5 6
4 3 2 1
6 5 4 5 6
3 2 1
6 5 5
2 1
6
1
7.45. Write a program to display Armstrong numbers
7.42. Write a program to display the following pattern
1=1
upto a specific limit.
1+2=3 7.46. Write a program to display perfect numbers upto a
1+2+3=6
sepecific limit.
1+2+3+4=10
1+2+3+4+5=15 7.47. Write a program to determine all pythagorean
1+2+3+4+5+6=21 triplets in the range 1 to 100.
1+2+3+4+5+6+7=28
1+2+3+4+5+6+7+8=36 7.48. Write a program to display composite numbers
1+2+3+4+5+6+7+8+9=45 between 1 to n.
1+2+3+4+5+6+7+8+9+10=55
1+2+3+4+5+6+7+8+9+10+11=66 7.49. Write a program to convert decimal numeral to
1+2+3+4+5+6+7+8+9+10+11+12=78 roman numeral.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

8
ARRAY

8.1 INTRODUCTION

Take a situation in which we have 25 students in a class and we are


asked to write a program that reads and prints the marks of all these
25 students. In this program, we will need 25 integer variables with
different names, as shown in figure 8.1.

Figure 8.1 : : Twenty five Variable with Different Names

Now to read values for these 25 different variables, we must have


25 read statements. Similarly, to print the value of these variables, we
need 25 write statements. If it is just a matter of 25 variables, then it
might be acceptable for the user to follow this approach. But imagine,
will it be possible to follow this approach if we had to read and print
marks of the students
 in the entire course (say 100 students)
 in the entire college (say 500 students)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 130 Array Chapter 8

 in the entire university (say 10000 students)


The answer is no, definitely not. To process large amount of data,
we need a data structure known as array.

8.2 ARRAY

An array is a collection of same type of values stored in consecutive


memory locations. It can be used to store the values of different data
types, such as int, float, double, char, and string. Each value in an
array is referenced by a single name, which is the name of the array,
and a subscript or index, which indicates the position of the value in
the array. The subscript is a positive integer number, which is enclosed
in a pair of square brackets. As subscripts are used in arrays, they are
also referred as subscripted variables.
The individual values in an array are called the elements of the
array. The structure of an array, myArray, containing n elements is
shown in figure 8.2.

Figure 8.2 : : Structure of an Array

In figure 8.2, myArray[0] represents the first element of the array,


myArray[1] represents the second element of the array, myArray[2]
represents the third element of the array, and myArray[n-1] represents
the nth element of the array.

8.3 TYPE OF ARRAY

Arrays can be broadly classified into two types: one-dimensional arrays


and multi-dimensional arrays. A one-dimensional array has only one
subscript and a multi-dimensional array has n subscripts, where n
represents the dimensions of the array. Multi-dimensional array can be
further classified into two-dimensional and three-dimensional arrays.
The dimensionality of an array is determined by the number of pairs
of square brackets placed after the array name. For example, array1[
] represents a one-dimensional array, array2[ ][ ] represents a two-
dimensional array, and array3[ ][ ][ ] represents a three-dimensional
array. Each pair of square brackets contains the number of elements
corresponding to a specific dimension.

8.4 ONE DIMENSIONAL ARRAY

A one-dimensional array or a single dimensional array is used to store a


linear list of values of the same type. The elements in a one-dimensional

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 131

array are stored with the index values starting from zero to one less
than the size of the array. Each element in a one-dimensional array is
accessed using the same name and a single subscript. A one-dimensional
array is similar to a row matrix or a column matrix.

8.5 DECLARING ONE DIMENSIONAL ARRAY

Similar to an ordinary variable, you need to declare an array before


using it. A one-dimensional array can be declared using the following
syntax:
data_type array_name[size];
In the above syntax, data_type represents the data type of the
array to be declared, array_name represents the name of the array, and
size represents the number of value of the data_type type that can be
stored in the array_name array.
The following statement declares an integer array, myArray, of size
10:
int myArray[10];
In this example, the myArray array can contain 10 elements, which
are indexed 0 to 9. If the data type and the number of elements in a
one-dimensional array are known, then total amount of memory that
can be allocated to the array can be calculated using the following
formula:
Total_memory = size * [sizeof(data_type)]
In this formula, size represents the number of elements that can
be stored in the array, sizeof is a unary operator used to calculate
the size in bytes, and data_type represents the data type of the array.
Using the preceding formula, the total amount of memory required for
a one-dimensional of size 10 is 20 bytes since the size of an integer data
type is 2 bytes.
Points To Remember :
1. C does not allow declaring an array whose number of elements
is not known at the compile time. Therefore, the following array
declarations are illegal in C :
in arr[];
int n, myArray[n];

2. It is a good programming practice to define the size of an array


as a symbolic constant as shown in the following code.
#include <stdio.h>
#define N 200
main()
{
int myArray[N]

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 132 Array Chapter 8

..........
..........
}

3. Size of the array can be specified using an expression. However,


the component of the expression must be available for evaluation
of the expression when the program is compiled. Therefore the
following array declaration are valid :
ʇ NOTE
#include <stdio.h>
C array indices start from 0. So
#define N 200 for an array with N elements,
main() the index of the last element is
{ N-1.
int i = 100
int myArray1[N+10], myArray2[i - 2*20]
..........
..........
}

4. C never checks the validity of the array index neither at compile


time nor at run time. So even if you declare an array as
int myAarry[N];
the C compiler will not raise any error but the result of running
such code is totally unpredictable. Even if you declare an array
of 10 elements and later on by mistake try to access the 11th
element, no error will be generated. But the results will be
unpredictable as the memory occupied by the (so-called) 11th
element may be storing data of another object.

8.6 STORING VALUES IN ONE DIMENSIONAL ARRAYS

When we declare and define an array, we are just allocating space for
the elements; no values are stored in the array. To store values in the
array, there are three ways
 to initialize the array elements,
 to input value for every individual element
 to assign values to the elements.
This is shown in following figure .

Figure 8.3 : Storing Values in Array

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 133

8.6.1 Initialization of Arrays


ʇ NOTE
Elements of the array can also be initialized at the time of declaration By default, the elements of the
similar to other variables. When an array is initialized, we need to array are not initialized, They
may contain some garbage
provide a value for every element in the array. Arrays are initialized by value, so before using the array
writing, you must initialize the array or
read some meaningful data into
data_type array_name[size] = {list of values};
it.
The values are written with curly brackets and every value is
separated by a comma. It is a compiler error to specify more number of
values than the number of elements in the array. When we write,
int marks[7] = {85, 56, 34, 78, 93, 39, 64};
ʇ NOTE
an array with name marks is declared that has space that is enough to If we have more initializers than
store 7 elements. The first element, i.e., marks[0] is assigned with the the declared size of the array,
then a compile time error will
value 56. Similarly, the second element of the array, i.e., marks[1] has be generated. For example, the
been assigned 42, and so on. This is shown in figure 8.4. following statement will result
in a compiler error.
int marks[3] = {1,2,3,4};

Figure 8.4 : Initialization of Array marks[6]

While initializing the array at the time of declaration, the


programmer may omit to mention the size of the array. For example,
int marks[] = {89, 79, 45};
The above statement is absolutely legal. Here, the compiler
will allocate enough space for all initialized elements. If the number
of values provided is less than the number of elements in the array,
the un-assigned elements are filled with zeros. Figure 7.6.5 illustrates
initialization of arrays.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 134 Array Chapter 8

Figure 8.5 : Initialization of of Array Elements in different way

Program 8.1 shows how to initialize array elements one by one:

/*****************************************************************************/
/* Program 8.1 : Initializing All the Array Elements at the Same Time */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5] = {34, 123, 375, 267, 745};
int i;
clrscr();
printf(“Elements of the array are:\n”);
for(i=0; i<5; i++)
printf(“%d\t”, arr[i]);
getch();
}

/*****************************************************************************/

 OUTPUT :
Elements of the array are:
34 123 375 267 745

ʇ NOTE
8.6.2 Inputting Values The C language does not
perform bound checking for
An array can be filled by inputting values from the keyboard. In this arrays; therefore, you need to
method, a while/do-while or a for loop is executed to input the value ensure that you are not trying
to access an array element that
for each element of the array. For example, look at the code shown falls outside the array boundary.
below

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 135

int i, marks[20];
for(i=0; i<20; i++)
scanf(“%d”, &marks[i]);

In the code, we start with the index i at 0 and input the value
for the first element of the array. Since the array can have 20 elements,
we must input values for elements whose index varies from 0 to 19.
Therefore, in the for loop, we test for condition (i<20) which means
the number of elements in the array.
Program 8.2 shows how to input values to array.

/*****************************************************************************/
/* Program 8.2 : Inputting Values to Array */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[30], i, n;
clrscr();
printf(“\nEnter the size of the array : ”);
scanf(“%d”, &n);
printf(“\nEnter the elements of the array :\n”);
for(i=0; i < n; i++)
scanf(“%d”, &arr[i]);
printf(“\nElements of the array are:\n”);
for(i=0; i<n; i++)
printf(“%d\t”, arr[i]);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the size of the array : 6
Enter the elements of the array:
20 40 60 80 100 120
Elements of the array are:
20 40 60 80 100 120

8.6.3 Assigning Values


The third way to assign values to individual elements of the array
is by using the assignment operator. Any value that evaluates to an
appropriate data type as that of the array can be assigned to the
individual array element. A simple assignment statement can be written
as,
marks[4] = 200;
Here, 200 is assigned to the fourth element of the array which is

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 136 Array Chapter 8

specified as marks[4].
We cannot assign one array to another array, even if the two arrays
have the same type and size. To copy an array, you must copy the value
of every element of the first array into the element of the second array.
Following statements illustrates the code to copy an array.
int j , array1[16], array2[16];
for(j=0; j<10; j++)
array2[j] = array1[j];

In this example, the code accesses each element of the first array
and simultaneously assigns its value to the corresponding element of
the second array. Finally, the index value j is incremented to access the
next element in succession. Therefore, when this code is executed,
array2[0] = array1[0];
array2[1] = array1[1];
array2[2] = array1[2];

and so on.
We can also use a loop to assign a pattern of values to the array
elements. For example, if we want to fill an array with even integers
starting (from 0), then we will write the code as below
int i, myArray[10];
for(i=0; i<10; i++)
myArray[i] = i*2;

In the code, we assign to each element value equal to twice of its


index, where index starts from zero. So after executing this code we will
have, myArray[0] = 0, myArray[1] = 2, myArray[2] = 4, and so on.
Program 8.3 illustrate how the values can be assigned to array
elements.

/*****************************************************************************/
/* Program 8.3 : To read and display n random numbers using an array */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define MAX 10
main()
{
int arr[MAX], i, RandNo;
for(i=0; i<MAX; i++)
{
RandNo = rand()%MAX; /* Scale the random number in the range 0 to MAX-1 */
arr[i] = RandNo; /*rand() is a pre-defined function */
}
printf(“\nThe contents of the array are:\n”);
for(i=0; i<MAX; i++)
printf(“%d\t”, arr[i]);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 137

getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
The contents of the array are:
6 0 2 0 6 7 5 5 8 6

8.7 ACCESSING ELEMENTS OF ONE DIMENSIONAL ARRAY

For accessing an individual element of the array, the array subscript


must be used. For example, to access the fourth element of the array,
you must write myArray[3]. The subscript/index must be an integer
value or an expression that evaluates to an integer value.
To access all the elements of the array, you must use a loop. That
is, we can access all the elements of the array by varying the value of
the subscript into the array. The subscript must be an integral value
ʇ NOTE
or an expression that evaluates to an integral value. The first element Although storing the related
of the array marks[8] can be accessed by writing, marks[0]. Now to data items in a single array
process all the elements of the array, we will use a loop as shown below. enables the programmers to
develop concise and efficient
int i, marks[8]; programs there in no single
for(i=0; i<8; i++) operation that can operate on
marks[i] = -1; all the elements of the array.

Figure 8.6 shows the result of the above code. The code accesses
every individual element of the array and sets its value to -1. In the for
loop, first the value of marks[0] is set to -1, then the value of the index
(i) is incremented and the next value, i.e., marks[1] is set to -1. The
procedure is continued until all the 8 elements of the array are set to -1.

Figure 8.6 : Array marks[i]

The name of the array is a symbolic reference for the address


to the first byte of the array. Therefore, whenever we use the array
name, we are actually referring to the first byte of the array. The index
specifies an offset from the beginning of the array to the element being
referenced.
Now we consider few programs given below.

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 138 Array Chapter 8

/* Program 8.4 : To read and display n numbers using an array */


/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
int main()
{
int i=0, n, arr[20];
clrscr();
printf(“Enter the number of elements:”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\nArr[%d] = ”, i);
scanf(“%d”, &arr[i]);
}
printf(“\nThe array elements are\n“);
for(i=0;i<n;i++)
printf(“Arr[%d] = %d, ”, i, arr[i]);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter the number of elements: 5
Arr[0] = 5
Arr[1] = 4
Arr[3] = 3
Arr[4] = 2
Arr[5] = 1
The array elements are
Arr[0] = 5 Arr[1] = 4 Arr[3] = 3 Arr[4] = 2 Arr[5] = 1

/*****************************************************************************/
/* Program 8.5 : To find mean of n numbers using arrays */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, arr[25], sum =0;
float mean = 0.0;
clrscr();
printf(“Enter the number of elements in the array: ”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\nArr[%d] = ”, i);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 139

scanf(“%d”, &arr[i]);
}
for(i=0;i<n;i++)
sum+= arr[i];
mean = sum/n;
printf(“\nSum of the array elements = %d”, sum);
printf(“\nMean of the array elements = %.2f”, mean);
getch(0);
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter the number of elements in the array: 5
Arr[0] = 1
Arr[1] = 2
Arr[2] = 3
Arr[3] = 4
Arr[4] = 5
Sum of the array elements = 15
Mean of the array elements = 3.00

/*****************************************************************************/
/* Program 8.6 : To generate first n terms FIBONACCI series */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main() {
int fib[50], n, i;
clrscr();
printf(“\nEnter the number of terms to generate : ”);
scanf(“%d”, &n);
fib[0] = 0;
fib[1] = 1;
printf(“\nFibonacci series :\n”);
for(i=2; i<n; i++)
fib[i] = fib[i-1] + fib[i-2];
for (i=0; i<n; i++)
printf(“%d\t”, fib[i]);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run 1
Enter the number of terms to generate : 6
Fibonacci series :

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 140 Array Chapter 8

0 1 1 2 3 5
Run 2
Enter the number of terms to generate : 9
Fibonacci series :
0 1 1 2 3 5 8 13 21

/*****************************************************************************/
/* Program 8.7 : To generate sum of two array */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], b[20], c[20];
int i, n;
clrscr();
printf(“\nEnter the number of elements for each array : ”);
scanf(“%d”, &n);
printf(“\nEnter the elements of array a:\n”);
for(i=0; i<n; i++)
scanf(“%d”, &a[i]);
printf(“\nEnter the elements of array b:\n”);
for(i=0; i<n; i++)
scanf(“%d”, &b[i]);
for(i=0; i<n; i++)
c[i] = a[i] + b[i];
printf(“Elements of array c:\n”);
for (i=0; i<n; i++)
printf(“%d\t”, c[i]);
getch();
}
/*****************************************************************************/

 OUTPUT :
Enter the number of elements for each array : 5
Enter the elements of array a:
23 45 12 45 34
Enter the elements of array b:
12 45 43 56 12
Elements of array c:
35 90 55 101 46

8.8 ADDRESS AND LENGTH OF ARRAY ELEMENTS

The subscript or the index represents the offset from the beginning of
the array to the element being referenced. With just the array name
and the index, C can calculate the address of any element in the array.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 141

An array stores all its data elements in consecutive memory


ʇ NOTE
locations. So, storing just the base address, i.e., the address of the first You must be wondering, how
element in the array is sufficient. The address of other data elements C knows where an individual
can simply be calculated using the base address. The formula for doing element of the array is located in
the memory? The answer is that
this calculation is, the array name is a symbolic
Address of data element, A[k] = BA(A) + w(k - lower_bound) reference for the address to the
first byte of the array. When
Here, A is the array, k is the index of the element for which we we use the array name, we are
have to calculate the address, BA is the base address of the array A, w actually referring to the first
byte of the array.
is the word size of one element in memory (for example, size of int is 2),
and lower_bound is the index of the first element in the array.
Length of the array is given by the number of elements stored in
it. The general formula to calculate the length of the array is,
Length = upper_bound - lower_bound + 1
where upper_bound is the index of the last element and lower_
bound is the index of the first element in the array.

8.9 TWO DIMENSIONAL ARRAY

A two-dimensional array is used to store a table of values of the same


data type. It is similar to a matrix containing rows and columns. You
can perform a number of operations on matrices using two-dimensional
arrays. Some of these operations are as follows:
 Reading and displaying elements of a matrix
 Adding and subtracting the corresponding elements of two
matrices
 Multiplying two matrices
 Searching and sorting elements in a matrix

8.9.1 Declaring a Two-Dimensional Array


In C, you can declare a two-dimensional array using the following
syntax:
data_type array_name[size1][size2];
In this syntax, data_type represents the data type of the array
to be declared, array_name represents the name of the array, size1
represents the number of rows, and size2 represents the number of
columns.
The following line of code declares a two-dimensional integer
array, myArray:
int myArray[5][6];
In the above example, the myArray array is a two-dimensional
array containing 5 rows and 6 columns.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 142 Array Chapter 8

8.9.2 Initializing a Two-Dimensional Array


Similar to a one-dimensional array, the elements of a two-dimensional
array can be initialized either one at a time or all at once. The syntax
for initializing the elements of a two-dimensional array is as follows:
data_type array_name[size1][size2] = {value1, value2, value3,...,valuen}
The following line of code declares and initializes a two-dimensional
integer array, myArray:
int myArray[2][3] = {10, 20, 30, 40, 50, 60};
Initialization of the array elements in the preceding line of code is
equivalent to initializing each array element separately as follows:
myArray[0][0] = 10;
myArray[0][1] = 20;
myArray[0][2] = 30;
myArray[1][0] = 40;
myArray[1][1] = 50;
myArray[1][2] = 60;

8.9.3 Accessing the Elements of Two - Dimensional Array


The elements in a multidimensional array are stored in contiguous
memory locations. While accessing the elements, remember that the
last subscript varies most rapidly whereas the first varies least rapidly.
In case of one-dimensional arrays we used a single for loop to
vary the index i in every pass, so the all the elements could be scanned.
Similarly, since a two-dimensional array contains two subscripts, we will
use two for loops to scan the elements. The first for loop will loop for
each row in the 2D array and the second for loop will scan individual
columns for every row in the array.
However, individual elements of a two-dimensional array can be
initialized using the assignment operator as shown below.
marks[1][2] = 79;
marks[1][2] = marks[1][1] + 10;

In order to input the values from the keyboard, you must use the
following code.
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”, &arr[i][j]);

Look at the code given below which prints the elements of a 2D


array on the screen.
Program 8.8 shows the declaring, initializing, and accessing
elements of a Two-Dimensional Array.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 143

/*****************************************************************************/
/* Program 8.8 : Using Two-dimensional Array */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[4][4]={ {1,2,3,4}, {2,3,4,1}, {3,4,1,2}, {4,1,2,3},};
int i, j, m=4, n=4;
clrscr();
printf(“Elements of the array are:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d “,arr[i][j]);
printf(“\n”);
}
getch();
}
/*****************************************************************************/

 OUTPUT :
Elements of the array are:
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3

Program 8.9 takes the values of 2 dimensional array from users


and then print them.

/*****************************************************************************/
/* Program 8.9 : To read and print a two-dimensional array */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10][10], i, j, m, n;
clrscr();
printf(“\nEnter the number of rows in the array : ”);
scanf(“%d”, &m);
printf(“\nEnter the number of columns in the array : ”);
scanf(“%d”, &n);
printf(“\nEnter the elements of the array:\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
scanf(“%d”, &arr[i][j]);
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 144 Array Chapter 8

printf(“Elements of the array are:\n”);


for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
printf(“%d\t“, arr[i][j]);
printf(“\n”);
}
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the number of rows in the array : 3
Enter the number of columns in the array : 3
Enter the elements of the array:
5 6 8 2 4 3 1 9 7
Elements of the array are:
5 6 8
3 4 3
1 9 7

Program 8.10 initialize two 2 dimensional array and add the


elements of both array.

/*****************************************************************************/
/* Program 8.10 : To add the elements of two two-dimensional arrays */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
int arr1[3][3] = {{1, 2, 3}, {2, 4, 5}, {4, 5, 3}};
int arr2[3][3] = {{3, 5, 2}, {2, 5, 6}, {1, 2, 3}};
int arr3[3][3];
int i, j;
clrscr( );
printf(“Elements of the first array are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf(“%d\t“, arr1[i][j]);
printf(“\n”);
}
printf(“Elements of the second array are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf(“%d\t”, arr2[i][j]);
printf(“\n”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 145

}
printf(“Elements of the resultant array are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
arr3[i][j] = arr1[i][j] + arr2[i][j];
printf(“%d\t”, arr3[i][j]);
}
printf(“\n”);
}
getch();
}
/*****************************************************************************/

 OUTPUT :
Elements of the first array are:
1 2 3
2 4 5
4 5 3
Elements of the second array are:
3 5 2
2 5 6
1 2 3
Elements of the resultant array are:
4 7 5
4 9 11
5 7 6

Program 8.11 multiply two matrix and store the result in third
matrix.

/*****************************************************************************/
/* Program 8.11 : To print the product of two Matrix */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
int matrix1[2][3] = {{4, 2, 5}, {3, 5, 7}};
int matrix2[3][2] = {{7, 4}, {6, 2}, {4, 8}};
int matrix3[2][2];
int i, j, k;
clrscr( );
printf(“Elements of the first Matrix are:\n”);
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
printf(“%d\t”, matrix1[i][j] );
printf(“\n”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 146 Array Chapter 8

}
printf(“Elements of the second Matrix are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
printf(“%d\t“, matrix2[i][j]);
printf(“\n”);
}
printf(“Elements of the resultant matrix are:\n”);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
matrix3[i][j] = 0;
for(k=0; k<3; k++)
matrix3[i][j] = matrix3[i][j] + (matrix1[i][k]*matrix2[k][j]);
}
}
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
printf(“%d\t“,matrix3[i][j]);
printf(“\n”);
}
getch();
}

/*****************************************************************************/

 OUTPUT :
Elements of the first matrix are:
4 2 5
3 5 7
Elements of the second matrix are:
7 4
6 2
4 8
Elements of the resultant matrix are:
60 60
79 78

8.10 MULTIDIMENSIONAL ARRAY


ʇ NOTE
A multidimensional array in simple terms is an array of arrays. Like A three-dimensional array
we have one index in a one-dimensional array, two indices in a two- consists of pages. Each page
in turn contains m rows and n
dimensional array, in the same way we have n indices in a, n-dimensional columns.
array or multi dimensional array. Conversely, an n-dimensional array
is specified using n indices. An n-dimensional m1×m2×m3×...mn array is
a collection m1*m2*m3*...*mn elements. In a multidimensional array, a

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 147

particular element is specified by using n subscripts as A[I1][I2][I3]...


[In], where,
I1 <= m1 I2< = M2 I3 <= m3 ... In <= mn

A multidimensional array can contain as many indices as needed


and the requirement of the memory increases with the number of indices
used. However, hardly more than three indices are used in any program.
Figure 8.7 shows a three-dimensional array. the array has three pages,
four rows, and two columns.

Figure 8.7 : Multidimensional Array

A multidimensional array is declared and initialized similar to


one- and two-dimensional arrays.

/*****************************************************************************/
/* Program 8.12 : To read and display a 2 × 2 × 2 array. */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
main()
{
int array1[2][2][2], i, j, k;
clrscr();
printf(“\nEnter the 8 elements of the matrix:\n ”);
for(i = 0; i < 2; i++)
{
for(j = 0; j <2; j++)
{
for(k = 0; k < 2;k++)
scanf(“%d”, &array1[i][j][k]);
}
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 148 Array Chapter 8

printf(“\nThe matrix is: “);


for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
for(k = 0; k < 2;k++)
printf(“\narray1[%d][%d][%d] = %d“, i, j, k, array1[i][j][k]);
}
}
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the elements of the matrix :\n
1 2 3 4 5 6 7 8

The matrix is:

array1[0][0][0] = 1
array1[0][0][1] = 2
array1[0][1][0] = 3
array1[0][1][1] = 4
array1[1][0][0] = 5
array1[1][0][1] = 6
array1[1][1][0] = 7
array1[1][1][1] = 8

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 149

REVIEW QUESTIONS arr[1]=12;


printf(“%d”, arr[1]);
getch();
8.1 What is an array? How are arrays declared and }
initialized?
8.4 What is the output of the program?
8.2 Why are arrays needed?
#include<stdio.h>
8.3 What does an array name signify? #include<conio.h>
8.4 How is an array represented in memory? main()
{
8.5 What happens when an array is initialized with: (a) int dim[2][]={4, 6, 9, 8};
fewer initializers as compared to its size? (b) more int i;
initializers as compared to its size? clrscr();
printf(“Elements in the 2-D array are:\n”);
8.6 Explain why arrays are used in programming and for(i=0; i<2; i++)
give the syntax of accessing the elements of array printf(“Elements in the row %d are: %d and
%d\n”, i, dim[i][0], dim[i][1]);
in C.
getch();
8.7 What do you understand by two-dimensional arrays? }
State some situations that can easily represented by
these. 8.5 The output of the following code is not as desired.
Identify the error:
8.8 If an array is initialized at the time of declaration,
#include<studio.h>
what thing one must keep in mind?
#include<conio.h>
8.9 How is a two-dimensional array represented in main()
memory? {
int x[5]={4, 6, 9, 8},
8.10 What are multi-dimensional arrays? int i,
clrscr();
for(i=0; i<20; i++)
printf(“\n%d” x[i];
PROGRAMMING OUTPUT QUIZ }
getch();

8.6 What would be the output of the program. ?


8.1 What is the output of the following program? Will
#include<stdio.h>
compiler show any error? main()
#include<stdio.h> {
main() int arr[6]={18, 19};
{ printf(“\n%d%d%d”, a[2], a[3], a[4]);
int arr[10]; }
printf(“%d, %d”, a[0], a[12]);
} 8.7 What is the output of the following program?
#include<stdio.h>
8.2 What is the output of the program? main()
#include<stdio.h> {
#include<conio.h> int arr[10];
void main() printf(“%d”, *arr+6-*arr+3);
{ }
int a[0];
clrscr(); 8.8 What is the output of the program?
a[0]=10;
#include<stdio.h>
printf(“%d”, *a);
#include<conio.h>
getch();
void main()
}
{
int a[4]={4, 5, 6, 7};
8.3 What is the output of the program ? clrscr();
#include<stdio.h> printf(“%d%d\n”, 3[a], a[3]);
#include<conio.h> printf(“%d”, *a) ;
main() getch();
{ }
int x=5;
int arr[x]; 8.9 What is the output of the program?

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 150 Array Chapter 8

#include<stdio.h> main()
#include<conio.h> {
void main() static int arr[3][3]={1,2,3,4,5,6,7,8,9};
{ /* Assume that array begins at address 4004 */
int a[2][2]={{2}, {3}}; printf(“%d%d%d”, arr, arr[2], arr[2][2]);
clrscr(); }
printf(“%d”, a[0][0]);
printf(“%d”, a[0][1]); 8.15 What would be the output of the following code?
printf(“%d”, a[l][0]);
#include<stdio.h>
printf(“%d”, a[1][1]);
main()
getch();
{
}
static int arr[3][3]={1, 2, 3, 4, 5, 6, 7, 8, 9};
int *ptr;
8.10 What is the output of the program? ptr=(int *)arr;
#include<stdio.h> printf(“%d”, arr[2]); /* arr[2]=4016 */
#include<conio.h> printf(“%d”, ptr[2]);
void main() printf(“%d”, *(ptr + 2));
{ }
int a[]={15, 16, 17, 18};
clrscr(); 8.16 What would be the output of the following code ?
printf(“%d”, a[2.9999]);
#include <stdio.h>
getch();
void main()
}
{
int arr[2][3][4]={{{1, 2, 3, 4}, {5, 6, 7, 8},
8.11 What would be the output of the following code ? {8, 7, 6, 5}},{{4, 3, 2, 1}, {5, 6, 7, 8},{1, 2, 3,
#include<stdio.h> 4}}};
main() printf(“%d%d\n”, arr[1][2][3], *(*(*(arr+1)+2)));
{ }
static float arr[]={13.24,1.5,1.5,5.4,3.5};
float *var1, *var2; 8.17 What would be the output of the following code ?
var1=arr;
#include<stdio.h>
var2=arr + 4;
#include<conio.h>
var1=var1 * 2;
void main()
var2=var2 / 2;
{
printf(“%f %f”, *var1, *var2);
int arr[4]={‘0’, ‘1’, ‘2’, ‘3’}, i;
}
clrscr();
for(i=0;i<4;i++)
8.12 What would be the output of the following code ? arr[i]=arr[3-i];
#include<stdio.h> for(i=0;i<4;i++)
main() printf(“%d\n”, arr[i]);
{ getch();
static int arr[]={10, ll, 12, 13, 14}; }
int i, *var;
var = &arr[4] - 4; 8.18 What would be the output of the following code ?
for(i=0; i <= 4; i++)
#include<stdio.h>
{
#include<conio.h>
printf(“%d”, *var);
main()
var++;
{
}
int n=3, i, j, k, x;
}
int a[7]={12, 13};
clrscr();
8.13 What would be the output of the following code ? for(i=0;i<n-l;i++)
#include<stdio.h> {
main() k=i;
{ x=a[k];
int arr[]={0, 1, 2, 3, 4}; for(j=i+l;j<n;j++)
int *ptr, i; {
for(ptr=arr+4; ptr >= arr; ptr--); if(a[j]<k)
printf(“%d”, arr[ptr - arr]); {
} k=j;
x=a[k];
8.14 What would be the output of the following code ? a[k]=a[i];
a[i]=x;
#include<stdio.h>
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 8 Array Page 151

} #include<stdio.h>
} #include<conio.h>
for(i=0;i<n-1;i++) main()
printf(“%d”, a[i]); {
getch(); int arr[]={0, 1, 2, 3, 4, 5};
} int i, *ptr;
clrscr();
8.19 What would be the output of the following code ? for(ptr=arr+5;*ptr;--ptr)
printf(“%d\n”, *ptr) ;
#include<stdio.h>
}
#include<conio.h>
main()
{

LAB PROGRAMS
int arr[]={1, 2, 3 , 4, 5, 6, 7};
char crr[]={‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
clrscr();
printf(“&arr[4]=%u\t &arr[0]=%u\n”, &arr[4],&arr
[0]); 8.1. Write a program to find largest and smallest of
printf(“&crr[4]=%u\t &crr[0]=%u\n”, &crr array of n elements.
[4],&crr[0]);
printf(“&arr[4]-&arr[0]=%d\n”, arr[&arr[4]- 8.2. Write a program to calculate sum and average of
&arr[0]]); n numbers
printf(“&crr[4]-&crr[0]=%c\n”, crr[&crr[4]-
&crr[0]]);
8.3. Write a program to generate Pascal triangle using
printf(“%d\t%d”,(&arr[4]-&arr[0]),(&crr[4]- array.
&crr[0]));
8.4. Write a program to find even numbers among array
}
of n numbers.
8.20 What would be the output of the following code? 8.5. Write a program to find sum of even and odd
#include<stdio.h> numbers among n integers using array.
#include<conio.h>
main()
8.6. Write a program to reverse an array.
{ 8.7. Write a program to calculate mean,variance and
int i, j;
standard deviation.
int arr[3][3]={1,2,3,4,5,6,7,8,9};
clrscr(); 8.8. Write a program to evaluate the given polynomial
for(i=2;i>=0;i--) using Horner’s method
for(j=2;j>=0;j--)
printf(“arr[%d][%d]=%d\n”, i, j, arr[i][j]); 8.9. Write a program to generate prime number from 1
for(i=2; i>=0; i--) to SIZE (say 200)by sieve of Eratosthenes method.
for(j=2;j>=0;j--)
printf(“%d\n”, *(*(arr+j)+i)); 8.10. Write a program to insert in an array at a specific
} position.

8.21 What would be the output of the following code? 8.11. Write a program to delete from an array from a
specific position.
#include<stdio.h>
#include<conio.h> 8.12. Write a program to find the transpose of a matrix.
main()
{
8.13. Write a program to trace of a square matrix.
int arr[2]; 8.14. Write a program to find norm of a matrix. Norm is
clrscr();
square root of the sum of squares of all elements.
*arr[0]=1;
*arr[1]=2; 8.15. Write a program to find sum of all elements of a
printf(“%d\n”, &arr[1]-arr); matrix.
}
8.16. Write a program to check a number for palindrome
8.22 What is the output of the following code? 8.17. Write a program to generate a magic square of odd
#include<stdio.h> order.
void main (void)
{ 8.18. Write a program to print the square of all elements
int a[9] = {“12345678”}; of a square matrix.
printf(“%d”, ((a+6) + (a+1)));
} 8.19. Write a program to check a square matrix for
symmetry.
8.23 What is the output of the following code ?

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 152 Array Chapter 8

8.20. Write a program for concatenation of two arrays. array is in descending order.
8.21. Write a program which reverse an array of n 8.35. Write a program for merging of two sorted arrays
elements without using temporary variable. given in ascending order merged array is also in
8.22. Write a program for insertion in a sorted array and ascending order.
the array remains sorted after insertion. 8.36. Write a program to remove the duplicate elements
8.23. Write a program to print the matrix along with row from an array.
and column sum. 8.37. Write a program to delete all occurrences of an
8.24. Write a program for row wise sorting of a matrix integer number. Shift all the non deleted members
(selection sort). to left and fill the unused space by 0 (zero).

8.25. Write a program to check whether given odd order 8.38. Write a program for deletion from a sorted array
matrix is a magic square or not. given in ascending order. After deletion of only first
occurrence of the element the array remains sorted
8.26. Write a program to multiply two matrices.
8.39. Write a program for deletion of a specific element
8.27. Write a program for subtraction of two matrices. from an unsorted array. Only first occurrence is
8.28. Write a program for addition of two matrices. deleted.
8.29. Write a program to display the upper and lower 8.40. Write a program to find the maximal subsequence
triangles of a square matrix. out of a given sequence
8.30. Write a program to find the sum of non diagonal 8.41. Write a program which accept and count votes of
elements of a square matrix. candidates print the number of discarded votes (if
any).
8.31. Write a program to calculate the sum of elements
of either diagonals of a square matrix 8.42. Write a program find average male and average
female height.
8.32. Write a program to find transpose of a square
matrix where transpose is stored in the original 8.43. Write a program which read n integers from the
matrix. keyboard and store them in the array ar and then
copy the odd numbers from array ar to array oar ,
8.33. Write a program to mix elements of two integer
even numbers to array ear also display arrays oar
arrays A and B of sizes M and N. All even numbers
and ear.
of A from left to right are copied into C from left to
right. All odd numbers of A from left to right are 8.44. Write a program to find minimum, maximum and
copied into C from right to left. All even numbers sum of array elements
of B from left to right are copied into C from left 8.45. Write a program to check a square matrix for
to right. All odd numbers of B from left to right orthogonality.
are copi~d into c from right to left. For example :
A is {3, 2, 1, 7, 6, 3} and B is {9, 3, 5, 6, 2, 8, 10}. 8.46. Write a program to find the inverse of a square
The resultant array C is {2, 6, 6, 2, 8, 10, 5, 3, 9, matrix. Check for the singularity of the given
3, 7, 1, 3} matrix and append a unit matrix of same order.
Swap current row with the row having maximum
8.34. Write a program for merging of two sorted arrays, element, in the column corresponding to the
given arrays are in ascending order and merged diagonal element.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

9
STRINGS

9.1 INTRODUCTION

As you are already familiar that an array is a collection of elements


of similar data-type that are stored in contiguous memory locations.
When the elements of an array are integers or floating-points, the arrays
are called numerical arrays. However, when the elements of an array are
characters, the arrays are called strings. In simple terms, a string is an
array of characters in C language. Consider a scenario, where you need
to store a word, WELCOME. For this, one option is to declare seven
variables of char type and initialize the variables with the characters:
W, E, L, C, O, M, and E individually. Another option is to declare
and initialize a char array variable or a string variable, which stores
the data, WELCOME, collectively. Therefore, you need to declare and
use a char array or string when you need to store a complete word, for
instance, WELCOME. In addition, C also allows you to create an array
of strings, which means two-dimensional char array, to store a complete
sentence, for instance, WELCOME TO C.
The C language also provides various string functions, such as
strcmp(), and strlen(), to handle string operations. These operations
include comparing two strings, converting the characters of a string into
upper case, and calculating the length of a string. The string functions
are stored in a string library, called the string.h header file.

9.2 UNDERSTANDING STRINGS IN C

In C language, a string is one-dimensional character array where each


element is either a character constant or a string constant. For example,
you create an array of characters that stores the vowels of English
language. Then, the vowels characters (a, e, i, o and u) are either
character constants or string constants.
Now, let’s explain how a string is stored in the main memory of
a computer. Consider an example of storing the word, Rajasthan. The
Rajasthan word contains eight characters. Figure 9.1 shows the storing
of the Rajasthan word, as a string in C language:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 154 Strings Chapter 9

Figure 9.1 : Word Rajasthan stored in an array

As similar to a numerical array, the first element of a string is


stored at 0th subscript position; the second element is stored at 1st
subscript position, and so on. In addition, the last character of the
string is stored at n-1 subscript position, where n is the total number
of characters. How, there is a difference between a numerical array and
a character array or string. The difference is that a character array or
a string stores a null (\0) character at the nth subscript position, while
a numerical array does not store such a character. This means that, a
character array or string stores n+1 element, because the last character
of the array is always null.

9.3 DECLARING AND INITIALIZING A STRING

As similar to a numerical array, a character array or a string is declared


as follows:
char variable_name[array_length];
In this syntax, variable_name stands for a user-defined string
name, and array_length stands for the size of the array or string.
A character array or a string variable is initialized by either
assigning a character constant individually or assigning all the characters
collectively. When you initialize a string variable by assigning character
constants individually, you use single quotes ‘ ‘. The following example
shows the declaration and initialization of a string variable by using the
single quotes:
char month[8]={‘J’, ‘A’, ‘N’, ‘U’, ‘A’, ‘R’, ‘Y’, ‘\0’}
In this statement, an array of characters or a string variable,
month, is declared and initialized. The size of this string variable is 8.
All the character constants are assigned individually. Note the null (\0)
character is also assigned manually for the 7th subscript position of the
array.
Now, when you initialize a string variable by assigning all the
characters collectively, you use double quotes “ ”. The following example
shows the declaration and initialization of a string variable by using the
double quotes:
char month[8]={“JANUARY”};
In this example, an array of characters or a string variable, month,
is declared and initialized. The size of this string variable is 8. All the
character constants are assigned to the individual elements of the array
automatically. In addition, the above declaration automatically adds
the null (\0) character at the end of the string.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 155

9.4 READING AND DISPLAYING THE STRINGS

In a program, data input and output are two important processes


that are used to accept input details and display the information after
processing these details, respectively. A string data can be read or
display by using the input and output functions, such as getchar(),
puts(), printf(), and scanf(). these input and output functions
are defined in the stdio.h header file to perform I/o operations. You
can display a string on a computer by using the printf(), puts(), or
putchar() functions. However, a string can be read by using either a
keyboard or a data file. You can provide a user-defined string by using
the scanf(), gets(), or getchar() functions.

9.4.1 Using the scanf() and printf() Functions


As you are already familiar with the scanf() and printf() functions,
these functions are used to perform console-based input and output (I/o)
operations in a program. The scanf() function reads characters from
the keyboard and stores them in variables according to the specified
formats, which are known as format specifiers. When you need to read
a string, you can use the %s format specifier. The following example
shows the use of the scanf() function:
scanf(“%s”, &month_name);
scanf(“%s”, &employee_name);

In this the scanf() functions read the strings for month_name and
employee_name string variables or char array variables.
The printf() function along with the %s format specifier prints a
string stored in character array to the console. You can use the printf()
function to display the string data with the help of two ways. Either
you can pass the string data directly within the printf() function or
you can store the string data in a character array, for instance str, and
then pass the str array as a parameter in the printf() function.
The following examples show the both ways of using the printf()
function to display a string data:
printf(“Test string”); /* Example 1*/
or
char str[]={“Test string”}; /* Example 2*/
printf(“%s”,&str);

In the first example, the printf() function takes string as


a parameter and prints the specified string in the console. On the
other hand, in the second example, the printf() function takes two
parameters. The first parameter is the string format specifier, (%s),
which tells the compiler to print the string data on the console and the
second parameter is the address of the character array, str, where the

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 156 Strings Chapter 9

string data is stored in the memory. Program 9.1 shows the use of the
printf() function:

/*****************************************************************************/
/* Program 9.1 : Using the printf() function to print string */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
char str[100]={“Using printf() function for displaying the string”};
clrscr();
printf(“%s”,str);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
This program is using printf() function for displaying the string

 EXPLANATION :
In this program, a character array or string variable, str, is declared of the 100 size.
This str variable is initialized with a string message that is displayed to the console
by using the printf() function and the %s format specifier.

The printf() function can be used as many number of times as


you want for displaying different strings. Program 9.2 shows another
example of the printf() function to show two different names of the
days of a week:

/*****************************************************************************/
/* Program 9.2 : Displaying Specific Days of a Week by Using the printf() */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
char s1[] = “Sunday”;
char s2[] = “Wednesday”;
clrscr();
printf(“%s\n”, s1, s1);
printf(“%s\n”, s2, s2);
getch();
return 0;
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 157

 OUTPUT :
Sunday
Wednesday

 EXPLANATION :
In program 9.2, two strings, s1 and s2, are initialized with the string data, sunday
and wednesday, respectively. Then, the printf() function is used two times along with
the %s format specifier to display the string data.

An important feature of a string is that you can access the


American Standard Code for Information Interchange (ASCII) value
of an individual character in the string. For this purpose, you need to
use the %d format specifier with the printf() function. Program 9.3
shows an example of accessing the ASCII value of a character constant
in a string:

/*****************************************************************************/
/* Program 9.3 : Showing the ASCII Value of a Character Constant */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char nm[5]=“kabir”;
clrscr();
printf(“ASCII Value: %d\n”,nm[2]);
printf(“Character in upper case: %c\n”,nm[2]-32);
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
ASCII Value: 98
Character in upper case: B

Now, let’s use the scanf() function along with the printf()
function for reading and displaying a string data. Program 9.4 shows
the use of the scanf() and printf() functions:

/*****************************************************************************/
/* Program 9.4 : Using the scanf() and printf() Functions */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char name[20];
clrscr();
printf(“What is your name?\n”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 158 Strings Chapter 9

scanf(“%s”,&name);
printf(“Welcome, %s!!!\n”,name);
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
What is your name?
Mahesh
Welcome, Mahesh!!!

 EXPLANATION :
In this program, a string variable or a character array, name, is declared of the 20
size. The printf() function is used to display a string message. What is your name?
The name, which is entered by you, will be stored in the name variable. For instance,
in out case, the name is Mahesh. Then, the second occurrence of the printf() function
along with the %s format specifier is used to display the stored name in the name
variable.

9.4.2 Using the puts() and gets() Functions


The gets() function reads a string from keyboard. This function stops
reading the string only when you press the ENTER key from they
keyboard. The gets() function is similar to the scanf() function. The
difference between the gets() and scanf() functions is that the gets()
function can read the whole sentence, which is a combination of multiple
words: while the scanf() function can read the characters until a space
or a newline character is encountered in a sentence. Program 9.5 shows
that the scanf() function cannot store the string data of multiple
words in a variable.

/*****************************************************************************/
/* Program 9.5 : Displaying the Limitation of the scanf() */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char msg[70];
clrscr();
printf(“Enter a message : ”);
scanf(“%s”,msg);
printf(“%s”,msg);
getch();
return 0;
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 159

 OUTPUT :
Enter a message : welcome to Jhunjhunuwala
welcome

 EXPLANATION :
Program 9.5 shows that the scanf() function does not read multiple words into an
array. This is because when you enter a space after the word welcome, the scanf()
function considers it as the end of string and do not consider any character typed
after it.

The gets() function in place of the scanf() function is used to


overcome this problem of reading multiple words into an array. We
rewrite the above program using gets() function as below :

/*****************************************************************************/
/* Program 9.6 : Displaying the Limitation of the scanf() */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char msg[70];
clrscr();
printf(“Enter a message : ”);
gets(msg);
printf(“You Entered : %s”,msg);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter a message : welcome to Jhunjhunuwala
You Entered : welcome to Jhunjhunuwala

The puts() function, on the other hand, prints a string or a value


stored in a variable to the console and appends a newline character
(‘\n’) to it. Program 9.7 shows the use of the gets() and puts()
functions:

/*****************************************************************************/
/* Program 9.7 : Using the gets() and puts() Functions */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char msg[70];
clrscr();

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 160 Strings Chapter 9

printf(“Enter a message : ”);


gets(msg);
printf(“You Entered : ”)
puts(msg);
printf(“Press any Key”)
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter a message : welcome to Jhunjhunuwala
You Entered : welcome to Jhunjhunuwala
Press any Key.

9.5 CREATING AN ARRAY OF STRINGS

As you get familiar with the process of creating a single string that
is also called as one dimensional character array. Now, you can also
create an array of string that is known as two-dimensional character
arrays. Two-dimensional character array is an array of one-dimensional
character array, which consists of strings as its individual elements. The
following code snippet an example of two-dimensional character array:
char days[7][10]=
{“Sunday”,“Monday”,“Tuesday”,“Wednesday”,“Thursday”,Friday”,“Saturday”};

Table 9.1 shows the storage of an array of string, days, in the


main memory of a computer:

TABLE 9.1 : Storage of an array of String


days[][0] days[][1] days[][2] days[][3] days[][4] days[][5] days[][6] days[][7] days[][8] days[][9]
days[0] S u n d a y \0
days[1] M o n d a y \0
days[2] T u e s d a y \0
days[3] W e d n e s d a y \0
days[4] T h u r s d a y \0
days[5] F r i d a y \0
days[6] S a t u r d a y \0

In table 9.1, you can see that days[ ] is a two-dimensional array


of character, or an array of strings. It stores seven strings, where the
maximum length of each string element is 10.
You can access any string element by specifying the subscript
position of the array. For instance, the days[2] element displays the
string, Tuesday; while the days[5] element displays the string, Friday,
on a console. In addition, you can also access the individual characters

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 161

of a string element. for instance, the days[3][4] element displays the


character, e; and the days[4][1] element displays the character, h, on
your console. Program 9.8 shows on example of an array of string:

/*****************************************************************************/
/* Program 9.8 : Creating and Displaying an Array of String */
/*****************************************************************************/

#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
int i;
char montharr[12][10]={“January”,“February”,“March”,“April”,“May”,“June”,
“July”,“August”,“September”,“October”,“November”,“December”};
clrscr();
for(i=0;i<12;i++)
printf(“%s\n”,montharr[i]);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
January
February
March
April May
June
July
August
September
October
November
December

 EXPLANATION :
In this program, an array of string or a two-dimensional array of character, montharr,
is declared and initialized. Then, the string elements stored in the string array are
displayed by using the printf() function.

9.6 PERFORMING STRING OPERATIONS

Using C language syntaxes, you can perform various operations on


strings. For example, you can compare two strings, combine two or
more strings, and calculate the length of a string.
In the following sections, we perform the following tasks:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 162 Strings Chapter 9

(1) Concatenating strings


(2) Calculating the length of a string
(3) Comparing strings

9.6.1 Concatenating Strings


String concatenation means one string is appended at the end of
another string. Take an example of two strings, str1 and str2. The
str1 stores the data, Welcome; while the str2 sting stores the data, to
C programming. Now, if the two strings are concatenated, the resultant
string will be, Welcome to C programming. Program 9.9 shows an
example of string concatenation:

/*****************************************************************************/
/* Program 9.9 : Concatenating Two Strings */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[50], s2[50];
int i, j, k;
puts(“Enter First String :”);
gets(s1);
puts(“Enter Second String :”);
gets(s2);
for (i=0;s1[i]!=‘\0’;i++)
{
;
}
k=i;
for(i=k, j=0;s2[j]!=’\0’;i++,j++)
{
s1[i]=s2[j];
}
s1[i]=’\0’;
puts(“After concatenating the first string is :”);
puts(s1);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter First String :
Welcome to Jaipur
Enter First String :
Welcome to Rajasthan
After concatenating the first string is :

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 163

Welcome to JaipurWelcome to Rajasthan

 EXPLANATION :
In program 9.9, two strings, s1 and s2, are declared. We read the string using gets
function. Then, the s1 string is traversed to its end. Next, the second string, s2, is
attached at the end of the s1 string. The last character of the resultant string is set
to null character (\0).

9.6.2 Calculating the Length of a String


String length is a process of finding the total number of elements present
in a string. Program 9.10 shows an example of defining and using a
function that returns the total number of characters stored in a string:

/*****************************************************************************/
/* Program 9.10 : Calculating the Length of a String */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
char str[200];
int num, strlength = 0;
clrscr();
printf(“Enter String : ”);
gets(str);
for(num=0; str[num]!=’\0’;num++)
strlength=strlength+1;
printf(“Length of the string is : %d”,strlength);
getch();
}
/*****************************************************************************/

 OUTPUT :
Enter String : welcome to jaipur
Length of the string is : 17

 EXPLANATION :
In program 9.10, a string is read using gets() function. A counter is declared and
initialized with the value zero, so that whenever the characters are read, the value of
this counter is also increased. The provided string is traversed character by character.
and the value of the counter is increased, whenever a new character is encountered.
The process continues until, all the characters present in the provided string are
traversed completely.

9.6.3 Comparing Strings


String comparison means that two strings are compared to check

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 164 Strings Chapter 9

whether the strings are equal or not. Program 9.11 shows an example
of comparing two strings:

/*****************************************************************************/
/* Program 9.11 : Comparing Two Strings */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100], s2[100];
int num, strlength1=0, strlength2=0, n=0, strflag;
clrscr();
puts(“Enter First String : ”);
gets(s1);
puts(“Enter Second String : ”);
gets(s2);
for(num=0; s1[num]!=‘\0’;num++)
strlength1=strlength1+1;
for(num=0; s2[num]!=‘\0’;num++)
strlength2 = strlength2+1;
if(strlength1==strlength2)
{
while (n<strlength1 && n<strlength2)
{
if(s1[n]<s2[n])
{
strflag=-1;
break;
}
if(s1[n]>s2[n])
{
strflag=1;
break;
}
if(s1[n]==s2[n])
{
strflag=0;
n++;
}
}
printf(“String Comparasion Result : %d”, strflag);
}
else
printf(“String length is not equal.”);
getch();
}

/*****************************************************************************/

 OUTPUT :

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 165

Run1
Enter First String :
rajasthan
Enter Second String :
jaipur
String length is not equal.
Run2:
Enter First String :
rajasthan
Enter Second String :
karnataka
String Comparasion Result : 1

 EXPLANATION :
In program 9.11, two strings, s1 and s2, are compared character by character. A
counter is declared and initialized with zero. When the first character of both strings is
matched. The value of the counter is incremented, and then the subsequent characters
of the strings are compared. This process continues, untill a character is mismatched
in both strings, or until the string is reached. The strflag variable can return any one
of the following values:
(1) 0 (zero): Specifies that both string are equal.
(2) 1: Specifies that the s1 string is greater than the s2 string.
(3) -1: Specifies that the s1 string is less than the s2 string.

9.7 USING STRING HANDLING FUNCTIONS

The C language provides a string library that contains various predefined


string handling functions, such as strcat and strlen. These string
handling functions are stored in the string.h header file. Therefore,
you must include the string.h header file in your program, when you
need to use a string handling function. Some common and useful string
handling functions are given as follows:
(1) strlen()
(2) strcmp()
(3) strncmp()
(4) strcat()
(5) strncat()
(6) strcpy()
(7) strncpy()
(8) strchr()
(9) strlwr()
(10) strupr()
(11) strrev()

9.7.1 strlen()

The strlen() function is used to find out the length of a string. The
syntax to use the strlen() function is as follows:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 166 Strings Chapter 9

strlen(string_data);
In this syntax, you see that the strlen() function takes a string
parameter to count the number of characters in the string. Program
9.12 shows an example of using the strlen() function:

/*****************************************************************************/
/* Program 9.12 : Displaying the Length of a String */
/*****************************************************************************/

#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char s1[100];
clrscr();
puts(“Enter any String : ”);
gets(s1);
printf(“String Length: %d”,strlen(s1));
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run1
Enter any String :
It is very nice
String Length: 15

Run 2
Enter any String :
Jhunjhunuwala is best publication.
String Length: 34

 EXPLANATION :
In program 8.12, the strlen() function takes a string argument, The length of this
string is. The len variable stores the number of characters, which is returned by the
strlen() function. Then, the printf() function is used to display the value stored in
the len variable.

9.7.2 strcmp()
The strcmp() function is used to compare two string data. The syntax
to use the strcmp() function is as follows:
strcmp(string_data1,string_data2);
In the above syntax, you see that the strcmp() function takes
two parameters of strings for comparing. It returns an integer value

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 167

indicating the relationship between the strings. The returned value can
be zero, greater than zero, or less than zero. A zero value indicates that
the both strings are equal. A value, which is greater than zero, indicates
that the first character that does not match has a greater value in
string1 than in string2. Finally, a value less than zero indicates that
the first character that does not match has lesser value in string1 than
in string2. Program 9.13 shows an example of comparing two strings
by using the strcmp() function:

/*****************************************************************************/
/* Program 9.13 : Using the strcmp() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[80];
clrscr();
printf(“Enter password: “);
gets(s);
if(strcmp(s, “pass”))
printf(“Invalid Password\n”);
else
printf(“Valid Password\n”);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run 1
Enter password: pass
Valid Password

Run 2
Enter password: computer
Invalid Password

 EXPLANATION :
In program 9.13, a prompt appears to enter a password. If you enter a correct password,
the Valid Password message appears; and if you enter incorrect password, the Invalid
Password message appears. The process of checking the password is performed by
using the strcmp() function.

9.7.3 strncmp()
The strncmp() function is used to compare two strings up to a specified
number of characters. The syntax to use the strncmp() function is as

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 168 Strings Chapter 9

follows:
strncmp(string_data1,string_data2,n);
In the above syntax, you can see that the strncmp() function
compares two string up to the nth character, where n is the number of
characters. This function takes three parameters, where two parameters
are the strings, which have to be compared; and the third parameter
is the number of characters up to which the two strings are compared.
Program 9.14 shown an example of using the strncmp() function for
comparing two strings up to given number of characters:

/*****************************************************************************/
/* Program 9.14 : Using the strncmp() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char s1[50], s2[50];
int n;
clrscr();
puts(“Enter First String :”);
gets(s1);
puts(“Enter Second String :”);
gets(s2);
printf(“Enter the value of n: ”);
scanf(“%d”, &n)
if(!strncmp(s1, s2, n))
printf(“Strings are same.\n”);
else
printf(“Strings are not same.\n”);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run 1
Enter First String :
rajkumar sharma
Enter Second String :
rajkumar verma
Enter the value of n: 7
Strings are same.

Run 2
Enter First String :
rajkumar sharma
Enter Second String :

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 169

rajkumar verma
Enter the value of n: 11
Strings are not same.

 EXPLANATION :
In program 9.14, user input two string and enter the value to which comparasion is
to be make. In first run user enter the vlaue of n as 7. As you can see that first nine
characters of both strings are same from the beginning. Therefore, the message. The
strings are same, is displayed on the console.
In second run user enter the vlaue of n as 11. So the string are not same, is
displayed on the console.

9.7.4 strcat()
The strcat() function is used to concatenate two strings. The syntax
to use the strcat() function is as follows:
strcat(string_data1,string_data2);
In the above syntax, you can see that the strcat() function takes
two arguments to add second string to first string. This means that
second string is appended to first string and the concatenated string is
stored in the first string. Program 9.15 shows an example of using the
strcat() function for adding two strings:

/*****************************************************************************/
/* Program 9.15 : Using the strcat() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str1[50], str2[50];
clrscr();
printf(“Enter str1: ”);
gets(str1);
printf(“Enter str2: ”);
gets(str2);
strcat(str1, str2);
printf(“\nstr1: %s”, str1);
printf(“\nstr2: %s”,str2);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter str1: What is your name :
Enter str2: Raju

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 170 Strings Chapter 9

str1: What is your name :Raju


str2: Raju

 EXPLANATION :
In this program two strings, str1 and str2, are entered by user. Then the str2 string
is appended at the end of the str1 string.

9.7.5 strncat()

The strncat() function is used to add two strings, where a specified


number of characters of one string are appended at the end of another
string. The syntax to use the strncat() function is as follows:
strncat(string_data1,string_data2,n);
In the above syntax, you can see that the strncat() function
is used to add first n characters of a string at the end of another
string. This function takes three parameters, where two parameters are
the strings, which have to be concatenated; and the third parameter
is number of characters up to which the two strings are combined.
Program 9.16 shows an example of using the strncat() function:

/*****************************************************************************/
/* Program 9.16 : Using the strncat() Function */
/*****************************************************************************/

#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char s1[50], s2[50];
unsigned int len;
clrscr();
printf(“Enter First name : ”);
gets(s1);
printf(“Enter Last name : ”);
gets(s2);
len = 50-strlen(s2);
strncat(s1, s2, len);
printf(“\nFull Name : %s”, s1);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter First name : What is your name ?

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 171

Enter Last name : Mahesh

Full Name : What is your name ?Mahesh

 EXPLANATION :
In program 9.16, two strings, s1 and s2, are provided at the runtime. A variable,
len, is used to store the number of characters, which is obtained by subtracting the
string length of s2 string from the number, 19. The strncat() function takes three
arguments, s1, s2, and len. It adds the characters from the s1 string to the end of the
s2 string, up to the number of characters stored in the len variable.

9.7.6 strcpy()

The strcpy() function is used to copy the content of first string to


second string. You have to pass two strings as an argument of the
strcpy() function to copy first string to second string. The syntax to
use the strcpy() function is as follows:
strcpy(string_data1,string_data2);
In the above syntax, the strcpy() function copies the content of
string_data2 to string_data1.
Program 9.17 shows the use of strcpy() function to combine the
two strings:

/*****************************************************************************/
/* Program 9.17 : Using the strcpy() Function */
/*****************************************************************************/

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char first_name[100], last_name[100], full_name[200];
clrscr();
printf(“Enter First Name : ”);
gets(first_name);
printf(“Enter Last Name : ”);
gets(last_name);
strcpy(full_name, first_name);
strcat(full_name, “ ”);
strcat(full_name, last_name);
printf(“\nYou Entered First Name : %s”, first_name );
printf(“\nYou Entered Last Name : %s”, last_name );
printf(“\nFull Name : %s”, full_name);
getch();
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 172 Strings Chapter 9

 OUTPUT :
Run 1
Enter First Name : Mahesh
Enter Last Name : Singh

You Entered First Name : Mahesh


You Entered First Name : Singh
Full Name : Mahesh Singh

Run 2
Enter First Name : Mahesh Pratap
Enter Last Name : Singh

You Entered First Name : Mahesh Pratap


You Entered First Name : Singh
Full Name : Mahesh Pratap Singh

 EXPLANATION :
In program 9.17, three string variables, first_name, last_name, and full_name are
declared. The first_name and last_name string are provided at the runtime by using
the gets() function. Next, the string stored in first_name string is copied into the
full_name string by using the strcpy() function. Then blank character is append by
strcat() function at the end of first_name Finally, the strcat() function is used to
append the last_name string at the end of the full_name string.

9.7.7 strncpy()

The strncpy() function is used to copy a specified number of characters


from one string to another string. The syntax to use the strncpy()
function is as follows:
strncpy(string_data1,string_data2,n);
In the above syntax, you can see that the strncpy() function is used
to copy first n characters of one string to second string. This function
takes three parameters, where two parameters are the strings, which
have to be copied; and the third parameter is number of characters,
up to which the second string is copied to the first string. Program
9.18 shows the use of strncpy() function to copy a specified number of
characters from one string to another string:

/*****************************************************************************/
/* Program 9.18 : Using the strncpy() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str1[100], str2[100];
int n;
clrscr();

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 173

printf(“Enter first string : ”);


gets(str1);
printf(“Enter second string : ”);
gets(str2);
printf(“Enter the number of character to be copied : ”);
scanf(“%d”, &n);
strncpy(str1, str2, n);
printf(“\nStr1: %s”,str1);
printf(“\nStr2: %s”,str2);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter first string : baba baba black ship have you any wool
Enter second string : twinkle twinkle little star how are wonder what you are
Enter the number of character to be copied : 10
str1: twinkle twblack ship have you any wool
str2: twinkle twinkle little star how are wonder what you are

 EXPLANATION :
In program 9.18, two strings, str1 and str2, are provided at the runtime. The
strncat() function takes three arguments, str1, str2, and a number 10. The first 10
characters of the str1 string are copied to the str2 string. Finally, str1 and str2 are
displayed.

9.7.8 strchr()

The strchr() is used to search a specific character in a string. The


syntax to use the strchr() function is as follows:
strchr(string_data, searching_character);
The above syntax of strchr() function takes two parameters, one
is string data and another is the character that has to be searched inthe
string data.
Program 9.19 shows an example searching a character in the
provided string:

/*****************************************************************************/
/* Program 9.19 : Using the strchr() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25], ch;
clrscr();

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 174 Strings Chapter 9

printf(“Enter the String : ”);


gets(str);
printf(“Enter the character to be Searched : ”);
scanf(“%c”, &ch);
if(strchr(str, ch))
puts(“This string contain this character.”);
else
puts(“This string does not contain this character.”);
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Run 1
Enter the String : Computer Programming
Enter the character to be searched : r
This string contain this character.

Run 2
Enter the String : Computer Programming
Enter the character to be searched : z
This string does not contain this character.

 EXPLANATION :
In program 9.19, the strchr() function is used to search the given character, in the
provided string.

9.7.9 strlwr()

The strlwr() function is used to convert the characters stored in a


string into the lower case. The syntax to use the strlwr() function is
as follows:
strlwr(string_data);
In the above syntax, the strlwr() function takes a parameter
of string data, and returns the resultant string by converting all the
characters into lower case.
Program 9.20 shows an example of using the strlwr() function:

/*****************************************************************************/
/* Program 9.20 : Using the strlwr() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25];

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 175

clrscr();
printf(“Enter the String : ”);
gets(str);
printf(“\nString in lowercase: %s”, strlwr(str));
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
Enter the String : A Great LOVE
String in lowercase: a great love

 EXPLANATION :
In program 9.20, str is a string variable that is provided data runtime. The strlwr()
function is used to convert the string data stored in the str string into lower case.

9.7.10 strupr()

The strupr() function is used to convert the characters stored in a


string into the upper case. The syntax to use the strupr() function is
as follows:
strupr(string_data);
In the above syntax, the strupr() function takes a parameter
of string data, and returns the resultant string by converting all the
characters into upper case.
Program 9.21 shows an example of using the strupr() function:

/*****************************************************************************/
/* Program 9.21 : Using the strupt() Function */
/*****************************************************************************/

#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25];
clrscr();
printf(“Enter the String : ”);
gets(str);
printf(“\nString in Uppercase: %s”, strupr(str));
getch();
return 0;
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 176 Strings Chapter 9

 OUTPUT :
Enter the String : A Great LOVE
String in Uppercase: A GREAT LOVE

 EXPLANATION :
In program 9.20, str is a string variable that is provided data runtime. The strupr()
function is used to convert the string data stored in the str string into upper case.

9.7.11 strrev()

The strrev() function is used to reverse a string, which takes one


string argument. The syntax to use the streev() function is as follows:
strrev(string_data);
In the above syntax, the strlwr() function takes a parameter of
string data, and returns the resultant string by reversing the order of
all the characters.
Program 9.22 shows an example of using the strrev() function:

/*****************************************************************************/
/* Program 9.22 : Using the strrev() Function */
/*****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main ()
{
char str[25];
clrscr();
printf(“Enter the String :\n”);
gets(str);
strrev(str); /*reverse string1*/
printf(“Reverse string is :\n”);
puts(str);
getch();
return 0;
}
/*****************************************************************************/

 OUTPUT :
Enter string : This is a reverse program.
Reverse string is : .margorp esrever a si sihT

 EXPLANATION :
In program 9.22, a string variable, str, reads the value at run time using gets()
function. The strrev() function is used to reverse the string stored in the str variable.
Using puts() function reversed string is displayed.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 177

REVIEW QUESTIONS printf(“No”);


getch();
}
9.1 What are strings?
9.2 How are strings read from the standard input 9.2 What is the output of the program ?
device? Explain the different functions used to #include<stdio.h>
#include<conio.h>
perform string input operation. #include<string.h>
9.3 Explain how strings are represented in main main()
memory. {
char strl[]=”Hello”;
9.4 How a string is stored in C? char str2[10] ;
9.5 Explain, with example, how a string is declared and clrscr();
str2=strl;
initialised. printf(“%s”, str2) ;
9.6 Explain operations that can be performed on getch();
}
strings.
9.7 Explain how strings can be displayed on the screen. 9.3 What is the output of the following program?
9.8 Write a short note on string operations. #include<stdio.h>
main()
9.9 Differentiate between gets() and scanf().
{
9.10 How can putchar() be used to print a string? register num=5;
char str[]=”RTUK”;
9.11 Differentiate between a character array and a string. printf(“%s %d”, str, num);
9.12 How is an array of strings represented in the }
memory?
9.4 What is the output of the program?
9.13 What is the NULL character and what is its use, in
#include<stdio.h>
the context of strings? #include<conio.h>
9.14 List the important library functions for string #include<string.h>
manipulation with relevant example for each. void main()
{
9.15 Suggest different ways of handling strings with char arr[]=”hello\0\0\0\0\0”;
reference to I/O operations and explain. char arrl[]=”hello\n\n\n\n\n”;
clrscr();
9.16 Explain the following string handling functions: (i) printf(“%d\t%d\n”, sizeof(arr), strlen(arr));
strcat() (ii) strcpy() (iii) strcmp() (iv) strlen(). printf(“%d\t%d”, sizeof(arrl), strlen(arrl));
getch();
9.17 Differentiate between the following: (a) getch(),
}
getche() and getchar() (b) strcmp() and strcpy()
9.18 How can a list of strings be stored within a two 9.5 What is the output of the program?
dimensional array? How can individual strings be #include<stdio.h>
processed? What library functions are available to #include<conio.h>
simplify the string processing? void main()
{
char srt1[]={‘7’, ‘8’, ‘9’, ‘0’};
char srt2[]={‘9’, ‘8’, ‘7’, ‘\0’, ‘7’, ‘8’, ‘9’};
clrscr();
PROGRAMMING OUTPUT QUIZ printf(“%s”, str1);
printf(“%s”, str2) ;
getch() ;
}
9.1 Following program gives ‘No’ as the output , though
the output should be ‘Yes’. Identify the error: 9.6 What is the output of the program?
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() void main()
{ {
char strl[]=”abc”; int k=1, j=0;
char str2[]=”abc”; char *x;
if(str1 == str2) clrscr();
printf(“Yes”); scanf(“%s”, x); /* input: we */
else

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 178 Strings Chapter 9

j=strlen(x); char str2[15]={“RAJASTHAN”};


for(;j;(x[++k]=x[--j])); clrscr();
puts(x); if(strcmpi(strl, str2)==NULL)
getch(); printf(“Both strl and str2 are same without case
} sensitivity\n”);
if(stricmp(strl, str2)==NULL)
9.7 What is the output of the following code? printf(“Both strl and str2 are same without case
sensitivity\n”};
#include<stdio.h>
if(strcmp(strl, str2)!=NULL)
void main()
printf(“Both strl and str2 are different with
{
case sensitivity\n”);
char str[]=”RAVI”;
getch();
int i=0, n=strlen(str);
}
clrscr();
while(n)
{
9.12 What would be the output of the following code?
n--; #include<stdio.h>
str[i]=str[n]; #include<conio.h>
i++; void main (void)
} {
printf(“%s”, str) ; char str[‘11’]={“work hard”};
getch(); clrscr();
} printf(“%d\n”, sizeof(str));
printf(“%s”, str);
9.8 What is the output of the following code? getch();
}
#include<stdio.h>
#include<string.h>
void main()
9.13 What would be the output of the following code?
{ #include<stdio.h>
char str[]=”HELLO\r”; #include<conio.h>
printf(“%5s”, strcat(str, “HI”)); void main()
} {
char strl[]=”0123456789”;
9.9 What would be the output of the following code? char str2[]=”ABCDEFGHIJ”;
char chl, ch2;
#include<stdio.h>
int i=0;
main ()
clrscr();
{
chl=++str2[strl[i]-48];
char str1[]=”Computer”;
ch2=str2[strl [i++]-48];
char str2[]=”Computer”;
printf(“Charl is %c\n”, chl);
if (str1 == str2)
printf(“Char2 is %c\n”, ch2);
printf(“\nEqual”);
printf(“Strl=%s, Str2=%s\n”, strl, str2);
else
getch();
printf(“\nUnequal”);
}
}
9.14 What would be the output of the following code?
9.10 What would be the output of the following code ?
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
main()
typedef char int;
{
void main()
char arr[20];
{
int i;
int arr[]=“HI”, *ptr=“ABCDE”;
for (i=0; i <= 18; i++)
clrscr();
i[arr]=’v’;
printf(“%s%s”, arr, ptr);
i[arr]=’\0’;
getch();
printf(“%s”, arr);
}
}
9.15 What would be the output of the following code?
9.11 What is the output of the following code?
#include<stdio.h>
#include<conio.h>
#include <conic. h>
#include<string.h>
void main()
#include<stdio.h>
{
void main()
char arr[][5]={“ONE”};
{
char arrl[][5]={“ONE”,“TWO”};
char strl[15]={“Rajasthan”};
char arr2[][4] ={“ONE”, “TWO”, “THREE”};

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 179

char arr3[][4] ={“ONE”, “TWO”, “THREE”, “FOUR”}; char p[]=”ABCDE”, t;


clrscr(); int i, j;
printf(“arr=%d\n”, sizeof(arr)); clrscr();
printf(“arrl=%d\n”, sizeof(arrl)); for(i=0, j=strlen(p);i<j ;i++)
printf(“arr2=%d\n”, sizeof(arr2)); {
printf(“arr3=%d”, sizeof(arr3)); t=p[i];
} p[i]=p[j-i];
p[j-i]=t;
9.16 What is the output of the following code ? }
printf(“%s”, p);
#include<stdio.h>
}
#include<conio.h>
#include<string.h>
main()
9.21 What is the output of the following code ?
{ #include<stdio.h>
char p[9]={“ABCDEF”}; #include<conio.h>
clrscr(); main()
if(!(p[strlen(p)/2]=‘\0’)) {
printf(“strlen=%d, str=%s”,strlen(p), p); static char str[ ]={48, 49, 50, 51, 52, 53,54, 55,
else 56};
printf(“HELLO”); static char *ptr;
} int i;
ptr=str;
9.17 What is the output of the following code ? clrscr();
for(i=0; i<=8; i++)
#include<stdio.h>
{
#include<string.h>
if(*ptr)
main()
printf(“%c\n”, *ptr+17);
{
ptr++;
char arr[]=”hello”;
}
clrscr();
}
printf(6 + “ABCDEFG”“hi”);
printf(“%c”, “1234567”[3]);
strcpy(arr, “AB12345”);
9.22 What is the output of the following code ?
printf(“\s”, arr); #include<stdio.h>
} #include<conio.h>
void main()
9.18 What is the output of the following code ? {
char ch=“ABCDEF”[3];
#include<stdio.h>
clrscr();
#include<conio.h>
printf(“ch=%c\n”, ch);
main()
printf(“string=%s”, “ABCDEF”[3]);
{
}
char arr[4]=”hello”;
clrscr();
printf(“%c”, 4[“123456789”]);
9.23 Fowllowing program is to print a nonzero value if c
printf(“%s”, arr) ; is lower case a What is the output of the program?
} #include<stdio.h>
#include<conio.h>
9.19 What is the output of the following code ? #include<ctype.h>
#include <stdio. h> main()
#include<conio.h> {
main() int j, c;
{ printf(“\nEnter a Letter: “);
char arr[10]=”ABCDEF”; scanf(“%d”, &c) ;
clrscr(); j = islower(c);
scanf(“%[^\n]”, arr);/* input: 7654321*/ printf(“%d”, j) ;
printf(“CASE1=%s\n”, arr); getch();
printf(“CASE2=%[s^\n]”, arr); }
}
9.24 Fowllowing program is to print the length of the
9.20 What is the output of the following code ? string What is the output of the program ?
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() #include<string.h>
{ main()
{

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 180 Strings Chapter 9

int l; clrscr();
char string[30]; x=strcmp(strl[], str2[]);
clrscr(); if(x==0)
strcpy(string[30], “My First C program”); printf(“Strings are equal”);
l=strlen(string); else
printf(“%d”, 1); printf(“Strings are not equal”);
getch(); getch();
} }

9.25 What is the output of the program ? 9.29 What is the output of the program?
/*to print the reverse of a string/* #include<stdio.h>
#include<stdio.h> #include<string.h>
#include<conio.h> main ()
#include<string.h> {
main() char str[]=”Computer\0”;
{ int i=strlen(str);
char sl[30], s2[30]; printf(“Str length is %d\n”, ++i);
clrscr(); }
printf(“Enter a string: “);
gets(sl);
s2=strrev(sl);
printf(“\nThe reverse string is:%s”, s2); LAB PROGRAMS
getch();
}
9.1. Write a program which illustrate array initialization
9.26 What is the output of the program?
during compilation.
#include<stdio.h>
#include<conio.h> 9.2. Write a program which illustrate the use of scanf()
#include<ctype.h> and printf() for string Input/Output.
main()
{
9.3. Write a program which illustrate the use of scanf()
char c; and printf() for string I/O. scanf() must accepts
clrscr(); multiword string.
printf(“Enter a character: “);
scanf(“%c”, &c); 9.4. Write a program for conversion of lower case
printf(“%c”, isupper(c)); characters to upper case in a string.
getch();
9.5. Write a program to copy a string using library
}
function strcpy().
9.27 Follwoing program is to print a string. What is the 9.6. Write a program for conversion of a characters
output of the program ? string having digits to its integer equivalent.
#include<stdio.h>
9.7. Write a program which replace lowercase with
#include<conio.h>
main() uppercase and viseversa.
{ 9.8. Write a program for concatenation of strings using
char str[25] ;
library function strcat().
clrscr();
puts(“Enter a string:”) ; 9.9. Write a program to display all consonants in a
gets(str); given line, without using any if.
puts(“\nThe entered string is:”, str);
getch(); 9.10. Write a program to copy a string without using
} library function.
9.28 Following program is to compare two string. What 9.11. Write a program to check a string for palindrome
is the output of the program? using library functions.
/*to compare two strings/* 9.12. Write a program which accept a month number
#include<stdio.h> and display the month name.
#include<conio.h>
#include<string.h> 9.13. Write a program which compare string using library
main() function strcmp().
{
char strl[]=”abc”; 9.14. Write a program to emulate strcmp using functions.
char str2[]=”abc”; 9.15. Write a programme to count number of vowels and
char x=0;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 9 Strings Page 181

consonants in the given sentence 9.26. Write a program which search a substring in a
9.16. Write a program to display the length of a string given string and replace all the occurrence of the
and count number of vowels in it. substring by another string of equal length. ( use
library functions ).
9.17. reverse a given string
9.27. Write a program to search a substring in a given
9.18. Write a program which accepts input a person’s string and replace only the first occurrence of the
name in first, middle, last form and display in the substring by another string of equal length. ( use
form last, first, M where M is the first letter in the library functions ).
person’s middle name using built in functions.
9.28. Write a program to rearrange an array without
9.19. Write a program to check a string for palindrome using any temporary array
without using string function.
9.29. Write a program to calculate the frequency of all
9.20. Write a program which accepts a string and a characters in a stream of data.
character and check if that character is present in
the string or not. 9.30. Write a program to count number of characters,words
and lines in a given text multiple blanks between
9.21. Write a program to reverse all strings stored in an words are counted as characters.
array
9.31. Write a program to count number of vowels, blanks
9.22. Write a program to sort names in alphabetical and consonants in a given text.
order.
9.32. Write a program to check for lexical equivalence of
9.23. Write a program to calculate frequency of a two strings without using any library function.
particular character in a stream of data.
9.33. Write a program to concatenate two strings without
9.24. Write a program to decode a brief message using using strlen() and strcat().
substitution cipher.
9.34. Write a program to perform various operations on
9.25. Write a program for encryption and decryption of strings without using language supported built-in
a string. functions.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

10
FUNCTIONS

10.1 INTRODUCTION

Consider a program wherein a set of operation has to be repeated


often, though not continuously, n times or so. If they has to be repeated
continuously, loops could be used. Instead of inserting the program
statement for these operation at so many places, write a separate
program segment and compile it separately. As many times as it is
needed, keep calling the segment to get result. The separate program
is called a function and the program that calls it is called the main
program. Figure 10.1 explains this concept.

Figure 10.1 : Concept of Function

A function is a self-contained block of program statements that


perform a particular task. It is often defined as a section of a program
performing a specific job. Every function interfaces to the outside
world in terms of how information is transferred to it and how results
ʇ NOTE
generated by the function are transmitted back from it. This interface A function f that uses another
is basically specified by the function name. For example, look at figure function g, is known as the
10.1 which explains how the main() calls another function to perform calling function and g is known
as the called function.
a well-defined task.
From the figure we see that main() calls the function named
functn1(). Therefore, main() is known as the calling function and
functn1() is known as the called function. The moment the compiler

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 183

encounters a function call, instead of executing the next statement in


the calling function, the control jumps to the statements that are a part
of the called function. After the called function is executed, the control
is returned back to the calling program.
It is not necessary that the main() can call only one function, it
can call as many functions as it wants and as many times as it wants.
For example, a function call placed within a for loop, while loop, or
do-while loop may call the same function multiple times until the
condition holds true.
Another point is that it is not only the main() that can call other
functions. A function can call any other function. For example, look at
figure 10.2 which shows one function calling another, and this function
in turn calling some other function. From this we see that every function
encapsulates a set of operations and when called it returns information
to the calling program.

Figure 10.2 : Function may call any Function

Why are function Needed ?


The use of functions provides several benefits :
(1) Different programmers working on one large project can divide
the workload by writing different functions.
(2) It makes programs easier to understand and maintain by
breaking up a program into easily manageable chunks. Even
without software engineering, functions allow the structure of
the program to reflect the structure of its application.
(3) The main program can consist of a series of function calls rather
than countless lines of code. It can be executed as many times
as necessary from different points in the main program. Without
the ability to package a block of code into a function, programs
would end up being much larger, since one would typically need
to replicate the same code at various points in them.
(4) We can reuse well written functions in multiple programs. The
C standard library is an example of the reuse of functions. This
enables code sharing.
(5) Functions can be used to protect data. This is related with the

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 184 Functions Chapter 10

concept of local data. Local data is the data described within


a function. They are available only within a function when the
function is being executed.

10.2 FUNCTION DECLARATION


ʇ NOTE
All the header files contain declarations for a range of functions, Function declaration is a
as well as definitions for various constants. In a C program, a user- declaration statement that
identifies a function with its
written function should normally be declared prior to its use to allow name, a list of arguments that
the compiler to perform type checking on the arguments used in its it accepts, and the type of data
call statement or calling construct. The general form of this function it returns.

declaration statement is as follows:


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

There are three basic parts in this declaration.


(1) function_name is the name given to the function and it follows
the same naming rules as that for any valid variable in C.
(2) return_data_type specifies the type of data given back to the
calling construct by the function after it executes its specific
task.
(3) data_type_list specifies the data type of each of the variables,
the values of which are expected to be transmitted by the calling
construct to the function.
The following are some examples of declaration statements.
float Ftoc(float faren);
double power(double, int);
int isPrime(int);
void printMessage(void);
void fibo_series(int);

A function has a name that both identifies it and is used to call it


for execution in a program. The name of a function is global. Functions,
which perform different actions, should generally have different names.
The names are, generally, created to indicate the particular job that the
function does, as is seen in above examples.
Things to Remember :
(1) After the declaration of every function, there should be a
semicolon. If the semicolon is missing, the compiler will generate
an error message.
 PROGRAMMING TIPS
(3) Use of argument names in the function declaration statement is Use argument names in the
optional. So both declaration statements are valid in C. function declaration, though it
is optional.
int functn(int, char, float);
or
int functn(int num, char ch, float numf);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 185

(4) A function cannot be declared within the body of another


function.
(5) A function having void as its return type cannot return any
value.
(6) A function having void as its parameter list cannot accept any
value. So the function declared as
void calculate(void);
or
void calculate()

does not accept any input/arguments from the calling function.


(7) If the function declaration does not specify any return type, then
by default, the function returns an integer value. Therefore when
a function is declared as
multiply(int x, int y);
then the function multiply accepts two integer values from the
calling function and in turn returns an integer value to the caller.
(2) The function declaration is global. Therefore, the declared
function can be called from any point in the program.

(8) Some compilers make it compulsory to declare the function before


its usage while other compilers make it optional. However, it is
good to always declare the function before its usage as it allows
error checking on the arguments in the function call.
ʇ NOTE
10.3 FUNCTION DEFINITION Function definition consists of a
function header that identifies
When a function is defined, space is allocated for that function in the the function, followed by the
body of the function containing
memory. A function definition comprises two parts:
the executable code for that
 Function header function.
 Function body
The general form of function definition is as follows:
return_data_type function_name(data_type variable1, data_type variable2,...)
{
............
statements
...........
return(variable);
}

The number of arguments and the other of arguments in the


function header must be same as that given in the function declaration
 PROGRAMMING TIPS
statement. The parameter list in the
While the first line is known as the function header, the rest of function definition as well
the portion comprising of program statements within { } is the function as function declaration must
match.
body which contains the code to perform the specific task.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 186 Functions Chapter 10

The function header is same as that of function declaration. The


only difference between the two is that a function header is not followed
by a semicolon. The list of variables in the function header is known as
ʇ NOTE
the formal parameter list. The parameter list may have zero or more A function can be defined either
parameters of any data type. The function body contains instructions before or after the main().
to perform the desired computation in that function.
The function definition itself can act as an implicit function
declaration. So the programmer may skip the function declaration
statement in case the function is defined before being used.
Following code is example of function that computes xn, where x
is any valid number and n an integer value. Here first argument is any
valid number, second argument is power index.
double power(double x, int n) /* function header */
{ /* function body starts */
double result = 1.0; /* declaration of variable result */
for(int j=1; j<=n; i++) /* computing xn */
result*= x;
return result; /* return value in ‘result’ to calling function */
} /* function body ends */

In above code, the first statement in the function body declares a


variable result that is initialized with the value 1.0. The variable result
is local to the function, as are all automatic variables declared within a
function body. This means that the variable result ceases to exist after
the function has completed execution.
The calculation is performed in the for loop. A loop control
variable i is declared in the for loop which will assume successive
values from 1 to n. The variable result is multiplied by x once for each
loop iteration. Thus this occurs n times to generate the required value.
If n is 0, the statement in the loop will not be executed at all because
the loop continuation condition will immediately fail, and so result will
be left as 1.0.
ʇ NOTE
return statement If a function returns a value,
usually it has to be assigned
The return statement is used to terminate the execution of a to some variable since a value
function and returns control to the calling function. The general form is being returned. If there is no
of the return statement is as follows: assignment specified, then is
it a valid statement in C? The
return expression; answer is yes but may fire a
or warning message. It is allowed
return(expression); as the returned value is simply
discarded.
where expression must evaluate to a value of the type specified
in the function header for the return value. The expression can be any
desired expression as long as it ends up with a value of the required
type. In earlier example, the return statement returns the value of
result to the point where the function was called. What might strike
immediately is that the variable result, as stated earlier, ceases to exist

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 187

on completing the execution of the function. So how is it returned? The


answer is that a copy of the value being returned is made automatically,
and this copy is available to the return point in the program.
The expression can also include function calls, if those functions
return a numeric value. The following is a valid calling statement:
x = power(power(2, 4), 2);
The inner call to power returns 16, which is then used as an
argument for the outer call to power. This call to power passes 16 and
2, and power will return the value 256 which would get assigned to x.
ʇ NOTE
10.4 FUNCTION CALL Function definitions are often
placed in a separate header file
Invoking or calling function means executing the code of a function from which can be included in other
C source files that wish to use
program. When a function is invoked the compiler jumps to the called
the functions. For example, the
function to execute the statements that are a part of that function. header file stdio.h, contains
Once the function complete its task, the program control is returned to the definition of scanf and
printf functions. We simply
the calling function. include this header file and
The syntax of function call statement is as follows call these functions without
worrying about the code to
function_name(variable1, variable2,...);
implement their functionality.
When the function declaration is present before the function call,
the computer can check if the correct number and type of arguments
are used in the function call and the returned value, if any, is being
used reasonably.

10.4.1 Points to Remember While Calling a Function


 PROGRAMMING TIPS
The following points should be kept in mind while calling a function A logic error will be generated
• The parameter list must be separated with commas. if the arguments in the function
• Function name and the number and type of arguments in call are placed in the wrong
order.
the function call must be same as that given in the function
declaration and function header of the function definition.
• If by mistake the parameter passed to a function are less than
what it is specified to accept then the unmatched argument will
be initialized to some garbage value.
• If by mistake the parameter passes to a function are more than
what it is specified to accept then the extra arguments will be
discarded.
• Names (and not the types) of variables in function declaration,
function call, and header of function definition may vary.
• Arguments may be passed in the form of expressions to the
called function. In such cases, arguments are first evaluated and
converted to the type of formal parameter and then the body of
the function gets executed.
• If the data type of the argument passed does not match with that
specified in the function declaration then either the unmatched

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 188 Functions Chapter 10

argument will be initialized to some garbage value or compile


time error will be generated.
• If the return type of the function is not void, then the value
returned by the called function may be assigned to some variable
as shown in the following statement.
variable_name = function_name(var1, var2,...);
Let us now consider a program to add two integers using function.

/*****************************************************************************/
/* Program 10.1 : To add two integer using function */
/*****************************************************************************/

#include <stdio.h>
int sum (int a, int b); /* Function Declaration */
int main()
{
int num1, num2, total = 0;
clrscr();
puts(“This program calculate the sum of two number using function.”);
printf(“\nEnter the first number : ”);
scanf(“%d”,&num1);
printf(“\nEnter the second number : ”);
scanf(“%d”,&num2);
total = sum(num1, num2); /* Function Call */
printf(“\nTotal = %d”, total);
getch();
return 0;
}

/* Function Defination */
int sum(int a, int b) /* Function Header */
{ /* Function Body */
int result;
result = a + b;
return result;
}
/*****************************************************************************/

 OUTPUT :
This program calculate the sum of two number using function.
Enter the first number : 45
Enter the second number : 35
Total = 80

The variables declared within the function and its parameters


 PROGRAMMING TIPS
are local to that function. The programmer may use same name for It is an error to use void as the
variables in other functions. This eliminates the need for thinking and return type when the function
keeping unique names for variables declared in all the functions in the is expected to return a value to
the calling function.
programs.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 189

In the function sum(), we have declared a variable result just


like any other variable. Variables declared within a function are called
automatic local variables because of two reasons
 PROGRAMMING TIPS
(1) They are local to the function, So, their effect (in terms of scope, A function cannot be
lifetime, or accessibility) is limited to the function. Any change used on the left side of a
made to these variables is visible only in that function. assignment. Therefore writing,
func(10)=100; is invalid in
(2) They are automatically created whenever the function is called C, where func that accepts an
and they cease to exist at the end of the function. integer value.

10.5 PASSING PARAMETER TO FUNCTION

When function is invoked, a list of parameters is passed into the


function, if required. The list of parameters is passed into only those
function that have been defined with parameters. During its invocation
as well as definition, either a variable or an address of a variable is
passed into the function. When a variable or a value is passed to the
function during its invocation, this function invocation is called call
by value. However, when an address of the variable is passed to the
function during its invocation, then this function invocation is called
call by reference, Let’s discuss the two types of function call in the
following sections.

10.5.1 Call By Value


Invoking a function by passing values or variables to the function is
called call by value. When a method is invoked by passing values, the
change made to the value is not visible outside the functions definition.
Program 10.2 shows an example of invoking a function by using call by
value method:

/*****************************************************************************/
/* Program 10.2 : Passing Parameter by using call by Value Method */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int area(int length, int breadth)
{
int area_rec;
area_rec = length*breadth;
return(area_rec);
}
void main()
{
int lngth, brdth, result;
clrscr();
printf(“This program is the example of passing parameter call by value method.”);
printf(“Changes made in the formal parameters are not visible outside the

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 190 Functions Chapter 10

function definition.”);
printf(“\nEnter length: “);
scanf(“%d”, &lngth);
printf(“Enter breadth: “);
scanf(“%d”, &brdth);
result = area(lngth, brdth);
printf(“Area of rectangle is: %d”, result);
getch();
}
/*****************************************************************************/

 OUTPUT :
This program is the example of passing parameter call by value method. Changes
made in the formal parameters are not visible outside the function definition.
Enter length: 10
Enter breadth: 20
The area of rectangle is: 200

 EXPLANATION :
In program 10.2, the area() method created, is invoked by using the call by value
method. The parameters lngth and brdth, which are used invoke the function are
called actual parameters. The argument length and breadth, which are used in the
function definition, are called formal parameters. When the function is called, the
value of the actual parameter is copied into the formal parameter.

The above method is called parameter passing by value. The


changes made in the formal parameters are not visible outside the
function definition. In addition, these changes do not affect the value
stored in the actual parameter. Program 10.3 shows an example of a
method in which the changes are made in the formal parameter:

/*****************************************************************************/
/* Program 10.3 : Making Changes in formal Parameter */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int area(int length, int breadth)
{
int area_rec;
area_rec = length*breadth;
length = 10;
printf(“\nValue of length inside function definition: %d”, length);
return(area_rec);
}
void main()
{
int length, breadth, result;
clrscr();
printf(“This program is the example of passing parameter call by value method.”);
printf(“\nEnter length: “);
scanf(“%d”,&length);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 191

printf(“Enter breadth: “);


scanf(“%d”, &breadth);
printf(“\nValue of length before function invocation: %d”, length);
result = area(length, breadth);
printf(“\nValue of length after function invocation: %d”, length);
printf(“\nArea of rectangle is: %d”, result);
getch();
}

/*****************************************************************************/

 OUTPUT :
This program is the example of passing parameter call by value method.
Enter length: 5
Enter breadth: 6
Value of length before function invocation: 5
Value of length inside function definition: 10
Value of length after function invocation: 5
Area of rectangle is: 30

 EXPLANATION :
In program 10.3, the value of the length formal parameter has been changed inside
the function definition. However, this change is not visible inside the main() function
where the area() function is invoked.

ʇ NOTE
Points To be Remember: Using call be value method of
passing values must be preferred
The following points are to be noted while passing arguments to a to avoid inadvertent changes to
function using call-by-value method. variables of the calling function
(1) When arguments are passed by value, the called function creates in the called function.
new variables of the same data type as the arguments passed to
it.
(2) The value of the arguments passed by the function are copied
into the newly created variables.
(3) Values of the variables in the calling functions remain unaffected
when the arguments are passed using call by value technique.
(4) Arguments are called by value when the function does not need
to modify the values of the original variables in the calling
program.
Therefore, call by value method of passing arguments to a function
must be used only in two cases:
(5) When the called function does not modify the value of the actual
parameter. It simply uses the value of the parameters to perform
its task.
(6) When you want that the called function should only temporarily
modify the value of the variables and not permanently. So
although the called function may modify the value of the
variables, but these variables remain unchanged in the calling
program.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 192 Functions Chapter 10

Advantage and Disadvantage :


The biggest advantage of using call by value technique to pass arguments
to the called function is that arguments can be variables (e.g., y),
literals (e.g., 8), or expressions (e.g., y+1). The disadvantage is that
copying data consumes additional storage space. In addition, it can
take a lot of time to copy, thereby resulting in performance penalty,
especially if the function is called many times.

10.5.2 Call by Reference


Sometimes, you pass the parameter to a function and its value is
ʇ NOTE
changed inside the function call. In case you want to make the changed Apart from passing a single value
value visible outside the function, then you must pass the parameter or single reference as function
parameter, you can also pass an
by reference. C does not support the method of passing parameter of array as the function parameter,
reference; therefore, it is done indirectly by passing the addresses or the as discussed later.
variable through its address. Program 10.4 shows an example of passing
parameter by by reference.

/*****************************************************************************/
/* Program 10.4 : Passing Parameter by Using Call by Reference Method
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void main()
{
int num1, num2;
clrscr();
printf(“\nThis program swap the two given number.”);
printf(“\nThis is example of Passing Parameter by Using Call by Reference.”);
printf(“\nEnter First Number : ”);
scanf(“%d”, &num1);
printf(“Enter Second Number : ”);
scanf(“%d”, &num2);
printf(“\nValue of num1 before function invocation: %d”, num1);
printf(“\nValue of num2 before function invocation: %d”, num2);
swap(&num1,&num2);
printf(“\n\n\nValue of num1 after function invocation: %d”, num1);
printf(“\nValue of num2 after function invocation: %d”, num2);
getch();
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 193

 OUTPUT :
This program swap the two given number.
This is example of Passing Parameter by Using Call by Reference.
Enter First Number : 10
Enter Second Number : 20

Value of num1 before function invocation: 10


Value of num2 before function invocation: 20

Value of num1 after function invocation: 20


Value of num2 after function invocation: 10

 EXPLANATION :
The swap() function is created in Program 10.4 and parameter to this method are
passed by using the call by reference method. You notice that the changes made to the
formal parameters inside the function definition is also reflected in main() function.

Advantage and Disadvantage:


The advantages of using call-by-reference technique of passing arguments
are as follows:
(1) Since arguments are not copied into new variables, it provides
greater time-and space-efficiency.
(2) The function can change the value of the argument and the
change is reflected in the caller.
(3) A function can return only one value. In case we need to return
multiple values, pass those arguments by reference so that
modified values are visible in the calling function.
Disadvantages:
However, the side-effect of using this technique is that when an argument
is passed using call by address, it becomes difficult to tell whether that
argument is meant for input, or both.

10.6 PASSING ARRAY IN FUNCTION

When an array is passed to a function, the address of the array is


passed and not the copy of the complete array. Therefore, when a
function is called with the name of the array as the argument, address
to the first element in the array is handed over to the function. Hence
when an array is a function argument, only the address of the array
is passed to the function called. This implies that during its execution
the function has the ability to modify the contents of the array that
is specified as the function argument. Therefore array is not passed
to a function by value. This is an exception to the rule of passing the
function arguments by value. Consider the program given below.

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 194 Functions Chapter 10

/* Program 10.5 : Passing Array to a Function


/*****************************************************************************/

#include <stdio.h>
void triple(int [], int); /* declaration of function */
int main()
{
int myArray[100], size, i;
clrscr();
printf(“This program is example of passing array to function.”);
printf(“\nEnter size of array : “)
scanf(“%d”, &size);
printf(“Enter element of Arrays :\n”);
for(i = 0; i < size; i++)
scanf(“%d”, &myArray[i]);
triple(myArray, size);
printf(“After function invocation array is :\n”);
for(i = 0; i < size; i++)
printf(“%d\t”, myArray[i]);
getch();
return 0;
}

void triple(int a[], int size) /* function definition */


{
int i;
for(i =0; i < size; i++)
a[i] = 3*a[i];
}

/*****************************************************************************/

 OUTPUT :
This program is example of passing array to function.
Enter size of array : 8
Enter element of Arrays :
8 12 6 15 33 28 19
After function invocation array is :
24 36 18 45 99 84 57

The following program uses a function to find the average age of


students of a class chosen for a junior quiz competition.

/*****************************************************************************/
/* Program 10.6 : To find the average age of students of a class */
/*****************************************************************************/

#include <stdio.h>
#define SIZE 100
float avg_age(int [],int);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 195

int main(void)
{
int i,b[SIZE],n;
float average;
printf(“This program calculate the average age of students of a class.”);
printf(“\nEnter Number of Students: ”);
scanf(“%d”,&n);
printf(“\nEnter the age of all students :\n”);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
average = avg_age(b,n);
printf(“\nAverage age of students = %0.2f”, average);
return 0;
getch();
}
float avg_age(int a[], int n)
{
int j;
float sum = 0.0;
for(j=0;j<n;j++)
sum = sum+a[j];
return sum/n;
}

/*****************************************************************************/

 OUTPUT :
This program calculate the average age of students of a class.
Enter Number of Students : 5
Enter the age of all students :
14 16 15 18 19
Average age of students = 16.40

The following program uses a function to find the maximum value


in an array.

/*****************************************************************************/
/* Program 10.7 : Function to find the maximum value in an array. */
/*****************************************************************************/

#include <stdio.h>
int maximum(int [],int); /* function prototype */
int main(void)
{
int values[50], size, i, max;
clrscr();
printf(“This program find the maximum value in given array.”);
printf(“\nEnter the size of Array : ”);
scanf(“%d”, &size);
printf(“\nEnter elements of Array :\n ”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 196 Functions Chapter 10

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


scanf(“%d”, &values[i]);
max = maximum(values, size); /* function call */
printf(“\nMaximum value is %d.\n”, max);
getch();
return 0;
}
int maximum(int values[], int n) /* function definition */
{
int max_value, i;
max_value = values[0];
for(i = 1; i < n; ++i)
if(values[i] > max_value)
max_value = values[i];
return max_value;
}

/*****************************************************************************/

 OUTPUT :
This program find the maximum value in given array.
Enter the size of Array : 5
Enter elements of Array :
91 104 121 214 58 221
Maximum value is 221.

When an array is passed to a function, actually the address of


the first element (called the base address of an array) is passed which
is nothing but passing arguments by address. In general, when a one
dimensional array is passed to a function, it degenerates to a pointer.
This will be explained in the chapter on pointers.
Passing Strings to Function :
Strings are passed to functions in the same way as are one-
dimensional arrays. Consider Program 10.8 that uses a function to copy
one string into another without using the strcpy() function available
in the standard library of C.

/*****************************************************************************/
/* Program 10.8 : Function to copy one string into another */
/*****************************************************************************/

#include <stdio.h>
void string_copy(char [], char []); /* function prototype */
int main()
{
char source[100]; /* source string */
char destin[100]; /* destination string */
clrscr();
printf(“This program copy one string to another using function.”);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 197

printf(“\nEnter Source String : ”);


scanf(“%[^\n]”,source); /* read input source string */
string_copy(destin, source); /* function call */
printf(“\nDestination string : %s\n”,destin);
getch();
return 0;
}
void string_copy(char d[], char s[]) /* function definition */
{
int i = 0;
printf(“\nSource string : %s”,s);
/* copying the string */
for (i = 0; s[i] != ‘\0’; i++)
d[i] = s[i]; /* copy NUL character to destination string */
}
/*****************************************************************************/

 OUTPUT :
This program copy one string to another using function.
Enter Source String : Jhunjhunuwala
Source string : Jhunjhunuwala
Destination string : Jhunjhunuwala

10.7 RECURSIVE FUNCTION

Recursive functions are those functions that call themselves during


their execution until certain condition are not satisfied. This process is
used for repetitive computation in which each action is stated in terms
of the previous result. For example, if you are calculating the factorial
of a number, then you multiply the number to number -1. You continue
doing this till you reach up to one, to get the factorial of the given
number. In other words, if you are supposed to get the factorial of five
you perform the following multiplication.
5*4*3*2*1
In this example, the multiplication is performed repeatedly, until
the number reaches one. The factorial calculated in this example, can
be calculated by using a recursive function, as shown in program 10.9.

/*****************************************************************************/
/* Program 10.9 : Using Recursive Function */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
long factorial(long n)
{
if(n==1)
return n;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 198 Functions Chapter 10

else
return(n*factorial(n - 1));
}
void main()
{
long n, fact;
clrscr();
printf(“This program calculate the factorial of given number using recursion.”);
printf(“\nEnter a number : ”);
scanf(“%d”, &n);
fact = factorial(n);
printf(“\nFactorial of %d is %l.”, n, fact);
getch();
}

/*****************************************************************************/

 OUTPUT :
This program calculate the factorial of given number using recursion.
Enter a number : 5
Factorial of 5 is 120.

 EXPLANATION :
In this program, the factorial() function is created to calculate the factorial of a
number using recursive function.

Two conditions must be satisfied, to solve a problem recursively:


(1) The problem must be written in recursive form.
(2) The problem statement must include a stopping condition.
Program 10.10 shows another example of recursive function:

/*****************************************************************************/
/* Program 10.10 : Recursive Function to get nth Term of Fibonacci Series */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
int fibo(m)
{
if(m==1 || m == 2)
return(1);
else
return(fibo(m-1)+fibo(m-2));
}
void main()
{
int i,n;
clrscr();
printf(“This program calculate the Fibonacci number using recursion.”);
printf(“\nEnter term number : ”);
scanf(“%d”,&n);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 199

i = fibo(n);
printf(“\nThe %dth Fibonacci number is %d.”, n, i);
getch();
}

/*****************************************************************************/

 OUTPUT :
This program calculate the Fibonacci number using recursion.
Enter term number : 12
The 12TH Fibonacci number is 144.

 EXPLANATION :
The fibo() function created in program 10.10 is a recursive function that calculates
the nth term of the Fibonacci series. The variables used in a program behave differently
according to the type and scope.

ʇ NOTE
10.8 RECURSION VS ITERATION Recursion is more of a top-
down approach to problem
Recursion is a very powerful tool for solving complex problem, solving in which the original
problem is divided into smaller
particularly when the underlaying problem or data to be treated
sub-problems. On the contrary,
defined in recursive terms. For such problems, recursion can lead to iteration follows a bottom-up
solutions that are much clearer and easier to modify than their iterative approach that begins with what
is known and then constructing
counterparts. the solution step by step
However, recursive solutions are not always the best solutions.
In some cases, recursive programs may require substantial amount of
run-time overhead. Therefore, when implementing a recursive solution,
there is a trade off involved between the time spent in constructing and
maintaining the program and the cost incurred in running time and
memory space required for the execution of the programs.
Advantage of Recursion :
The advantage of using a recursive program are as following:
• Code is clearer and easier to use.
• Recursive solutions often tend to be shorter and simpler non-
recursive ones.
• Recursion work similar to the original formula to solve a problem.
• In some (limited) instance, recursion may be more efficient.
• Follows a divide and conquer technique to solve problems.
Disadvantage of Recursion :
The disadvantages of using a recursive programs includes the following:
• Using a recursive function takes more memory and time to
execute a compared top its non-recursive counter part.
• For many programmers and readers, recursion is a difficult
concept.
• Recursion is implemented using system stack. If the stack space

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 200 Functions Chapter 10

on the system is limited, recursion to a deeper level will be


difficult to implement.
• Aborting a recursive process in midstream is slow and sometimes
nasty.
• It is difficult to find bugs, particularly while using global variables.
In general, an iterative version of a program will execute more
efficiently in terms of time and space than a recursive version. This
is because the overhead involved in entering and exiting a function
is avoided in iterative version. However a recursive solution can be
sometimes the most natural and logical way of solving a complex
problems.
ʇ NOTE
10.9 STORAGE CLASSES Storage class of a variable
defines the scope (visibility)
Storage class gives the following information about the variable or the and lifetime of variables and/
or functions declared within a C
function.
program.
(1) It specifies how long the storage allocation will continue to exist
for that function or variable.
(2) The storage class of a function or a variable determines the part
of memory where storage space will be allocated for that variable
or function (whether the variable/function will be stored in a
register or in RAM).
(3) It specifies whether the variable or function has internal, external,
or no linkage.
(4) It specifies the scope of the variable or function, i.e., the storage
class indicates the part of the C program in which the variable
name is visible or the part in which it is accessible. In other words,
whether the variable/function can be referenced throughout the
program or only within the function, block, or source file where
it has been defined.
(5) It specifies whether the variable will be automatically initialized
to zero or to any indeterminate value.
C supports four storage classes: automatic, register, external, and
static. The syntax for specifying the storage class of a variable is
storage_class_specifier data_type variable_name

10.9.1 auto Storage Class


The auto storage class specifier is used to explicitly declare a variable
with automatic storage. It is the default storage class for variables
declared inside a block. For example, in statement
auto int y;
y is an integer that has automatic storage. It is deleted when the block
in which y was declared exits.
This storage class can be used to declare variables in a block or

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 201

the names of function parameters. However, since the variable names


or names of function parameters by default have automatic storage,
the auto storage class specifier is therefore treated as redundant while
declaring data.
ʇ NOTE
10.9.2 register Storage Class One drawback of using a register
variable is that they cannot
When a variable is declared using register as its storage class, it is be operated using the unary
stored in a CPU register instead of RAM. Since the variable is stored ‘&’ operator because it does
not have a memory location
in RAM, the maximum size of the variable is equal to the register size. associated with it.
A register variable is declared in the following manner.
register int y;
Register variables are used when quick access to the variable is
needed. It is not always necessary that the register variable will be
stored in the register. Rather, the register variable might be stored in
a register depending on the hardware and implementation restrictions.
ʇ NOTE
10.9.3 extern Storage Class A large C program can be
broken down into smaller
The storage class extern is used to give a reference of a global variable programs. When these smaller
that is visible to all the program files. Such global variables are declared programs are compiled, they
are joined together to form a
like any other variable in one of the program file. When there are large program. However, these
multiple files in a program and you need to use a particular function or smaller programs may need
variable in a file apart from which it is declared, then use the keyword to share certain variables for
processing. For such situations
extern. To declare a variable y as extern write, C language provides an external
extern int y; storage class.

External variables may be declared outside any function in a


source code file as any other variable is declared. But usually external
variables are declared and defined at the beginning of a source file.
ʇ NOTE
10.9.4 static Storage Class While auto is the default storage
class for all local variables,
Static variables have a lifetime over the entire program, i.e., memory static is the default storage class
for the static variables is allocated when the program begins running for all global variables.
and is freed when the program terminates. To declare an integer x as
static, write,
static int y = 45;
Here y is a local static variable. Static local variables when
defined within a function are initialized at the runtime. The difference
between an auto variable and a static variable is that the static variable
when defined within a function is not re-initialized when the function
is called again and again. It is initialized just once and further calls of
the function share the value of the static variable. Hence, the static
variable inside a function retains its value during various calls.
Table 10.1 compares the key features of all the storage classes.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 202 Functions Chapter 10

TABLE 10.1 : Comparison of storage classes

FEATURE STORAGE CLASS


auto extern register static
Accessibility Accessible within the Accessible within Accessible within the Local: Accessible within
function or block in all program files function or block in the function or block in
which it is declared. that are a part of which it is declared. which it is declared.
the program. Global: Accessible
within the program in
which it is declared.
Storage Main Memory Main Memory CPU Register Main Memory
Existence Exists when the Exists Exists when the Local: Retains value
function or block in throughout the function or block in between function calls
which it is declared execution of the which it is declared or block entries.
is entered. Ceases program. is entered. Ceases Global: Preserves value
to exist when the to exist when the in program files.
control returns from control returns from
the function or the the function or the
block in which it was block in which it was
declared. declared.
Default value Garbage Zero Garbage Zero

10.10 FUNCTIONS AND VARIABLES

Different types of variables are used in the C program, which have their
associated scope or visibility. The variables declared within a function
or a block of codes are known as local variables. These are visible only
within the function or block of code in which it is declared. However,
the variables declared outside the function are called global variables
and are visible in all the block of codes or functions in the program.
Moreover, the variables that are declared with the static and register
keywords and are called static and register variables, respectively.
Let’s discuss the behavior of these variables with a function under the
following broad level headings:
(1) Local and Global Variables
(2) Static and Register Variables
Local and Global Variables
The functions created in the program including the main() function
of the program, declare variables to store temporary values. These
variables are local variable and are accessible only within the function
it is declared. If any attempt is made to access the variable outside the
function, a compilation error occurs. Following code shows an example
in which the local variable is accessed outside the function and cause
compilation error:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 203

#include<stdio.h>
#include<conio.h>
void function1()
{
printf(“%d”, n);
}
void main()
{
int n;
clrscr();
printf(“\nEnter the number”);
scanf(“%d”,&n);
printf(“The number you entered is %d”,n);
function();
getch();
}

When you try to compile the above program, it generates a


compilation error as shown:
Undefined symbol ‘n’
The compilation error is generated because the n variable, which
is declared inside the main() function is accessed inside the function1()
function. The modified code is shown in program 10.11, which does not
cause any compilation error and executes successfully:

/*****************************************************************************/
/* Program 10.11 : Using Local Variable Inside a Function it is Declared */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void functn1()
{
int n=20;
printf(”\nInside Function the value of n is %d.”, n);
}
void main()
{
int n;
clrscr();
printf(“\nEnter the number : ”);
scanf(“%d”,&n);
printf(“\nThe number you entered is %d.”,n);
functn1();
getch();
}
/*****************************************************************************/

 OUTPUT :
Enter the number : 25
The number you entered is 25.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 204 Functions Chapter 10

Inside Function the value of n is 20.

The n variable in program 10.11 is declared in main() function


as well as in the functn1() function and accessed in both the functions.
The program compiles and executes successfully, as it works in case
of global variable. Program 10.12 shows an example of using a global
variable in a C program:

/*****************************************************************************/
/* Program 10.12 : Using Global Variable */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int n;
void functn1()
{
printf(“\nInside Function the value of n is %d.”, n);
}
void main()
{
clrscr();
printf(“\nEnter the number : ”);
scanf(“%d”,&n);
printf(“\nThe number you entered is %d.”,n);
functn1();
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the number : 35
The number you entered is 35.
Inside Function the value of n is 35.

 EXPLANATION :
The n variable is declared as a global variable in program 12, and it is accessible from
all the functions in the program.

Static and Register Variables


The variables declared with the static keyword are called static
variables. These variables can be declared locally within a function
or block of code or globally, in a program. When the static variable is
declared within a function, it is visible within the function and retains
its value during the execution of the program. These static variables
are called internal static variables. However, the static variables that
are globally declared in the program, are accessible to all the functions
in the program and retain their value throughout the execution of the

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 205

program, are known as external static variables.


The variables of a program are stored in the Random Access
Memory (RAM). However, sometimes the program variables are also
stored in the Central Processing Unit (CPU) registers to make the
execution of the program fast. The variables which need to be stored in
the CPU register are declared with the register keyword. The register
variables are local variables.
Program 10.13 shows an example of using internal static variable:

/*****************************************************************************/
/* Program 10.13 : Using Internal Static Variable */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void functn1()
{
static int result = 1;
result = result*2;
printf(“%d \n”, result);
}
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
functn1();
getch();
}
/*****************************************************************************/

 OUTPUT :
2
4
8
16

 EXPLANATION :
The result variable in program 13 is declared as the internal static variable inside the
function1 function and is used to calculate the product of numbers up to 4.

Program 10.14 shows the use of external static variable.

/*****************************************************************************/
/* Program 10.14 : Using External Static Variable */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
static int result=5;
void functn1()
{

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 206 Functions Chapter 10

result = result*2;
printf(“%d\n”, result);
}
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
functn1();
getch();
}

/*****************************************************************************/

 OUTPUT :
10
20
40
80

 EXPLANATION :
The result variable in program 10.14 is declared as an external static variable and is
used to calculate the product of numbers.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 207

REVIEW QUESTIONS #include<conio.h>


small(int, int);
main()
10.1 Define a function. Why are they needed? {
int a,b;
10.2 Explain the general syntax of a C function with printf(“\nEnter the integers: ”);
examples. scanf(“%d”,&a);
10.3 Differentiate between function declaration and scanf(“%d”,&b);
small(&a,&b);
function definition. getch();
10.4 Why is function declaration statement placed prior }
to function definition? small(int p,int r)
{
10.5 Differentiate between formal parameters and actual if {p==r)
parameters. printf (“The numbers are equal”} ;
else
10.6 Explain the concept of making function calls. if(p<r)
10.7 How many types of storage classes does the C printf(“The smaller number is: %d”, p);
else
language support? Why do we need different types
printf(“The smaller number is: %d”, r);
of classes? }
10.8 Give the features of each storage class.
10.2 Following program is to print a mesage. What is
10.9 Explain the concept of recursive functions with the output of the following program ?
example.
#include<stdio.h>
10.10 Differentiate between an iterative function and a #include<conio.h>
recursive function. Which one will you prefer to use main()
and in what circumstances? message();
{
10.11 What will happen when data type of a variable in printf(“C is a powerful language”);
the function declaration does not match with the }
corresponding variable in the function header? {
printf(“\nThe following message is displayed: “);
10.12 What will happen when a function returns a value message();
that does not match with the return type of the getch();
function? }

10.13 What do you understand by scope of a variable? 10.3 What is the output of the following code?
Explain in detail with suitable examples. #include<stdio.h>
10.14 What will happen when the actual parameters are #include<conio.h>
main()
less than formal parameters in a function?
{
10.15 How is call by value method of function calling int x, y, sum;
different from call by reference method? Give printf(“\nEnter the numbers: “);
sacanf(“%d”, &x);
suitable examples to support your answer.
scanf(“%d”,&y);
10.16 What is recursion? While writing any recursive sum =add(x,y);
function what thing(s) must be taken care of? printf(“\nThe sum is %d”, sum);
getch();
10.17 What are different categories of functions in C? }
Give examples. int add(int p, int r)
{
10.18 How are the local variables of any recursive int a;
subprogram are interpreted in C? a=p+r;
10.19 Differentiate between local and global variables. return();
}

10.4 Following program is to print product of two


integers What is the output of the following code?
PROGRAMMING OUTPUT QUIZ
#include<stdio.h>
#include<conio.h>
float mult(int, int);
10.1 What is the output of the following program ? main()
#include<stdio.h> {

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 208 Functions Chapter 10

int x, y, prod; goto here;


printf(“\nEnter the numbers: “); num++;
scanf(“%d”,&x); }
scanf(“%d”,&y); }
prod = mult(x,y);
printf(“\nThe product is %d”, prod); fun()
getch(); {
} here:
int mult(int k, int l) printf(“PP”);
{ }
int a;
a=k*l; 10.8 What is the output of the following program?
return(a);
#include<stdio.h>
}
void main()
{
10.5 What is the output of the following code? int sze=ret_val(sizeof(float));
#include<stdio.h> printf(“\nSize is %d.”, ++sze);
#include<conio.h> }
int fact(char);
main() int ret_val(int ret_val)
{ {
int n,factorial; ret val+= 2.5;
printf(“\nEnter the number: “); return(ret_val);
scanf(“%d”,&n); }
factorial=fact(n);
printf(“The factorial of %d is %d”, n, factorial); 10.9 What is the output of the following code?
getch();
#include<stdio.h>
}
main()
{
int fact(int k)
void swap();
{
int num1=20, num2=12;
int i,factorial;
swap(&num1,&num2);
factorial=1;
printf(“num1=%d num2=%d”, num1,num2);
if(k==0)
}
factorial=1;
void swap(int *a, int *b)
for(i=2;i<=k;i++)
{
factorial=factorial * i;
*a ^= *b;
}
*b ^= *a;
*a ^= *b;
10.6 What is the output of the following program? }
#include<stdio.h>
main() 10.10 What is the output of the program?
{
#include<stdio.h>
int num1=20;
#include<conio.h>
int num2=10;
void main(int x, int x)
swap(num1,num2);
{
printf(“num1 = %d, num2 = %d”, num1, num2);
clrscr();
}
printf(“%d”,x);
swap(int num11, int num22)
getch();
{
}
int temp;
temp=num11;
num11=num22; 10.11 What would be the output of the program ?
num22=temp; #include<stdio.h>
} print(x,y)
{
10.7 What is the output of the following program? printf(“x = %d, y = %d”,x, y);
}
#include<stdio.h>
main()
main()
{
{
char x=67, y=’C’;
int num=1;
print(x,y);
while(num<=5)
}
{
printf(“%d”,num);
if(num>2) 10.12 What would be the output of the program?

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 209

#include<stdio.h> int *b = (int *)malloc(sizeof (int) *5);


#include<conio.h> clrscr();
art(int m, int n) fun(arr);
{ b=arr;
int y,z; fun(b);
y=m+n; getch();
z=m*n; }
return(y,z);
} 10.16 What would be the output of the following program
main() ?
{
int m=20, n=30, l; #include<stdio.h>
clrscr(); #include<conio.h>
l=art(m,n); char *fun()
printf(“l=%d”,l); {
getch(); char arr[80];
} strcpy(arr,“work”);
return (arr);
10.13 What would be the output of the program ? }
main()
#include<stdio.h> {
#include<conio.h> char *ptr,*fun();
main () clrscr();
{ ptr=fun();
int m=1; printf(“%s”,ptr);
clrscr(); getch();
m=incr(m=incr(m=incr(m))); }
printf(“m=%d”,m);
getch(); 10.17 What would be the output of the following program
}
?
incr(m)
{ #include<stdio.h>
m++; #include<conio.h>
return(m); #include<stdlib.h>
} void print(j)
{
10.14 What would be the output of the following program printf(“%d\n”,j);
? }
void fun(i)
#include<stdio.h> {
main() void (*p) (int);
{ p=print;
int num; p(100+i);
num=func(20) (p)(100+i);
printf(%d”,num); }
} main()
int func(int num) {
{ void (*ptr) (int);
num>20?return(100):return(200) clrscr();
} ptr=fun;
(*ptr) (222);
10.15 What would be the output of the following program ptr(333);
? }
#include<stdio.h>
#include<conio.h>
10.18 What would be the output of the following program?
void fun(int *p) #include<stdio.h>
{ #include<conio.h>
printf(“%d”, p[0]); #include<stdlib.h>
} void fun(int a, int f)
void fun(int p[]) {
{ if(a==0)
printf(“%d”, p[0]); return;
} a--;
void main() if(f)
{ {
int arr[5] ={l,2,3,4,5}; fun(a, f);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 210 Functions Chapter 10

printf(“%c”,a+65);
10.22 What would be the output of the following program?
}
else #include<stdio.h>
{ #include<conio.h>
printf(“%c”,a+65); fun(int x)
fun(a,f); {
} static int i=2;
} return(x+i++);
main() }
{ void main()
clrscr(); {
fun(10,1); int i, sum=0;
printf(“\n”); int arr[6]={1, 2, 3, 4, 5, 6};
fun(10,0); clrscr();
} for(i=0;i<4,i++)
sum+=fun(arr[i]);
10.19 What would be the output of the following program printf(“SUM=%d”,sum);
}
?
#include<stdio.h> 10.23 What would be the output of the following program
#include<conio.h>
?
char *fun()
{ #include<stdio.h>
char *str; #include<conio.h>
return str=((str=”NITIN”,“AMIT”,“MUKESH”,“ANK fun(int *ptr)
IT”)); {
} int i;
void main(void) for(i=1;i<3;i++)
{ printf(“%d\n”, *(ptr+i));
clrscr(); }
printf(“%s”,fun()); void main()
} {
int arr[]={1, 2, 3, 4, 5, 6, 7, 8, 9};
10.20 What would be the output of the following program clrscr();
fun(arr+1);
?
}
#include<stdio.h>
char fun() 10.24 What would be the output of the following program?
{
static char* str=”ABC\0”; #include<stdio.h>
printf(“%s\n”,str); #include<conio.h>
if(*str++!-=NULL) fun(char *str)
return(main()) {
} return(printf(“%s\n”, str));
main(void) }
{ main()
fun(); {
} char *str=”ABCDEFG”;
clrscr();
printf(“The string size is %d”,fun(str));
10.21 What would be the output of the following program
}
?
#include<stdio.h>
#include<conio.h>
int fun(int *p, int *q) LAB PROGRAMS
{
*p ^= *q, *q ^= *p, *p ^=*q;
} 10.1. Write a program to calculate square of a number
void main(void)
{
using a function.
int a=30, b=40; 10.2. Write a program to illustrate the use of auto
clrscr(); variables.
printf(“before swap=>a=%d\t b=%d\n”,a,b);
fun(&s,&t); 10.3. Write a program to calculate the area and perimeter
printf(“after swap =>a=%d\t b=%d”,a,b); of a circle using function call by reference method.
}
10.4. Write a program to illustrate the use of static

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 10 Functions Page 211

variable. 10.17. Write a program to illustrate the use of global


10.5. Write a program to display general message using variable.
function. 10.18. Write a program which read 2 integer numbers
10.6. Write a program to display welcome message using and find their sum, difference, multiplication and
function. division. Use a separate function for each of these
operations.
10.7. Write a program to calculate compound interest
using function. 10.19. Write a program which set smaller of two integers
to 0 using call by reference.
10.8. Write a program to add three numbers using
function. 10.20. Write a program to compute sum of the series
x+x^2/3!+x^3/5!+ ......... +x^n/(2n-1)!
10.9. Write a program to find sum of cosine series.
10.21. Write a program to find of the series
10.10. Write a program to find largest of three numbers x-(x^2)/2!+(x^3)/3!-(x^4)/4!+ ..........
using function.
10.22. Write a program to find sum of sine series.
10.11. Write a program to find largest of three numbers
using function returning a value. 10.23. Write a program to compute sum of series
u+y^3/2!+y^5/3!+ .......... +y^(2m-l)/m!.
10.12. Write a program to find the factorial of a number
non recursively using function. 10.24. Write a program to convert 2-digit octal number to
binary equivalent using fundtion.
10.13. Write a program to implement a^b where a and b
are integers. 10.25. Write a program to find standard deviation of n
numbers using function.
10.14. Write a program to implement the investment
equation v=p(l+r)^n using functions without 10.26. Write a program for base conversion using function.
arguments. 10.27. Write a program to find the primes their count,
10.15. Write a program for swapping of two numbers sum and average between 10 and 50 using function.
using call by refernce. 10.28. Write a program to find divisors of a positive
10.16. Write a program to find the sum of series-- 1 + 1/1! integer using nested functions.
+ 1/2! + 1/3! + 1/4! ....... 10.29. Write a program to display word equivalent of a
number (of 1-3 digits).

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

11
STRUCTURE AND UNION

11.1 INTRODUCTION

Now you are familiar with basic data types, such as int, float, double,
char etc available in C. You also know that when multiple elements of
same data type are logically grouped together then that group is called
array. For example, int array1[20] is a group of 20 elements. Each
member in this group is of int data type. Now the question is, can
multiple elements of different data types (say one integer element, two
float element) also be combined logically to form a group? Well, this is,
what structure is all about.

Figure 11.1 : Concept of Structure

Structure is basically a logical group of multiple items of different


data types such as int, float etc. Conceptual diagram of structure is
illustrated in figure. This figure illustrated a structure, named student.
It comprises of four elemenets ie Roll-No, Age, Religion and Fees.
Roll_No and Age are of int data type, while Religion and Fees are of
char and float data types, respectively.
Individual elements that constitute the structure are called
members. Thus structure illustrated in figure comprises of four members.

11.2 DECLARING A STRUCTURE

All the structures that you use in the program need to be defined first.
General format for defining the structure is given below.
struct structure_name

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 213

{ data_type_member_1 member_1;
data_type_member_2 member_2;
...................................
...................................
data_type_member_n member_n;
};

Here struct is a keyword, which is to be written as such. The


structure_name is the name that you wish to assign to the structure.
The data_type and member name have obvious meaning. Thus
structure, illustrated in figure 11.1 can be defined as follows:
struct student
{
int roll_no;
int age;
char religion;
float fees;
};

It must be noted that when you define a structure, you basically


define a derived data type. Now you need to have variables of this data
type. How do you define variables of structure data type is described
below.
Structure Containing Pointers
Members of a structure can be of any data type, including pointers. A
structure containing pointers is illustrated in the following example:
struct data
{
int roll;
char *name;
int marks;
};

11.3 STRUCTURE VARIABLES

After defining the structure, variables of this structure type can be


defined in the following format:
storage class struc_name variable_1, variable_2...variable_n;
Here storage class can either be static, automatic or external. But
it is optional. structure_name is name of that structure, which has
already been defined and the following variables of that type are to be
created. variable_1 to variable_n are the variables, which are to be
created.
For example, if three variables, say ram, shyam and geeta are to
be created of student type then following statement will have to be
included in the program:
struct student ram, shyam, geeta;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 214 Structure and Union Chapter 11

An alternate method for defining the variables along with the


definition of structure is also available in C language. This method is
described below.
struct struc_name
{
member definitions
}variable_1...variable_n;

e.g.

struct student
{
int roll-no;
int age;
char religion;
float fees;
}ram, shyam, geeta;

11.4 STRUCTURE INITIALIZATION

Like variables of basic data types (int, float, char, etc.), variable of
structure type can also be initialized at the time defined them. The
general format for initializing the variables of structure type, at the
time of their creation, is given below.
storage class struct struc_name variable_name = {value_1, value_2...value_n};
In this format, value_1 is assigned to the first member, value_2
is assigned to the second member and so on. Following is a valid
initialization statement:
struct student ram = {110,20,‘h’, 375.50};
When this statement will get executed, structure member
initialization for variable ram, will take place as follows:
roll_no = 110
age = 20
religiion = ‘h’
fees = 37.5.50

Similarly another variable shyam can be initialized as follows:


struct student shyam={111,21,’c’,150.75};

11.5 ACCESSING STRUCTURE MEMBERS

Once the structure has been defined and variable have been created.
Individual members for that variable can be accessed through dot
operator(.). Following is the general format for accessing any member
of structure variable:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 215

variable_name.member_name
e.g.
ram.roll_no shyam.roll_no
ram.age or shyam.age
ram.religion shyam.religion
ram.fees shyam.fees

You are now familiar with structures, their definition and methods
of declaring variables of structure type. So let’s write a simple program
to define a structure named employee. The structure have the following
elements in it:
1. employee number (int type)
2. name (character array of 50 elements)
3. age (int type)
4. expression (int type)
5. salary (float type)
Program should create a variable alok of this data type accept
member’s values from keyboard and print them.

/*****************************************************************************/
/* Program 11.1 : Illustrating Structure */
/*****************************************************************************/

#include <stdio.h>
struct employee
{
int empno;
char name[30];
int age;
int experience;
float salary;
}alok;
main()
{
printf(“This program use structure to record the employee details.”);
printf(“\nEnter Employee Number : ”);
scanf(“%i”,&alok.empno);
printf(“Enter Name : ”);
scanf(“%s”,&alok.name);
printf(“Enter age : ”);
scanf(“%d”,&alok.age);
printf(“Enter experience : ”);
scanf(“%i”,&alok.experience);
printf(“Enter salary : ”);
scanf(“%f”,&alok.salary);
printf(“\nEntered data are as below :”);
printf(“\nEmployee No : %i”,alok.empno);
printf(“\nName : %s”,alok.name);
printf(“\nAge : %i years”,alok.age);
printf(“\nExperience : %i years”,alok.experience);
printf(“\nSalary : %g”,alok.salary);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 216 Structure and Union Chapter 11

getch();
}
/*****************************************************************************/

 OUTPUT :
This program use structure to record the employee details.
Enter Employee Number : 1204
Enter Name : tarun
Enter age : 29
Enter experience : 4
Enter salary : 15000

Entered data are as below :


Employee No : 1204
Name : tarun
Age : 29 years
Experience : 4 years
Salary : 15000

11.6 STRUCTURE ASSIGNMENT

In C language, one structure variable can be assigned to another


structure variable, which is of the same type. For example, if man1 and
man2 are structure variables of employee type (structure mentioned
in program 1) then following structure assignment statement can be
written:
man2 = man1;
When this statement will get executed, values of all the members of
man1 will be assigned to the corresponding members of man2 variable.

11.7 FINDING SIZE OF THE STRUCTURE

Each variable that you operate upon in your C program, occupies some
space in memory. On most of the computers, integer occupies 2 bytes,
character occupies 1 byte, float occupies 4 bytes and double occupies
8 bytes. Often this occupied space is called the size of the variable of
length of the variable. Now the question is, what will be the size or
length of a structure variable? Well, its size can be calculated by adding
up the size of all its members. For example, any variable of employee
type (mentioned in program 1), will be of following size:
size of empno member (2 bytes) + size of name member (30 bytes)
+ size of age member(2 bytes) + size of experience member (2 bytes)
+ size of salary member (4 bytes). Thus the size of the variables, which
are of employee type, will be 2 + 30 + 2 + 2 + 4 i.e. 40 bytes.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 217

11.8 ARRAY OF STRUCTURES

To understand the requirement of array of structures, consider the


program 11.1 again. This program accepts data of one employee. Now
the question is, what do we do, if the data of 50 employees has to be
handled, within the program? Do we write 50 different variable names
after alok? Well, that’s not the way. To deal with 50 persons, an array
of 50 elements, which are of this structure type, need to be defined. For
example, below given statement creates an array of structure, which
has 50 elements in it:
struct employee pepole[50];
Here people is an array of 50 elements. Each element is a variable
of employee (which is a structure) type.

11.9 ACCESSING MEMBERS OF STRUCTURE ARRAY

Once an array of structure has been defined, members can always be


accessed in the following format:
array_name[index].member name
For example, following are few, valid member names of the array
defined above:
people[0].employee_number
people[0].name
people[0].age
people[0].experience
people[0];salary
people[1];name
people[2].salary
people[49].experience etc.

Now you are familiar with array of structures, so let’s apply this
concept for handling multiple data items of structure data type in a
program.
Say account department has to keep track of savings done by 30
employees of the organization. For this it maintains following record of
these employees.
1. employee_number
2. Name
3. Earnings
4. Expenditure
Let’s write a program that accepts the data of all the employees
and prints saving amount for them.

/*****************************************************************************/
/* Program 11.2 : Illustrating array of structure */
/*****************************************************************************/
#include <stdio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 218 Structure and Union Chapter 11

void readdata(int i);


void calculate(int i);

struct employee
{
int empno;
char name[30];
int earning;
int spend;
} emp[25];

void main()
{
int n;
clrscr();
printf(“This program keeps the record of saving of employee.”);
printf(“\nHow many employees are there ? ”);
scanf(“%d”,&n);
readdata(n);
calculate(n);
getch();
}

void readdata(int n)
{
int i;
printf(“Enter data of employee one by one.\n”);
for(i = 0; i < n; i++)
{
printf(“\nEnter employee Number : ”);
scanf(“%i”,&emp[i].empno);
printf(“Enter employee name : ”);
scanf(“%s”,emp[i].name);
printf(“Enter earning amount : ”);
scanf(“%i”,&emp[i].earning);
printf(“Enter Expenditure amount : ”);
scanf(“%i”,&emp[i].spend);
}
return;
}

void calculate(int n)
{
int i, diff;
printf(“\n\n\nSaving of each employee are as follows.”);
for (i = 0; i < n; i++)
{
diff = emp[i].earning - emp[i].spend;
printf(“\n\nEmployee Number : %i”,emp[i].empno);
printf(“\nName : %s”,emp[i].name);
printf(“\nEarning : %i”,emp[i].earning);
printf(“\nExpenditure : %i”,emp[i].spend);
printf(“\nSaving : %i”,diff);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 219

}
return;
}
/*****************************************************************************/

 OUTPUT :
This program keeps the record of saving of employee.
How many employees are there ? 3
Enter data of employee one by one.

Enter employee Number : 101


Enter employee name : ram
Enter earning amount : 12000
Enter Expenditure amount : 3230

Enter employee Number : 102


Enter employee name : rahim
Enter earning amount : 15000
Enter Expenditure amount : 4230

Enter employee Number : 103


Enter employee name : mahesh
Enter earning amount : 25000
Enter Expenditure amount : 6440

Saving of each employee are as follows.

Employee Number : 101


Name : ram
Earning : 12000
Expenditure : 3230
Saving : 8770

Employee Number : 102


Name : rahim
Earning : 15000
Expenditure : 4490
Saving : 10510

Employee Number : 103


Name : mahesh
Earning : 25000
Expenditure : 6440
Saving : 18560

11.10 STRUCTURE WITHIN STRUCTURE (NESTED STRUCTURE)

As mentioned earlier, members of any structure can be of any data


type (i.e. int, float, char, array, pointer etc.). Since structure is also

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 220 Structure and Union Chapter 11

a derived type hence the question is, can a structure member be of


structure data type? Well, the answer is yes. When a structure is placed
within another structure, as its member item, the resultant structure is
called nested structure.
To understand the concept of nested structures, consider two
structures. Say first data structure named ddmmyy consists of three
members i.e. day, month and year, which are of int data type. Such a
structure can be defined as follows:
struct ddmmyy
{
int day;
int month;
int year;
};

Say, second structure, named emp consists of four member i.e.


emp_no, name, salary, data_of_joining, which are of int, character
array of 50 elements, float and ddmmyy structure type. Such a structure
can be defined as follows:
struct emp
{
int day;
int month;
int year;
};

Say, second structure, named emp consists of four member i.e.


emp_no, name, salary, join_data, which are of int, character array of
50 elements, float and ddmmyy structure type. Such a structure can be
defined as follows:
struct emp
{ int emp_no;
char name[50];
float salary;
struct ddmmyy join_date
};

In is quite obvious that a variable, named person1 of emp type


can be defined as follows:
struct emp person1;

11.10.1 Accessing Members of Nested Structure


Members of nested data structures are accessed, using two dot operators.
For example, member of emp structure defined above can be accessed
as follows:
person1.emp_no
person1.name

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 221

person1.salary
person1.join_date.day
person1.join_date.month
person1.join_date.year

Since you can now access the members of nested structures hence
you can process them also. Now let’s write a program that accepts
data for 10 employees and prints the details of all those employees,
who joined the organization after 10/10/2002. Code of this program is
shown below.

/*****************************************************************************/
/* Program 11.3 : Nested Structure */
/*****************************************************************************/

#include <stdio.h>
#define size 3
struct ddmmyy
{
int day;
int month;
int year;
};
struct emp
{
int emp_no;
char name[50];
int salary;
struct ddmmyy doj;
} em[size];
void main()
{
int i;
clrscr();
for(i=0; i<size; i++)
{
printf(“\n\nEnter Employee Number : ”);
scanf(“%i”,&em[i].emp_no);
printf(“Enter Name of Employee ID %i : ”, em[i].emp_no);
scanf(“%s”,&em[i].name);
printf(“Enter salary of %s : ”, em[i].name);
scanf(“%i”,&em[i].salary);
printf(“Enter date of joining of %s : ”, em[i].name);
scanf(“%i”,&em[i].doj.day);
printf(“Enter month of joining of %s : ”, em[i].name);
scanf(“%i”,&em[i].doj.month);
printf(“Enter year of joining of %s : ”, em[i].name);
scanf(“%i”,&em[i].doj.year);
}
for(i=0; i<size; i++)
{
if(em[i].doj.year > 02)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 222 Structure and Union Chapter 11

goto prt;
else if(em[i].doj.year==2 && em[i].doj.month> 10)
goto prt;
else if (em[i].doj.year==2&&em[i].doj.month==10&&em[i].doj.day> 10)
goto prt;
else continue;
prt:
printf(“\n\nEmployee Number : %i”, em[i].emp_no);
printf(“\nName : %s”, em[i].name);
printf(“\nSalary : %i”, em[i].salary);
printf(“\nDate of joining : %i”,em[i].doj.day);
printf(“\nMonth of joining : %i”,em[i].doj.month);
printf(“\nYear of joining : %i”, em[i].doj.year);
}
getch();
}
/*****************************************************************************/

11.11 UNION

Union can be visualized as special type of structure, whose members


share common memory space. Thus at any given point of time, only
one member will remain present in the memory. So while working with
them, you will have to keep track of the member, which is currently
available in the memory. An attempt to access a member, which is not
presently available in the memory, will produce absurd results. General
format for defining the union is described below.
union union_name
{
member1;
member2;
...........
...........
membern;
};

Here union is the keyword, which is to be written as such, other


items have the same meaning as the items of any structure. Following
is a union definition:
union detail
{
int size;
char color[10];
float amount;
};

Variables of union data type can be declared as follows:


storage_class union_name variable_1, variable_2......, variable_n;
Here storage class is optional. The union_name is the name of

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 223

that union, which has already been defined in the program and the
following variables in the statement have be created, of this union type.
variable_1, variable_2 etc. are the names of variables, which have to
be created of mentioned union type. For example, if shirt and trouser
and the two variables, which have to be defined as detail (earlier defined
as union) type then following statement will have to be written:
union detail
{
int size;
char color[10];
float amount;
} shirt,trouser;

Individual members of any union can be accessed either through


dot operator or arrow operator.
To get familiar with the concept of unions, their usage and
behaviour, consider the following program. The program simply assigns
the value to different members of the union and then accesses them.
This program clearly illustrates that only one member of the union
remains in memory at a time and other members stay out. It also
illustrates that, if you try to access the value of those members, which
are not currently present in memory, you get meaningless results.

/*****************************************************************************/
/* Program 11.4 : Illustration of Union */
/*****************************************************************************/
#include<stdio.h>
#include<stdlib.h>
union detail
{ int size;
int color[10];
float amount;
};
main()
{
union detail shirt;
/* Section-1: Last accessed member in following section is amount so you will
get the right value of amount. Other two values will be wrong when displayed*/
shirt.size = 42;
strcpy(shirt.color,”Blue”);
shirt.amount = 500.55;
printf(“\n\nShirt size is %d”,shirt.size);
printf(“\nShirt color is %s”,shirt.color);
printf(“\nShirt Amount is %f”,shirt.amount);
/* Section-2: Last accessed member in following section is color so you will
get the right value of color. Other two values will be wrong, when displayed*/
shirt.size = 42;
shirt.amount = 500.55;
strcpy(shirt.color,”Blue”);
printf(“\n\nShirt size is %d”,shirt.size);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 224 Structure and Union Chapter 11

printf(“\nShirt color is %s”,shirt.color);


printf(“\nShirt Amount is %f”,shirt.amount);
/* Section-c: Last accessed member in following section is size so you will get
the right value of size. Other two values will be wrong, when displayed*/
shirt.amount = 500.55;
strcpy(shirt.color,”Blue”);
shirt.size = 42;
printf(“\n\nShirt size is %d”,shirt.size);
printf(“\nShirt color is %s”,shirt.color);
printf(“\nShirt Amount is %f”, shirt.amount);
getch();
}
/*****************************************************************************/

 OUTPUT :
Shirt size is 1800256
Shirt color is fF2
Shirt Amount is 500.55
Shirt size is 2771468
Shirt color is Blue
Shirt Amount is 42368989.07234
Shirt size is 42
Shirt color is fX4b
Shirt Amount is 42368080989.07234

 EXPLANATION :
If you observe, above program and its result closely, you will analyze the following
points:
1. Out of three given values, program displays only one correct value at a time. For
example, in the first three lines of the result, only the amount value is correct. Rest
of the values (i.e. size and color) are absurd.
2. You may note that the amount value is displayed correctly because the last
member of the union that you accessed before displaying the result was amount.
3. When the last member accessed was color then correct color was displayed, other
two values (i.e. size and amount) were absurd.
4. The same logic was true for size also.

From this observation we can conclude that member of the union,


which you access last, its value remains in memory, rest of the values
remain out.
Apart from the characteristic of union; that its members shares
common memory space, rest of the things are similar to that of structure
and it can be treated in the same manner. You can use union arrays,
pointers to unions or pass a union to a function in the same way as you
do for structures.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 225

REVIEW QUESTIONS a.emp_no, a.name, a.last_name);


getch();
}
11.1 What is a structure? Why is it used? Explain with
an example. 11.2 What is the output of the following code?
11.2 How is a structure name different from a structure /*to print elements of a structure array*/
#include<stdio.h>
variable? #include<conio.h>
11.3 Differentiate between a structure and a union. void main()
{
11.4 Explain, with an example, how a structure is struct employee
declared and initialized. {
11.5 Structure declaration reserves memory for the int emp_no;
} emprec[];
structure. Comment on this statement with valid clrscr();
justifications. emprec[0].emp_no=1;
emprec[1].emp_no=2;
11.6 Differentiate between a structure and an array.
printf(“\n%d %d”, emprec[0].emp_no, emprec[1].emp_
11.7 What is the purpose of the typedef feature? How is no);
this feature used in structure declaration? getch();
}
11.8 Explain with an example how structures are
initialized. 11.3 What is the output of the following code?
11.9 Is it possible to create an array of structures? #include<stdio.h>
Explain with the help of an example. main()
{
11.10 What is the need for a tag in a structure declaration? struct emp
Demonstrate with a segment of a program. {
char name[20);
11.11 Distinguish between an array and a structure. Give int age;
an example. float sal;
11.12 Explain why arrays and structures are used in };
struct emp e={“scott”};
programming and give syntax of accessing the printf(“\n %d %f”, e.age, e.sal);
elements of array and structure. }
11.13 How can the size of a structure be determined in C?
11.4 What is the output of the following code ?
11.14 Explain the following: (a) Nested structures. (b)
#include<stdio.h>
Pointer to a structure. (c) Array of structures. (d) struct trail
Array of pointers to structures. {
11.15 What is the difference between the two member int i;
char c;
access operators: . and ->. }
union trail1
{
struct trail srt;
PROGRAMMING OUTPUT QUIZ double d;
};
printf(“%d”, sizeof (union trail1));

11.1 Following program is to print the detail of an 11.5 What is the output of the following code ?
employee. What is the output of the program?
#include<stdio.h>
#include<stdio.h> main()
#include<conio.h> {
void main() struct student
{ {
struct employee char name[25];
{ struct date dob;
int emp_no; }stud;
char name[15];
char last_name[15]; struct date
}; {
employee a={115, “ABC”, “XYZ” }; int day, month, year;
printf(“\nThe details of employee: %d %s %s”, };

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 226 Structure and Union Chapter 11

} #include<stdio.h>
main()
11.6 Is the following code legal ? {
struct student
typedef struct srt
{
{
char name[20];
int num;
int age;
type *var;
};
}type
struct student stul={“Param”, 23};
struct student stu2=stul;
11.7 Is the following code legal? if(stul == stu2)
#include<stdio.h> printf(“The structures are equal”);
void main() else
{ printf(“The structures are not equal”);
typedef struct srt type; }
type variable;
struct srt 11.11 What is the output of the program?
{
#include<stdio.h>
int num;
struct student
type *b;
{
};
char class;
}
int age;
long int a;
11.8 Point out the error, if any, in the following code? };
#include<stdio.h> main()
void modify(struct emp*); {
struct student printf(“%d”, sizeof(struct student));
{ }
char name[20];
int age; 11.12 What would be the output of the following code ?
};
#include<stdio.h>
main()
main()
{
{
struct student stu={“Computer”, 35};
union student
modify(&e);
{
printf(“\n%s %d”, e.name, e.age);
int i;
}
char name[9];
void func(struct student *p)
};
{
union student s1={342, Ram};
strupr(p->name);
union student s2={0, Rahim};
p->age=p->age + 2;
}
}
11.13 What is the output of the following code?
11.9 What is output of the program?
#include<stdio.h>
#include<alloc.h>
main()
#include<string.h>
{
#include<stdio.h>
struct student
struct student
{
{
char name[30];
int len;
int age;
char name[1];
float percentage;
};
}
main()
{
struct student xyz;
char newname[]=“Computer”;
xyz.name=“Jhunjhunuwala”;
struct student *p=(struct student*)
xyz.age=25;
malloc(sizeof(struct student)-1 +
printf(“%s %d”, xyz.name, xyz.age);
strlen(newname)+1);
}
p->len=strlen(newname);
strcpy(p -> name, newname);
printf(“\n%d %s”, p -> len, p -> name);
11.14 What is the output of the following code?
} #include<stdio.h>
main()
11.10 What would be the output of the following program {
? struct

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 11 Structure and Union Page 227

{
11.18 What is the output of the following code ?
char name[20];
int age=30; #include<stdio.h>
}xyz; #include<conio.h>
static struct xyz={“Rahim”,‘C’}; typedef struct ST
printf(“%s %s”, xyz.name, xyz.age); {
} int sp, ST, sr;
}ST;
11.15 What is the output of the following code?
main()
#include<stdio.h> {
#include<conio.h> ST s;
main() s.ST=l000;
{ s.sp=2000;
struct s s.sr=3000;
{ clrscr();
int u; printf(“%d\n”, s.ST);
int v; printf(“%d\n”, s.sp);
}arr[4]={‘A’,‘M’,‘F’,‘R’,‘J’,‘W’,‘U’,‘H’}; printf(“%d\n”, s.sr);
struct s *p=arr; }
int i;
clrscr();
11.19 What is the output of the following code ?
for(i=0; i<4; i++)
{ #include<stdio.h>
p->u=p->v, ++p++->v; #include<conio.h>
printf(“%c %c\t”, arr[i].u, arr[i].v); struct ST
} {
} int i;
char *s;
11.16 What is the output of the following code ? };

#include<stdio.h> struct ST1


#include<conio.h> {
main() int j;
{ struct ST *t;
typedef struct };
{ void main()
int a, b, c, d; {
float e; struct ST1 *S;
}STR; clrscr();
S->j=200;
typedef union S->t->i=1;
{ printf(“j=%d\n”, S->j);
STR X; }
char a;
int b[12];
11.20 What is the output of the following code?
float c;
}UN; #include<stdio.h>
clrscr(); #include<conio.h>
printf(“sizeof STR=%d \nsizeof UN= %d\n”, typedef struct
sizeof(STR), sizeof(UN)); {
} int a;
int b[];
11.17 What is the output of the following code ? }s;

#include<stdio.h> typedef struct


main() {
{ int c;
struct ST int d[];
{ }T;
int no=15; const T c={5};
char name[]=”Lakshya”;
}; void main()
struct ST *s; {
printf(“%d”, s->no); clrscr();
printf(“%s”, s->name); printf(“c=%d\n”, c.c);
} printf(“d=%d\n”, c.d);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 228 Structure and Union Chapter 11

}
11.9. Write a program to illustrate the passing individual
11.21 What is the output of the following code ? structure to a function.
#include<stdio.h> 11.10. Write a program for passing structure to function
typedef enum e{a, b, c, a}d; by value. Here two times are entered in hh mm ss
void main() format and then added up
{
d f; 11.11. Write a program which check a valid date using
f=200; structure.
printf(“%d”, f);
11.12. Write a program to illustrate the use of a structure
}
pointer.
11.22 What is the output of the following code? 11.13. Write a program to illustrate the accessing structure
#include<stdio.h> using pointers.
#include<conio.h>
11.14. Write a program illustrating passing address of a
typedef int fun;
typedef struct fun structure variable.
{ 11.15. Write a program to illustrate passing structure to
fun a;
function by reference. Here seconds are entered as
fun b;
struct fun *c; input and converted to hh mm ss format
}st; 11.16. Write a program to add days to a valid date using
void main()
structure and function.
{
struct fun fl; 11.17. Write a program to which accept time in hh mm ss
struct fun f2; format and then add. Use returning structure from
clrscr();
a function.
printf(“%d %d %d %d”, sizeof(fl), sizeof(struct
fun), sizeof(st), sizeof(f2)); 11.18. Write a program to read employee records using
} array of pointers to structures and display them.
11.19. returning reference to a structure from a function
here rwo times are entered in hh mm ss format and
LAB PROGRAMS then added up
11.20. Write a program to prepare salary chart of daily
11.1. Write a program to maintain employee record and wages employees using array of structures.
print it. 11.21. Write a program to print names and numbers of
11.2. Write a program to determine size of a structure. employees who have 5 years or more experience and
salary less than Rs. 10,000 using array of structures
11.3. Write a program which copy a structure to another
(name, number, experience and salary)
and print these structures.
11.22. Write a program to sort an array of student records
11.4. Write a program which read an employee record
(containing name, rollno, marks, feepaid) based on
using nested structures and print it.
alphabetical ordering of name.
11.5. Write a program which accept student data and
11.23. passing an array of structures as argument to a
evaluate the performance.
function array of structures of students print the
11.6. Write a program to calculate the area of circle, name and roll number of the students who has
rectangle or triangle depending upon the user’s secured highest marks in each subject print the
choice using structures. name and roll number of the student who has
11.7. Write a program which read employee records using secured highest total marks
array of structures and display them. 11.24. Write a program to read 10 players records using
11.8. Write a program which search for a particular array of structures and print a team wise list
employee name and display the record using array containing names of players with their batting
of structures. Assuming identical names do not average.
exist. 11.25. Write a program to maintain record of countries
and capitals using structures

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

12
POINTERS

12.1 MEMORY ORGANIZATION

Memory is organized as a sequence of byte-sized (1 byte = 8 bits)


locations. These bytes are numbered beginning with a zero. The number
associated with a byte is known as its address or memory location. A
pointer is an entity which contains a memory address. Thus, a pointer
is a number which specifies a location in memory. The key concepts and
terminologies associated with memory organization are listed below:
(1) Each byte in memory is associated with a unique address
(2) An address is an integer having fixed number of bits, labelling a
byte in the memory.
(3) Addresses are positive integer values that range from zero to
some positive integer constant corresponding to the last location
in the memory.
(4) Every object (data or program code) that is loaded into memory
is associated with a valid range of addresses, that is, each variable
and each function in a program starts at a particular location,
and spans across consecutive addresses from that point onwards
depending on the size of the data item.
(5) The size of the data type referenced by the pointer is the number
of bytes that may be accessed directly by using that address
For example, if an address A represents a float location, then the
size of a is 2 bytes, beginning with the address A. The size of the data
type to which the pointer refers to is relevant only when the address
represents data rather than code.
Addressing Modes
Addressing is a technique used to access the contents of one or
more memory locations. Two types of addressing modes relevant to
ʇ NOTE
programming are relative addressing and absolute addressing. In the Most of the conventional
relative addressing mode, an address consists of two components, the computers use the relative
addressing mode to access
base (or segment) address and the offset address. The base address memory.
designates a specific segment of the memory and the offset specifies
the distance of the desired memory location from the beginning of that
segment, as illustrated below. An example of a relative address on an

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 230 Pointers Chapter 12

8086 machine (20 bit address bus) would be (in hexadecimal notation)
as follows:
Shift segment value 4 bits to Left.
108D:FFFE -----------> 108D0 + FFFE = 208CE
seg:Off (seg + Off = Absolute address)

All relative addresses are first translated into the corresponding


absolute addresses prior to physically accessing the memory. The use of
relative addressing simplifies the management of large memory.
Corresponding to a given physical address or absolute address, it
is possible to have different relative addresses. for example, all relative
addresses given below represent the same memory location.
Relative Addresses Absolute Address
0410 : 123C \
040F : 124C --> 00533C
040E : 125C /

ʇ NOTE
12.2 UNDERSTANDING POINTERS One of the disadvantages of
using pointers is that a program
A pointer is a variable that holds the address of another variable stored may crash if sufficient memory
is not available at runtime to
elsewhere in the computer memory. The pointer variable contains only
store pointers.
the address of the referenced variable not the value stored at that
address. Pointers are generally used to point to the variables, such as
array, functions, structures, unions, and the variables of any basic data
type. Some of the advantages of using pointers are as follows:
ʇ Pointers pass information back and forth between a function and
its reference point.
ʇ Pointer provide an alternate way to access individual elements
of the array
ʇ Pointers enable to pass arrays and strings as function arguments.
ʇ Pointers enable the programmers to return multiple data items
from a function via function arguments.
ʇ It enables references to functions. So with pointers, the
programmer can even pass functions as argument to another
function
ʇ Pointers is used to create complex data structures such as trees,
linked list, linked stack, linked queue, and graphs
ʇ Pointer are used for dynamic memory allocation of a variable.
The two basic operators used with pointers are the the address
of operator (&) and the indirection operator (*). The unary operator
& gives the address of an object whereas the unary operator * accesses
the object that the pointer points to.

12.3 DECLARING A POINTER VARIABLE

A pointer is a variable that store the address of another variable. You

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 231

can declare a pointer variable using the following syntax:


data_type *pointer_variable_name;
In the above syntax data_type specifies the type of the pointer
variable that you want to declare. The asterisk (*) symbol tells the
compiler that you are creating a pointer variable, and pointer_
variable_name specifies the name of the pointer variable. For example:
int *ptr; /* Declares a pointer variable ptr of integer data type */
float *temp; /* Declares a pointer variable temp of float data type */

Let’s create a C program to illustrate the pointer declaration.


Program 12.1 shows the code of this program:

/*****************************************************************************/
/* Program 12.1 : Declaring a Pointer Variable */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
void main()
{
int *ptr, b; /* Pointer declaration */
clrscr();
printf(“Enter any integer : ”);
scanf(“%d”, &b);
ptr = &b;
printf(“\nValue of b is %d.”, *ptr); /* Statement A */
printf(“\nPointer address of b is %d.”, ptr); /* Statement B */
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter any integer : 40

Value of a is 40.
Pointer address of a is -12.

 EXPLANATION :
In this program, the statement ptr=&b; specifies that the address of the b variable is
assigned to the pointer variable, ptr. Statement A displays the value of the b variable,
and the statement B displays the address of the ptr variable, which is -12 in our case.
This value can differ from computer to computer and time to time.

12.4 USING THE ADDRESS OF (&) OPERATOR

A computer uses memory to store the instructions of different programs


and the values of different variables. Since the memory is a sequential

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 232 Pointers Chapter 12

collection of storage cells, each cell has an address. When you declare a
variable, the operating system allocates memory according to the size
of the data type of that variable. In this memory location, the value of
the variable is stored. Consider the following statement:
int x = 230;

The above statement of the program requests the operating


system to allocate two bytes of space in memory. Since the data type of
the x variable is an integer, the operating system allocates two bytes of
ʇ NOTE
memory and stores 120 in that location. We have used frequently the &
x <--------- Variable name operator.
120 <------- Value of the variable
1030 <------- Address of the memory location

By using the address of (&) operator, you can determine the


address of a variable. The & operator is frequently used in the scanf()
function. Let’s consider an example to understand the concept better:
main()
{
int x = 149;
printf(“\nAddress of x: = %u”, & x); /* prints the address of variable x */
}

In the above example, the x variable contains the value, 149. The
printf() function prints the memory location of the x variable because
the x variable is preceded by the address of operator (&). Let’s create a
C program to understand the concept of the & operator. Program 12.2
shows the code of this program:

/*****************************************************************************/
/* Program 12.2 : Using the & Operator */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int var1, *ptr1;
float var2, *ptr2;
clrscr();
printf(“Enter the value for var1 : ”);
scanf(“%d”, &var1);
printf(“\nEnter the value for var2 : ”);
scanf(“%f”, &var2);
ptr1 = &var1;
ptr2 = &var2;
printf(“\nPointer address of var1 is %d and its value is %d.”, ptr1, *ptr1);
printf(“\nPointer address of var2 is %d and its value is %f.”, ptr2, *ptr2);
getch();
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 233

 OUTPUT :
Enter the value for var1 : 30
Enter the value for var2 : 42.45
The pointer address of var1 is -12 and its value is 30
The pointer address of var2 is -16 and its value is 45.000000

 EXPLANATION :
In this program, we have assigned values to an integer and a float variable and print
their addresses and values by using pointers. The ptr1=&var1; statement specifies that
the address of the var1 variable is assigned to the ptr1 pointer variable. Similarly, the
ptr2=var2; statement specifies that the address of the var2 variable is assigned to the
pointer variable, ptr2.

12.5 INITIALIZING A POINTER VARIABLE

While declaring pointer variables, you can explicitly specify which


variables you want the pointer variables to point to. Similar to the
initialization of other variables at the time of their declaration, you can
also initialize the pointer variables by assigning the addresses of other
variables to them. However, these variables must be declared in the
program. You can initialize a pointer variable by using the following
syntax:
data_type *pointer_variable_name = expression;
In the above syntax data_type can be any basic data type,
*pointer_variable_name is a pointer variable, and expression can be
a constant value or any variable containing a value. For example, let’s
consider the following code:
int num;
int *var = &num;

This code is equivalent to:


int num;
int *var;
var = &num;

When you initialize a pointer variable, you assign the reference


value to the memory location to which the pointer points, such as
var not the value being pointed, such as *var. You should note that
ʇ NOTE
at the time of declaring a pointer variable, the asterisk (*) symbol is The dereference operator also
used to indicate a pointer variable, it is not the dereference operator. uses the same *sign.
Therefore, you should not confuse with the use of the * symbol for two
different functions as the preceding code cannot be written as:
int num;
int *var;
*var = &num;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 234 Pointers Chapter 12

Program 12.3 shows how to initialize a pointer variable:

/*****************************************************************************/
/* Program 12.3 : Initializing a Pointer Variable */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
void main()
{
int b, *ptr1;
clrscr();
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
ptr1 = &b;
*ptr1=100; /* Pointer Initialization*/
printf(“\nValue of *ptr1 after initializing the pointer variable is %d.”, *ptr1);
printf(“\nValue of b after initializing the pointer variable is %d.”, b);
getch();
}
/*****************************************************************************/

 OUTPUT :
Enter the value of a : 30
Value of a after initializing the pointer variable is

 EXPLANATION :
In program 12.3, the ptr1=&b; statement specifies that the address of the b variable
is assigned to the pointer variable, ptr1. When ptr1 is initialized with the value 100,
the value of the b variable is changed in the memory location.

12.6 DEREFERENCING A POINTER

Pointer dereferencing refers to the process of referencing the values


of the variables by using pointers indirectly. To store the address of a
variable, you need to use the reference operator, &. You can retrieve
the address of a variable, say i, as follows:
int i = 10;
int *p = &i;

Now, if you want to use the value that the p pointer variable
points to, you can use the dereference operator * as follows:
printf(“value at p=”, *p);
In this statement, p itself is a variable (it holds the address of an
integer), so a pointer to it can be defined as:
int **q = &p;
You can directly access the value stored in the variable which it

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 235

points to by preceding the pointer variable with an asterisk (*) sign. In


this case, the * sign acts as the dereference operator, which is read as
value pointed by. Dereferencing a pointer is generally done in two steps.
In the first step, the address of the referenced variable is assigned to a
pointer and in the second step, the pointer points to the value stored in
the variable. For example, let’s consider the following code:
int a=100, *ptr;
ptr = &a; /* Step 1*/
*ptr = a; /* Step 2*/

In this code, the address of the a variable is assigned to the pointer


variable, ptr. Then the value of a is referenced by *ptr. The *ptr=a;
statement specifies that the ptr pointer variable accesses the value of
the a variable from the main memory. The process is shown in figure:

Figure 12.1 :

In figure 12.1, you can see that the ptr variable is stored at the
address, 10051, and references the address (10056) of the a variable
that contains the value, 100. Let’s create a C program to understand
the concept of dereferencing more clearly. Program 12.4 shows the code
of this program:

/*****************************************************************************/
/* Program 12.4 : Dereferencing a Pointer */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
void main()
{
int b, *ptr1;
clrscr();
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
ptr1=&b;
*ptr1=b;
printf(“\nAddress of %d is %d.”, b, ptr1);
printf(“\nValue of %d is %d.”, ptr1, *ptr1);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 236 Pointers Chapter 12

getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the value of b : 100
Address of 100 is -12.
Value of -12 is 100.

 EXPLANATION :
In program 12.4, the statement ptr1=&b; specifies that the address of the b variable is
assigned to ptr1 and the statement *ptr1=b; specifies that the ptr1 pointer variable
points to the memory location of the b variable to access its value.

12.7 PERFORMING OPERATION ON POINTER

Similar to other variables, you can use pointer variables in expressions.


The following statements are valid:
ʇ NOTE
k = *x * *y; /* it is same as (*x) * (*y); */
In the second statement, there
i = 3 - *y / *x; is a blank space between / and
*y = *y + 10; *. If there is no blank space then
As you know, the pointer variable holds the address of another it will be treated as beginning of
the comment lines.
variable. You can increment and decrement this address but cannot
multiply or divide it. However, you can multiply and divide the values
assigned to the pointer variables. Let’s create a C program to multiply
and divide the value assigned to the pointer variables. Program 12.5
shows the code of this program:

/*****************************************************************************/
/* Program 12.5 : Multiplying and Dividing Values within the Pointer */
/* Variables */
/*****************************************************************************/

#include <stdio.h>
#include <conio.h>
void main()
{
int a, b, mul;
int *ptr1, *ptr2;
float div;
clrscr();
printf(“Enter the value of a : ”);
scanf(“%d”, &a);
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
*ptr1 = a;
*ptr2 = b;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 237

mul=(*ptr1)*(*ptr2);
div=((float)*ptr1)/(*ptr2);
printf(“\nResult of multiplication is %d.”, mul);
printf(“\nResult of division is %0.2f.”, div);
getch();
}

/*****************************************************************************/

 OUTPUT :
Enter the value of a : 8
Enter the value of b : 3
Result of multiplication is 24.
Result of division is 2.67.

 EXPLANATION :
In program 12.5, you can see that the value of a is assigned to ptr1 and the value
of b is assigned to ptr2. Then, we have performed the multiplication and division
operations on these values.

The different operations that can be performed on the pointer


variables are:
(1) Assignment
(2) Arithmetic
(3) Comparison
Let’s discuss them one by one with the help of examples.

12.7.1 Assignment
The assignment operation can be performed on pointer variables in
different ways, such as assignment the address of other variables to a
pointer variable. For example:
int *ptr, a;
ptr = &a;

You can also assign one pointer variable to another only when
both variables point to the object of the same data type. For example:
float *ptr1, *ptr2;
ptr1=ptr2;

You can also assign a Null value to a pointer variable. For example:
int *ptr;
ptr = NULL;

12.7.2 Arithmetic
C allows you to add integers to pointers as well as subtract one pointer
from another. Arithmetic operation on pointers is somewhat different
from the arithmetic operations on regular integer data types. The

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 238 Pointers Chapter 12

arithmetic operation on pointers refers to the addition and subtraction


operations. You can add or subtract an integer value from a pointer
ʇ NOTE
variable. Both addition and subtraction have different behaviors When we increment a pointer,
according to the size of the data type to which they point. Shorthand its value is increased by the
length of the data type that it
operators can also be used with the pointers for arithmetic expressions, points to. this length is called
such as sum + = *p2. For example, suppose p1 is a pointer with a the scale factor.
current value of 2000. After the expression p1++, content of p1 will be
2002, not 2001. Each time p1 is incremented, it will point to the next
integer. Let’s consider the following examples of adding a number to a
pointer:
int i = 5, *j, *k;
j = &i;
j = j++;
j = ++j;
k = j+3;

Similarly, the following examples illustrate the subtraction of a


number from a pointer:
int i = 5, *j, *k;
j = &i;
j = j--;
j = j - 5;
k = --j;

Subtraction of one pointer variable from another can be performed


only when both variables point to elements of the same array.
You cannot perform the following operations on pointers:
1. Multiply a pointer with a constant
2. Add two pointers
3. Divide a pointer by a constant

12.7.3 Comparison
You can compare pointer variables by using relational operators, such
as <, >, <=, >=, and !=. You can compare two variables p1 and p2 by
using expressions, such as p1 > p2, p1 == p2, and p1 !=p2. Such
comparisons are useful when both pointer variables points to elements
of the same array.
Let’s create a C program to understand the different operations
that can be performed on pointer variables. Program 12.6 shows the
code of this application:

/*****************************************************************************/
/* Program 12.6 : Performing Operations on Pointer Variables */
/*****************************************************************************/

# include <stdio.h>
# include <conio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 239

void main()
{
int *ptr1, *ptr2;
static int arr[6] = {12, 14, 16, 18, 20, 22};
clrscr();
ptr1 = &arr[2];
ptr2 = &arr[4];
printf(“\nAddress of arr[2] is %d.”, ptr1);
printf(“\nValue of arr[2] is %d.”, *ptr1);
ptr1 = ptr1+3;
printf(“\nAfter addition of 3, address of ptr1 is %d.”, ptr1);
printf(“\nNow value pointed by ptr1 is %d.”, *ptr1);
if(ptr1<ptr2)
printf(“\nAddress %d is less than the address %d.”, ptr1, ptr2);
else
printf(“\nAddress %d is greater than or equals to the address %d.”, ptr1, ptr2);
getch();
}

/*****************************************************************************/

 OUTPUT :
Address of arr[2] is 174.
Value of arr{2} is 16.
After addition of 3, address of ptr1 is 180.
Now value pointed by ptr1 is 22.
Address 180 is greater than or equals to the address 178.

 EXPLANATION :
In this program, we have declared two pointer variables, ptr1 and ptr2, and an array
of integer data type. The elements of this array are assigned to the pointer variables.
ptr1 and ptr2. After printing the address and value of arr[2], we have incremented
ptr1 by 3 and again printed the address and value of ptr1. Finally, we compare the
address of ptr1 with the address of ptr2.

Rules for Pointer Operation


Let us now summarize the rules for pointer operations:
(1) A pointer variable can be assigned the address of another variable
of the same type.
(2) A pointer variable can be assigned the value of another pointer
variable of the same type.
(3) A pointer variable can be compared with another pointer variable
of the same type using relational operators.
(4) An integer value can be added or subtracted from a pointer
variable.
(5) A pointer variable cannot be multiplied by a constant.
(6) A pointer variable cannot be added to another pointer variable.
(7) A pointer variable can be initialized with a NULL (or 0) value.
(8) Prefix or postfix increment and decrement operators can be

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 240 Pointers Chapter 12

applied on a pointer variable.

12.8 NULL AND VOID POINTER

Void Pointer
A void pointer is a special type of pointer. It can point to any data
type, from an integer value or a float to a string of characters. Its sole
limitation is that the pointed data cannot be referenced directly (the
asterisk * operator cannot be used on them) since its length is always
undetermined. Therefore, type casting or assignment must be used to
turn the void pointer to a pointer of a concrete data type to which we
can refer.

/*****************************************************************************/
/* Program 12.7 : Void Pointer */
/*****************************************************************************/

#include <stdio.h>
int main()
{
int a = 8;
double pi = 3.1415;
void *vp;
vp = &a;
printf(“\nThis program demonstrate the use of VOID pointer.”);
printf(“\na = %d”, *((int *)vp));
vp = &pi;
printf(“\npi = %f”, *((double *)vp));
getch();
return 0;
}

/*****************************************************************************/

 OUTPUT :
This program demonstrate the use of VOID pointer.
a = 8
pi = 3.141500

Null Pointer
Null pointers are used in situations where one of the pointers in
ʇ NOTE
the program points to different locations at different times. In such A NULL pointer does not point
situations it is always better to set it to a null pointer when it doesn’t to any valid memory address.
point anywhere valid, and to test to see if it’s a null pointer before
using it.
Null pointer may be declare using the predefined constant NULL,

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 241

which is defined in several standard header files including <stdio.h>,


<stdlib.h>, and <string.h>. After including any of these files in your
program just write,
int *ptr = NULL;
You can always check whether a given pointer variable stores
ʇ NOTE
address of some variable or contains a NULL by writing, It is a logical error to dereference
if (ptr == NULL) a null pointer.
{
statement_block;
}

You may also initialize a pointer as a null pointer by using a


constant 0, as shown below.
int ptr,
 PROGRAMMING TIPS
ptr = 0;
A function that returns pointer
values can return a null pointer
This is a valid statement in C, as even NULL which is a preprocessor when it is unable to perform its
macro typically has the value, or replacement text, 0. However, to avoid task.
ambiguity it is always better to use NULL to declare a null pointer.

12.9 WORKING WITH FUNCTIONS AND POINTERS

We have already seen call by value method of passing parameters to


a function. Using call by value method it is impossible to modify the
ʇ NOTE
actual parameter in the call when you pass them to function. Passing the pointer to a
Pointer provide a mechanism to modify data declared in one function avoids the overhead of
function using code written in another function. In other words : if copying data from one function
to another.
data is declared in functn1() and we want to write code in functn2()
that modifies the data in functn1(), then we must pass the address of
the variables we want to change.
The calling function sends the address of the variables and the
called function must declare those incoming arguments as pointers. In
order to modify the variable sent by the caller, the called function must
dereference the pointer that were passed to it. Hence to use pointers for
passing arguments to a function, you must do the following:
(1) Declare the function parameters as pointers
(2) Use the dereferenced in the function body
(3) Pass the address as the actual argument when the function is
called
Let’s create a C program to understand the use of call by reference.
Program 8 shows the code of this program:

/*****************************************************************************/
/* Program 12.8 : Passing a Value by using Call by Reference */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 242 Pointers Chapter 12

void swap(int *i, int *j)


{
int temp;
temp = *i;
*i = *j;
*j = temp;
}
void main()
{
int x, y;
clrscr();
printf(“Enter the Two numbers : ”);
scanf(“%d%d”, &x, &y);
printf(“\n\nYou Entered :\nx = %d, y = %d”, x, y);
swap(&x, &y);
printf(“\nAfter swapping :\nx = %d, y = %d”, x, y);
getch();
}
/*****************************************************************************/

 OUTPUT :
Enter the Two numbers : 45 78
You Entered :
x = 45, y = 78
After swapping :
x = 78, y = 45

 EXPLANATION :
In program 12.8, you can see that the values of x and y are exchanged by using their
addresses stored in i and j.

12.10 WORKING WITH ARRAYS AND POINTERS

As you know that an array is a set of homogeneous elements, which


means in an array all the elements are stored adjacent to one another.
Therefore, you can access an array by using a single pointer.
For example:
ʇ NOTE
int arr[5] = {10,15,20,25,30}
The array name without any
The first element of the array that we have created in the preceding subscript returns the base
address that means the memory
code is arr[0] and the last element is arr[4]. The array elements and location of its first element.
their values are represented with their addresses, which are shown as
follows:
Variable name arr[0] arr[1] arr[2] arr[3] arr[4]
Value 10 15 20 25 30
Address 1004 1006 1008 1010 1012
arr is equivalent to &arr[0]
arr+0 is equivalent to &arr[0]
arr+1 is equivalent to &arr[1]

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 243

arr+i is equivalent to &arr[i]

Note that an increment in the address gives the address of the


next element and therefore,
*arr is equivalent to arr[0]
*(arr+i) is equivalent to arr[i]

Consider a two-dimensional array int aa[i][j]. Therefore, the


expression
arr is equivalent to &arr[0][0] = &arr[0]
aa+i is equivalent to &aa[i][0] = &aa[i]
*(aa+i) is equivalent to aa[i][0] = aa[i]
aa[i]+j is equivalent to &aa[i][j]
*(aa[i]+j) is equivalent to aa[i][j]
*(*(aa+i)+j) is equivalent to aa[i][j]

Let’s create a C program to find the largest value of one-


dimensional integer array using pointers. Program 12.9 shows the code
of this program:

/*****************************************************************************/
/* Program 12.9 : Finding Largest of One-dimensional Array using Pointers */
/*****************************************************************************/

#include<stdio.h>
#include<conio.h>
main() {
int a[20], i, n, large, p=0;
int *b;
clrscr();
printf(“\nInput array size : ”);
scanf(“%d”,&n);
printf(“\nInput %d array elements :\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
b=a;
large = 0;
printf(“\nEntered array is :\n”);
for(i=0;i<n;i++,b++)
{
printf(“%d\t”,*b);
if(*b>large)
{
large = *b;
p=i+1;
}
}
printf(“\nLargest element is %d at position %d.”,large,p);
getch();
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 244 Pointers Chapter 12

 OUTPUT :
Input array size : 10
Input 10 array elements :
123 654 789 741 258 963 147 852 369 520
Entered array is
123 654 789 741 258 963 147 852 369 520
Largest element is 963 at position 6.

 EXPLANATION :
In program 10, you can se that we have declared an array of size 20 and a pointer
variable, b. When you enter the values of the array elements, all the values are passed
through the for loop to check for the largest value.

12.11 POINTERS TO STRING

String represents a set of characters and known as a character array.


Therefore, pointer to string is same as pointer to integer array. When
a pointer is used with a string, the programmer needs to use the string
terminator because no such criteria exist for numeric array.
Let’s define a string variable n as follows:
char n[] = “books”;
variable name n[0] n[1] n[2] n[3] n[4]
value b o o k s
Address 2001 2002 2003 2004 2005

Let’s create a C program to use the pointer with a character


array. Program 12.10 shows the code of this program:

/*****************************************************************************/
/* Program 12.10 : Creating Pointer to Char Array */
/*****************************************************************************/

#include<stdio.h>
main()
{
char a[50];
char *p = a;
int i;
clrscr();
printf(“Enter any string : ”);
gets(a);
printf(“Address of character array and pointer variable are :\n”);
printf(“a = %u and p = %u\n”, a, p);
printf(“\na[i]\t&a[i]\n”);
for(i=0;*p!=’\0’;i++,p++)
printf(“\n%c\t%u”,a[i],p);
getch();
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 245

/*****************************************************************************/

 OUTPUT :
Enter any string : kitabwala
a = 65476 and b = 65476
a[i] &a[i]
k 65476
i 65477
t 65478
a 65479
b 65480
w 65481
a 65482
l 65483
a 65484

From the output, it is clear that one byte is needed to store one
character. The for loop in program 12.10 is same as the following code:
for(i=0;*p!=’\0’;i++)
{
printf(“\n%c\t%u”,a[i],p);
p++;
}

However, you can also write the above code as following:


for(i=0;a[i]!’\0’;i++)
{
printf(“\n%c\t%u”,a[i],&a[i]);
i++;
}

The loop execution continues until string terminator is encountered.


Let’s create another C program to find the length of a string by using
pointers. Program 12.11 shows the code of this application:

/*****************************************************************************/
/* Program 12.11 : Calculating Length of a String using Pointers */
/*****************************************************************************/

#include<stdio.h>
stlength(char *s);
main()
{
char st[100];
clrscr();
printf(“Enter any string : ”);
gets(st);
printf(“\n\nGiven string : %s”, st);
printf(“\nIts length is %d.”, stlength(st));
getch();

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 246 Pointers Chapter 12

}
stlength(char *s)
{
int len = 0;
while(*s != ‘\0’)
{
len++;
s++ ;
}
return(len);
}

/*****************************************************************************/

 OUTPUT :
Enter any String : encyclopedia

Given string : encyclopedia


Its length = 12.

 EXPLANATION :
In program 12.11, we have calculated the length of the string by using pointers.
However, the result is similar to the strlen() function that is used to find out the
length of a string.

In the next C program, the purpose is same as string function


strcmp(), which is used to compare two strings. The strings are compared
character by character. The compiler checks the ASCII values and if
the value is same then it proceeds ahead; otherwise it terminates the
execution. This implies that if any character does not match with the
corresponding character of another string, the break statement causes
the transfer of control to the end of the loop. Program 12.12 shows the
code to compare two strings:

/*****************************************************************************/
/* Program 12.12 : Comparing Two Strings using Pointers */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
char a[50],b[50];
char *p,*q;
int i,j,status=0;
p = a;
q = b;
clrscr();
printf(“\nInput two strings : \n”);
gets(a);
gets(b);
for(;*p!=’\0’ || *q!=’\0’;*p++,*q++)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 247

if(*p!=*q)
{
printf(“\nGiven strings are different”);
status = 1;
break;
}
if(status==0)
printf(“\nGiven strings are same.”);
getch();
}

/*****************************************************************************/

 OUTPUT :
Run1
Input two strings :
computer
computer
Given strings are same.

Run2
Input two strings:
Keyboard
KeyBoard
Given strings are different.

 EXPLANATION :
In case if you want to ignore the lower case and the upper case distinction, the
difference between the corresponding uppercase and lowercase values is 32; therefore,
A+32=a or a-A=32.

Let’s create a C program to convert characters of a string in


uppercase by using pointers. Program 12.13 shows the code for this
program:

/*****************************************************************************/
/* Program 12.13 : Converting a String in Uppercase */
/*****************************************************************************/
#include<stdio.h>
void main()
{
char a[50];
char *p;
int i;
p = a;
clrscr();
printf(“\nInput a string : ”);
gets(a);
printf(“\nEntered string : %s”, a);
printf(“\nEntered string in UPPERCASE is : ”);
for(;*p!=’0’;*p++)

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 248 Pointers Chapter 12

{
if(*p>=’a’ && *p<=’z’)
*p-=32;
}
puts(a);
getch();
}
/*****************************************************************************/

 OUTPUT :
Input a string : computer engineering

Entered string : computer engineering


Entered string in UPPERCASE is : COMPUTER ENGINEERING

Next, let’s create a C program to combine two strings and store


the result in a third string by using pointers. Program 12.14 shows the
code of this program:

/*****************************************************************************/
/* Program 12.14 : Combining Strings using Pointers */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
char a[50],b[50],c[100];
char *p,*q;
int i,j;
p = a;
q = b;
clrscr();
printf(“Input two strings :\n”);
gets(a);
gets(b);
for(i=0;*p!=‘\0’;*p++,i++)
c[i]=*p;
for(j=0;*q!=‘\0’;*q++,j++,i++)
c[i]=*q;
c[i]=‘\0’;
puts(“Entered strings are :”);
puts(a);
puts(b);
printf(“Entered strings are :”);
puts(a);
puts(b);
printf(“\nAfter combining : ”);
puts(c)
getch();
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 249

 OUTPUT :
Input two strings :
computer
science
Entered strings are :
computer
science
After combining : computerscience

In program 12.14, the program code:


for(i=0;*p!=’0’;*p++,i++)
c[i]=*p;
for(j=0;*q!=’\0’;*q++,j++,i++)
c[i]=*q;

can also be written as:


for(i=0;*p!=’\0’;c[i]=*p++,i++);
for(j=0;*q!=’0’;c[i]=*q++,j++,i++);

In the above code, note that we have initialized c[i] in the


declaration of the for loop itself. Next, let’s create a C program to find
the total number of white spaces from a given string. Program 12.15
shows the code of this program:

/*****************************************************************************/
/* Program 12.15 : Finding Occurrences of White Spaces in a String */
/*****************************************************************************/

#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
char *ch;
int i=0;
clrscr();
printf(“\Enter a string : “);
gets(ch);
while(*ch!=’\0)
{
if(*ch==’ ‘)
i++;
*ch++;
}
printf(“\The total number of white spaces are : %d”,i);
getch();
}

/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 250 Pointers Chapter 12

 OUTPUT :
Enter a string : hello user, how r u?
The total number of white spaces are : 4

 EXPLANATION :
In program 12.15, you can observe that the while loop executes until the escape
symbol is found in the string to terminate the string.

12.12 DIFFERENCE BETWEEN ARRAY NAME AND POINTER

When memory is allocated for an array, its base address is fixed and it
cannot be changed during program execution. In other words, an array
ʇ NOTE
name is an address constant. Therefore, its value cannot be changed. An lvalue is an expression to
To ensure that the address of the array does not get changed even which a value can be assigned.
An rvalue can be defined as an
inadvertently, C does not allow array names to be used as an lvalue. expression that can be assign to
Hence, array names cannot appear on the left side of the assignment an lvalue. The lvalue expression
operator. is located on the left side of an
assignment operator, whereas
However, you may declare a pointer variable of appropriate type an rvalue is located on the right
that points to the first element of the array and use it as lvalue. The side of an assignment statement.
following code gives an error as the array name is being used as an
lvalue for the ++ operator.
main()
{
int array1[10], i;
for(i=0;i<10;i++)
{
*array1 = 0;
array1++; /* Error */
}
for(i = 0; i < 10;i++)
printf(“\n %d”, *(array1+i));
}

The following code shows the correct way of doing the same thing.
main()
{
int array1[10], i, *parray1;
parray1 = array1;
for(i = 0; i < 10;i++)
{
*parray1 = 0;
parray1++;
}
for(i = 0; i < 10;i++)
printf(“\n%d”, *(array1+i));
}

Second thing to remember is that an array cannot be assigned to


another array. This is because an array name cannot be used as the

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 251

lvalue.
int array1[] = {31, 42, 53, 41, 98};
int array2[5];
array2 = array1; /* Error */

But, one pointer variable can be assigned to another pointer


variable of the same type. Therefore, the following statements are valid
in C.
int array1[] = {31, 42, 53, 41, 98};
int *ptr1, *ptr2;
ptr1 = array1;
ptr2 = ptr1;

When we write ptr2 = ptr1, we are not copying the data pointed
to. Rather, we are just making two pointers point to the same location.
This is shown in following figure.

Figure 12.2 :

Third point of difference lies with the return value of the address
operator. The address operator returns the address of the operand.
But when an address operator is applied to an array name, it gives the
same value as the array reference without the operator. Therefore, arr
and &arr gives the same value. However, this is not true for a pointer
variable.
Last but not the least, the sizeof operator when applied to an
array name returns the number of bytes allocated for the array. But
in case of a pointer variable, the sizeof operator returns the number of
bytes used for the pointer variable (machine dependent). Consider the
the following code which illustrates this concept.

/*****************************************************************************/
/* Program 12.16 : Use of sizeof function with pointer
/*****************************************************************************/
main()
{
int arr[]={1,2,3,4,5};
int *ptr;

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 252 Pointers Chapter 12

ptr=arr;
printf(“\n Size of array = %d”, sizeof(arr));
printf(“\nSize of pointer variable = %d”,sizeof(ptr));
}
/*****************************************************************************/

 OUTPUT :
Size of array = 10
Size of pointer variable = 2

12.13 POINTERS AND TWO DIMENSIONAL ARRAY

You are already familiar with the concept of pointers and their
relationship with one dimensional array. You know that the name of
one dimensional array (say b) always points to the first element of the
array. Applying pointer arithmetic i.e. adding 1 to it (i.e. b+1) yields
the address of the second element of the array and so on.
Now the question is, can a relationship between pointers and two
dimensional array be established? Well, the answer is yes. Since two
dimensional array is a group of multiple single dimensional array hence
pointer arithmetic can be devised to point to the second row, third row
etc. of the two dimensional array and all the elements in them. Once
you have correct pointers in hand, you can apply indirection operator
on them to get the values stored in them.
To understand the relationship between pointers and two
dimensional arrays, consider the following definition of two dimensional
array.
int p[3][4];
Using pointers, this definition can be rewritten as follows:
int (*p)[4];
In this declaration, following things will hold good:
(1) p will point to the first row of four elements.
(2) (p+1) will point to the second row of four elements.
(3) (p+2) will point to the third row of four elements.
Now the question is, what points to the elements of the rows?
Well, to understand this, recall that p is a pointer to the first array.
Thus *(p) will be an address. Add 0 to this and you get *(p)+0 i.e.
*(p). This will give the address of the first element of the first row.
Similarly if you add 1 to *(p) i.e. (*(p)+1) will give the address of the
second element of the first row. Thus pointers to the elements of the
first row can be obtained as follow.
(1) (*(p)) points to be first element of the first row.
(2) (*(p)+1) points to be second element of the first row.
(3) (*(p)+2) points to be third element of the first row.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 253

(4) (*(p)+3) points to be fourth element of the first row.

Figure 12.3 :

Now for the elements of second row: The pointer (p+1) points to
the second row of 4 elements. Thus *(p+1) will be an address. Using
pointer arithmetic, add 1 to this i.e. (*(p+1)+1) will point to the second
element of the first row. Thus pointers to the elements of second row
can be obtained as follow:
(1) (*(p+1)) will point to the first element of the second row.
(2) (*(p+1)+1) will point to the second element of the second row.
(3) (*(p+1)+2) will point to the third element of the second row.
(4) (*(p+1)+3) will point to the forth element of the second row.
Similarly performing pointer arithmetic on (p+2) i.e. pointer to
the third row, will yield the pointers to the elements of third row:
(1) (*(p+2)) will point to the first element of the third row.
(2) (*(p+2)+1) will point to the second element of the third row.
(3) (*(p+2)+2) will point to the third element of the third row.
(4) (*(p+2)+3) will point to the fourth element of the third row.
Now, since you have the pointers, Indirection operator can be
applied on them to get the value contained in the element, to which,
they point to. This is illustrated and summarized below.
(1) *(*(p)) will give the value contained in first element of the first
row.
(2) *(*(p)+1) will give the value contained in second element of the
first row.
(3) *(*(p)+2) will give the value contained in third element of the
first row.
(4) *(*(p)+3) will give the value contained in fourth element of the

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 254 Pointers Chapter 12

first row.
(5) *(*(p+1)) will give the value contained in first element of the
second row.
(6) *(*(p+1)+1) will give the value contained in second element of
the second row.
(7) *(*(p+1)+2) will give the value contained in third element of the
second row.
(8) *(*(p+1)+3) will give the value contained in fourth element of
the second row.
(9) *(*(p+2)) will give the value contained in first element of the
third row.
(10) *(*(p+2)+1) will give the value contained in second element of
third row.
(11) *(*(p+2)+2) will give the value contained in third element of
the third row.
(12) *(*(p+2)+3) will give the value contained in fourth element of
the third row.
This pointer arithmetic has been applied in the following program.
This program, declares an array of three row and four columns using
pointer. The elements of this array are initialized using pointer first
later their address and contents are printed, using pointers only.

/*****************************************************************************/
/* Program 12.17 : Illustrating Pointer arithmetic in 2 dimensional Array /
/*****************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define row 3
#define col 4
main()
{
int(*p)[4];
int i,j;
int sum = 10;
clrscr();
p = (int*)malloc(row * col * sizeof(int));
for(i=0;i<3;i++)
for(j=0;j<4;j++)
{
*(*(p+i)+j)=sum;
sum = sum + 10;
}
for(i=0;i<3;i++)
{
printf(“\n\nAddress and the contents of the elements of row %d :”, i);
for(j=0;j<4;j++)
{
printf(“\nAddress of element %d is %x. “,j,(*(p+i)+j));
printf(“Value of the element %i is %d.”,j,*(*(p+i)+j));

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 255

}
}
getch();
}
/*****************************************************************************/

 OUTPUT :
Address and the contents of the elements of row 0 :
Address of element 0 is 612. Value of the element 0 is 10.
Address of element 1 is 614. Value of the element 1 is 20.
Address of element 2 is 616. Value of the element 2 is 30.
Address of element 3 is 618. Value of the element 3 is 40.

Address and the contents of the elements of row 1 :


Address of element 0 is 61a. Value of the element 0 is 50.
Address of element 1 is 61c. Value of the element 1 is 60.
Address of element 2 is 61e. Value of the element 2 is 70.
Address of element 3 is 620. Value of the element 3 is 80.

Address and the contents of the elements of row 2 :


Address of element 0 is 622. Value of the element 0 is 90.
Address of element 1 is 624. Value of the element 1 is 100.
Address of element 2 is 626. Value of the element 2 is 110.
Address of element 3 is 628. Value of the element 3 is 120.

To get more familiar with the usage of pointer for accessing two
dimensional array let’s consider another program. Let there be an array
of 3 rows and 3 columns. Accept the values of its elements from the
keyboard. Copy its rows into columns of another array (transpose)
Print the new array. Make use of pointers for declaring the processing
functions. Code of this programme is given below :

/*****************************************************************************/
/* Program 12.18 : Illustrating Pointer arithmetic in 2 dimensional Array */
/*****************************************************************************/

#include<stdio.h>
main()
{
int (*mat1)[3];
int (*mat2)[3];
int i,j;
clrscr();
puts(“This program calculate the transpose of 3x3 Matrix.”);
mat1=(int*) malloc(3*4*sizeof(int));
for(i=0;i<3;i++)
{
printf(“Enter 3 elements for row %d : ”,i+1);
for(j = 0; j < 3; j++)
scanf(“%d”,(*(mat1+i)+j));
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 256 Pointers Chapter 12

printf(“\n\nGiven 3 X 3 Matrix is :\n”);


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d\t”,*(*(mat1+i)+j));
printf(“\n”);
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
*(*(mat2+j)+i)=*(*(mat1+i)+j);
printf(“\nTranspose of given matrix is :\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d\t”,*(*(mat2+i)+j));
printf(“\n”);
}
getch();
}

/*****************************************************************************/

 OUTPUT :
This program calculate the transpose of 3x3 Matrix.
Enter 3 elements for row 1 : 23 56 78
Enter 3 elements for row 2 : 12 45 89
Enter 3 elements for row 3 : 39 61 92
Given 3 X 3 Matrix is :
23 56 78
12 45 89
39 61 92

Transpose of given matrix is :


23 12 39
56 45 61
78 89 92

12.14 ARRAY OF POINTERS

Recall that in the previous section we declared a two dimensional array


as pointer to a group of one dimensional arrays. Using another method,
the same two dimensional array can be defined as one dimensional array
of pointers. Each element of this array would point to the beginning of
separate one dimensional array (that put together would constitute two
dimensional array). To understand the concept, refer figure 12.5.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 257

Figure 12.4 : Array of Pointers

Say we wish to work with two dimensional array of 3 rows and 4


columns, as illustrated in figure, which is of int type. Then instead of
defining the array as int a[3][4] or int (*a)[4], it can be defined as
follows:
int *a[3];
The general format for defining an array of pointer is
data_type *array_name[dimension];
Now, here in this definition, following points have to be noted:
(1) In *array_name, *a is not written, within bracket, because if you
do so, it will declare a pointer to a group of contiguous array
blanks.
(2) Dimension of pointer array is one less than that, in which data
is to be stored.
(3) The first element of the pointer array will point to the beginning
of the first row of two dimensional array. Second element will
point to be beginning of second row and so on.
(4) Since *a[3] is a pointer array hence a[0] will be the first pointer,
pointing to the first row of two dimensional array. Similarly a[1]
and a[2] will point to the beginning of second and third row.
(5) Since you have the pointer (say a[1]), pointing to the beginning
of row hence, adding a number (say2) to it will yield another
pointer (i.e. (a[1]+2)), which will point to the corresponding
element of that row (i.e. third element of second row).
(6) As usual, using indirection operator (i.e.*) on any pointer (say
(a[1]+2)) will refer to the contents of the element, to which it
points to (i.e. third element of second row).
(7) You can say that the elements of pointer array are pointers to
pointers.
Now you are familiar with the two methods, which make use of
pointers, for declaring the arrays, so a summary of their comparison is
given in the following table:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 258 Pointers Chapter 12

TABLE 12.1 : Comparison between Pointer variable and pointer array Method

SN Subject Pointer Variable Method Pointer Array Method


1. Declaration data type (* pointer variable)[column Data type *Array[row value] e.g.
value] e.g. int(*x)[6] *x[5]

2. Mentioning In declaration you mention the In declaration you mention the


rows/col number of column in each row. number of rows in the array.
3. Accessing the Third element of the second will be Third element of the second row
elements accessed as *(*(x+1)+2). will get accessed as *(x[1]+2)

To get familiar with the usage of pointer arrays, let’s consider


a programs, using pointer array, which accepts 5 names from the
keyboard, sorts them in ascending order and prints them.

/*****************************************************************************/
/* Program 12.19 : Illustrating Pointer Array */
/*****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#define size 5
void printarr(char *x[]);
void sortarr(char *x[]);
main()
{
int i;
char *x[size];
clrscr();
puts(“This program sort the 5 given name. Name should not contain space.\n”);
for(i =0;i<size;i++)
{
x[i] = (char *)malloc(15*sizeof(char));
printf(“Enter %ith Name : ”,i+1);
scanf(“%s”,x[i]);
}
printf(“\n\nUnsorted name list is as follows :”);
printarr(x);
printf(“\n\nSorted name list is as follows :”);
sortarr(x);
printarr(x);
getch();
}

void printarr(char *x[])


{
int i=0;
for(i=0;i<size;i++)
printf(“\n%ith Name : %s”,i+1,x[i]);
}

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 259

void sortarr(char *x[])


{
int i,j;
char *temp;
for(j=0;j<size-1;j++)
{
for(i=0;i<size-1;i++)
if(strcmp(x[i+1],x[i])<0)
{
temp=x[i+1];
x[i+1]=x[i];
x[i]=temp;
}
}
return;
}

/*****************************************************************************/

 OUTPUT :
This program sort the 5 given name. Name should not contain space.

Enter 1th Name : mahesh


Enter 2th Name : arvind
Enter 3th Name : lakshya
Enter 4th Name : varsha
Enter 5th Name : mahesh

Unsorted name list is as follows :


1th Name : ekta
2th Name : chandra
3th Name : bindu
4th Name : deepak
5th Name : anmol

Sorted name list is as follows :


1th Name : anmol
2th Name : bindu
3th Name : chandra
4th Name : deepak
5th Name : ekta

12.15 POINTERS TO FUNCTION

We have seen earlier that arguments of a function (called formal


arguments) receive value from the calling function (through actual
arguments). These arguments could be of any data type like int, float,
char, array, pointer etc. If any of the arguments is of pointer type then

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 260 Pointers Chapter 12

this pointer could point to any thing such as variable, array, function
etc.
ʇ NOTE
When a pointer to a function (let’s call this function as guest The advantage of passing
function) is passed to another function (let’s call this function as pointer to function, to another
host function) then the guest function becomes fully available in host function is that using different
pointers (say *p1 to x1 function
function, as if it was a part of it. Concept of passing one function to *p2 to y2 function), different
another, using pointers is illustrated in following figure. guest functions can be made
available in host function to do
multiple type of tasks.

Figure 12.5 : Pointer to Function

General syntax for host function is written as follows:


data_type_h function_name_h (data_type_g (*pointer)(data_type_a &variable_list),
data_type_b &variable_list);

Different symbols used in above format signify articles as


mentioned below:
(1) The host function will obviously return some value to the calling
function. The data_type_h signifies the data type of that value,
which host function returns.
(2) Host function will obviously have some name, by which it will be
identified throughout the program. Host-function-name is that
name.
(3) The data_type_g is the data type of that value which guest
function returns.
(4) Pointer is a pointer variable, which points to guest function.
(5) Guest function will obviously have an argument list, consisting
of data_type and variables. They are being denoted through
data-type-a & variable-list in the above format.
(6) Apart from pointer to the guest function, host function may
have other arguments also. Those arguments in terms of data
type and variables are being denoted by data_type_b & variable
list in the above mentioned format.
Function Definition
Function definition will be as follows:

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 261

data_type_h host_function_name (data type_g(*pointer)(data_type_a variable-list),


data_type_b variable list)
{
statements
return(expression);
}

Here all the symbols carry same meaning as mentioned in proto


type section.
Function Call
The host can be called by including statement of the following
type:
host_function_name(function_name, data_type_b variable_list)
Here data_type_b and variable_list have the same meaning,
which was explained in prototype section.
To get familiar with the process of passing one function to another
function, using pointers, let’s consider a program. A construction
company, develops blank land area, by doing land scaping, cement
construction and wood work on it. The cost of development varies for
circular areas and square plot areas.
Let’s write a program to get type of area and length/radius from
the keyboard and then depending upon the input calculates and prints
the cost of construction.

/*****************************************************************************/
/* Program 12.20 : Illustrating Pointer to Function */
/*****************************************************************************/
#include<stdio.h>
float circle_area(int r);
float square_area(int r);
float cost_constrn(float(*ptr)(int r1),float r1,float r2,float r3);
void main()
{
int len;
float amt=0;
char shape;
clrscr();
printf(“This program calculate the cost of construction.”);
printf(“\nArea must be circular or square.”);
printf(“\n\nEnter c for circular area and s for square : ”);
scanf(“%c”, &shape);
if(shape==’c’ || shape==’C’)
amt=cost_constrn(circle_area, 10.00,20.00,30.00);
if(shape==’s’ || shape==’S’)
amt=cost_constrn(square_area, 5.00,10.00,15.00);
if(amt==0)
{
printf(“Wrong input”);
getch();

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 262 Pointers Chapter 12

return;
}
printf(“\nTotal cost of construction : %0.2f”,amt);
getch();
}

float cost_constrn(float(*ptr)(int r1), float r1, float r2, float r3)


{
int len;
float area, total, c1,c2,c3;
printf(“\nEnter radius or length of the plot : ”);
scanf(“%d”,&len);
area=(*ptr)(len);
printf(“\nTotal Area for construction : %0.2f”,area);
c1 = area * r1;
c2 = area * r2;
c3 = area * r3;
printf(“\nCost of Landscaping : %0.2f”,c1);
printf(“\nCost of Cement Construction : %0.2f”,c2);
printf(“\nCost of Woodwork : %0.2f”,c3);
total = c1 + c2 + c3;
return(total);
}

float circle_area(int r1)


{
float area;
area = (float) (22 * r1 * r1)/7;
return(area);
}

float square_area (int r1)


{
float area;
area = (r1 * r1);
return(area);
}
/*****************************************************************************/

 OUTPUT :
Run 1
This program calculate the cost of construction.
Area must be circular or square.

Enter c for circular area and s for square : c

Enter radius or length of the plot : 3


Total Area for construction : 28.29
Cost of Landscaping : 282.86
Cost of Cement Construction : 565.71
Cost of Woodwork : 848.57
Total cost of construction : 1697.14

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 263

Run 2
This program calculate the cost of construction.
Area must be circular or square.

Enter c for circular area and s for square : s

Enter radius or length of the plot : 4


Total Area for construction : 16.00
Cost of Landscaping : 80.00
Cost of Cement Construction : 160.00
Cost of Woodwork : 240.00
Total cost of construction : 480.00

Run 3
This program calculate the cost of construction.
Area must be circular or square.

Enter c for circular area and s for square : d


Wrong input

12.16 POINTERS TO STRUCTURE

Members of a structure can be of any data type, including pointers. A


structure containing pointers is illustrated in the following example:
struct data
{
int roll;
char *name;
int marks;
};

You know that pointer is a variable, which points to another


variable. The variable. to which it points to can be of any data type,
i.e. int, float, char etc. You also know that structure is a derived data
type. Now the question is, can a pointer point to a variable, which is of
structure type? Well, the answer is yes. A pointer of structure type can
always point to the variables, which are of structure type. The concept
of pointer to structure is illustrated in following figure.

Figure 12.6 : Pointers to Structure

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 264 Pointers Chapter 12

The concept illustrated in figure 12.7, when translated into C


language, will result into following definitions and statements:
struct struc_name /* Structure definition*/
{
members
};
struc_name variable /* To which pointer will point*/
struc_name *pointer_name /* pointer, which will hold the address of structure
variable*/

To understand the concept clearly, let’s take an example.


struct data struct data
{ {
int roll_no; or int roll_no;
char name[50]; char name[50];
int marks; int marks;
int position; int position;
}; } student;
struct data student; struct data *pstudent
struct * pstudent

Address of the First element


Address of the first element of structure type variable can be
obtained using address operator. For above mentioned example, address
of first element of student variable can be obtained as follows:
pstudent=&student;

Accessing members through pointers


When you have a pointer pointing to structure variable, members
can be accessed through pointer, using Arrow operator(->). Arrow
operator consist of - sign followed by greater than sign. Such accessing
of members is done in following format:
pointer_name->member_name;
To understand the format clearly, refer structure data and pointers
pstudent, mentioned in previous section. Members of the student
variable can be referred to as mentioned below.
Referring Using Pointer Normal referencing
pstudent --> roll_no student.roll_no
pstudent --> name student.name
pstudent --> marks student.marks
pstudent --> position student.position
Note that name is a character array of 50 elements. Now the
question is, how do you access, individual elements (i.e. different
characters of name) of the array? Well, that would be accessed as
follows:
pstudent --> name[0], pstudent --> name[1], pstudent --> name[2] etc.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 265

Also note that these elements in normal referencing method will


be referred to as follows:
student.name[0], pstudent.name[1], pstudent.name[2] etc.
Now let’s consider a program that accept roll number, name and
marks of 50 students from the user and print all the details of the
student, who secured highest marks.

/*****************************************************************************/
/* Program 12.21 : Illustrating Pointer to Structure */
/*****************************************************************************/

#include<stdio.h>
void main()
{
int i, count=0;
int big=0;
struct data
{
int roll_no;
char name[50];
int marks;
};
struct data student[5];
struct data *pstudent[5];
clrscr();
printf(“This program find the topper among a five student list\n.”);
for(i=0;i<5;i++)
{
pstudent[i]=&student[i];
printf(“\nEnter Roll Number : ”);
scanf(“%d”,&pstudent[i]->roll_no);
printf(“Enter Name : ”);
scanf(“%s”,pstudent[i]->name);
printf(“Enter Marks : ”);
scanf(“%d”,&pstudent[i]->marks);
}
for(i=0;i<5;i++)
{ if(pstudent[i]->marks>big)
{
big=pstudent[i]->marks;
count = i;
}
}
printf(“\nTopper Student :”);
printf(“\nRoll No : %d”,pstudent[count]->roll_no);
printf(“\nName : %s”,pstudent[count]->name);
printf(“\nMarks :%d”, pstudent[count]->marks);
getch();
}
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 266 Pointers Chapter 12

 OUTPUT :
This program find the topper among five student list.

Enter Roll Number : 101


Enter Name : mahesh
Enter Marks : 78

Enter Roll Number : 102


Enter Name : manish
Enter Marks : 62

Enter Roll Number : 103


Enter Name : pankaj
Enter Marks : 48

Enter Roll Number : 104


Enter Name : rajkumar
Enter Marks : 95

Enter Roll Number : 105


Enter Name : praveen
Enter Marks : 39

Topper Student:
Roll Number : 104
Name : rajkumar
Marks : 95

12.17 DRAWBACK OF POINTER

Direct access to memory means you can do things that perhaps you
should not. Depending on the language, the compiler and the computer
platform, you could unintentionally (or intentionally) access memory
that is not yours to access. As a result, you could overwrite critical
memory, modify the code of a running application, or cause your
application or another application to behave or exit unexpectedly. One
common error is to run past the end of an array, accessing the memory
beyond the end of the space allocated for that array.

12.18 DYNAMIC MEMORY ALLOCATION

During compilation, C needs number of elements in an array. If the


array elements are not found appropriate, the program execution fails
or causes memory wastage.
In some languages, such as BASIC, it is possible to input the array
size during program execution. This process of allocation of memory
size at runtime is referred to as dynamic memory allocation.
In C, there are four library routines called memory management

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 267

functions for the purpose of memory management. Table 12.2 describes


the tasks of these functions:

TABLE 12.2 : Describing the Tasks of the Memory Management Functions

Function Task
malloc() Allocates memory from a pool and returns a pointer to a block of contiguous
memory of the specified size
calloc() Allocates memory for array elements, initializes them to 0, and returns a pointer
to the memory
free() Frees the memory block that are previously allocated by malloc() and calloc()
realloc() Modifies the size of a previously allocated memory block

The program instructions and global variables are stored in a


permanent storage area whereas local variables are stored in another
area called stack. The memory space that is located between these
two regions is available for dynamic allocation during program
execution. This free memory region is known as heap. Due to creation
and termination of local variables, the size of the heap keeps changing
during program execution. Let’s now discuss all the aforementioned
memory management functions one by one.

12.18.1 malloc()
When a C compiler executes a function, the memory is allocated to
local variables. This memory is taken from a free pool. Free pool refers
to a memory that is not used by a program. After completing the
execution, allocated memory is returned to the free pool for subsequent
use. The syntax of malloc() is as follows:
malloc (nob);
where, nob (number of bytes) represents the contiguous memory
locations to be allocated. The malloc() function allocates memory
from a pool. The malloc() function takes integer value as a parameter
that specifies the number of bytes to be allocated. It returns a pointer
to a block of contiguous memory of the specified size. The pointer is
actually of char * type, but it can be cast into any other type as per
requirement. The memory once allocated can be returned to the free
pool by passing the pointer to the free() function. For example,
ptr=(cast-type *), malloc(byte-size);
char *string,
string = malloc(n);
free(string);

In the above example, a string of type char * is declared along


with the malloc() function to return a value of the same type where n

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 268 Pointers Chapter 12

is a variable containing the number of bytes (characters) needed. After


handling an array, the program would execute free(string) statement
which returns the allocated memory to the free pool and at this point
a new value can be assigned to the string.

12.18.2 calloc()
The calloc() function is used for both, to allocate memory for
the array elements and to initialize them to 0. The parameters of the
calloc() function are different from the parameters of the malloc()
function. The syntax of the calloc() function is as follows:
ptr = (cast-type *) calloc(n,element-size);
The receding statement allocates space for n blocks in bytes
where each block is of the size specified by element-size. The calloc()
function initializes all bytes to zero and returns a pointer to the first
byte of the allocated region.

12.18.3 free()
The free() function is used to free the memory blocks that are
allocated by malloc() and calloc(). In a program, if some string or
array of some memory block is no more required, the memory can
be freed using this function. The syntax of the free() function is as
follows:
free (ptr);
where ptr is a pointer created by malloc() or calloc().

12.18.4 realloc()
The realloc() function is used to modify the size of a previously
allocated memory block. The syntax of the realloc() function is as
follows:
ptr = realloc(ptr,newsize);
The above statement allocates a new memory space of size newsize
to the ptr pointer variable and returns a pointer to the first byte of
the new memory block. The newsize may be smaller or larger than the
former size. The new memory block may or may not be allocated at the
same location as the old one. If the function is unsuccessful in locating
additional memory block, it returns a NULL value and the original
block is lost.
Let’s create a C program to learn how these functions are used for
memory management. Program 12.22 shows the code of this program:

/*****************************************************************************/
/* Program 12.22 : Allocating Memory at Runtime */
/*****************************************************************************/

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 269

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
main() {
int *x, *y, *z;
int i, num;
clrscr();
printf(“\nThis program add the elements of two array.”);
printf(“\nEnter the number of elements that you want in each array : ”);
scanf(“%d”,&num);
x=(int *) malloc(num *sizeof (int));
y=(int *) malloc(num *sizeof (int));
z=(int *) malloc(num *sizeof (int));
printf(“\nEnter the elements of first array : ”);
for(i=0; i<num; i++)
scanf(“%d”, x+i);
printf(“\nEnter the elements of second array : ”);
for(i=0; i<num; i++)
scanf(“%d”, y+i);
for(i=0; i<num; i++)
*(z+i)= *(x+i) + *(y+i);
printf(“\nNew array after addition : \n”);
for(i=0; i<num; i++)
printf(“%d\t”, *(z+i));
getch();
}
/*****************************************************************************/

 OUTPUT :
This program add the elements of two array.
Enter the number of elements that you want in each array : 5
Enter the elements of first array : 2 4 6 8 10
Enter the elements of second array : 1 3 5 7 9
New array after addition :
3 7 11 15 19

 EXPLANATION :
In program 17, we have created three one-dimensional arrays, x, y, and z, in which
the first two arrays accept the array elements which are added to create a new array.
The elements resulted from adding the elements of the first two array are stored in
the third array.

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 270 Pointers Chapter 12

REVIEW QUESTIONS int i, j;


clrscr(),
printf(“Enter the first integer value : ”);
12.1 Define pointers. scanf(“%d”, &i);
printf(”Enter the second integer value :”);
12.2 Write a short note on pointers. scanf(“%d”, &j);
12.3 What is a pointer and how it is initialized? Equal(&i, &j);
getch();
12.4 How is a pointer declared? How is variable accessed }
through its pointer? Equal(int *i, int *j)
{
12.5 What are pointers? Why are they needed? Explain
if(i==j)
with an example. printf(“The two values are equal.”);
12.6 Discuss the applications of pointers and list the else
printf(“The two values are not equal.”);
disadvantages of them.
}
12.7 Compare pointer and array name.
12.8 Explain the difference between a null pointer and a 12.2 Find out the error in the following code.
void pointer. #include<stdio.h>
#include<conio.h>
12.9 What do you understand by a null pointer? void main()
12.10 Write a short note on pointer arithmetic. {
int x[]={5, 3, 2, 8, 12};
12.11 What do you understand by the term pointer to a int *y;
function? clrscr();
y=x;
12.12 Differentiate between ptr++ and *ptr++. y=y*2;
12.13 Briefly explain array of pointers. printf(“value is %d”, *y);
getch();
12.14 In what way can the assignment of an initial value }
be included in the declaration of a pointer variable?
12.15 What is the relationship between an array name 12.3 Find out the error in the following code.
and a pointer in C? How is an array name treated #include<stdio.h>
when it appears as a function argument? #include<conio.h>
void main()
12.16 How can a one dimensional array of pointers be {
used to represent a collection of strings in C? int x[]={12, 13, 15, 16};
int *p;
12.17 Explain the difference between a pointer to a p = &(x+3);
constant and a constant pointer with suitable printf(“\n\n%d”, p[0]);
examples. getch();
}
12.18 Give an example of array of pointers and pointers
to pointers. 12.4 What is the output of the following code ?
12.19 What is an array of pointers? How is it different #include<stdio.h>
from a pointer to an array? main()
{
int *num;
{
int num1=200;
PROGRAMMING OUTPUT QUIZ num=&num1;
}
printf(“%d”, *num);
12.1 The following code is written to compare the two }
integer numbers whether they are equal or not,
12.5 What would be the output of the following code ?
However, every time when the user runs the code
# include<stdio.h>
snippet with different integer values and finds
int single_d[]={4, 5, 6};
the same output, “The two values are not equal” main()
Identify the error. {
#include<stdio.h> int *ptr;
#include<conio.h> ptr=single_d;
void main() ptr+=3;
{ printf(“%d”, *ptr);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 271

} int **i;
int *j=0;
12.6 What is the output of the following code? i=&j;
clrscr();
#include<stdio.h>
if(NULL != i && NULL != *i)
main()
printf(“hello”);
{
getch();
void *vod_ptr;
}
int integer=2;
int *ii = &integer;
vod_ptr = ii;
12.12 What is the output of the program?
printf(“%d”, (int*)*vod_ptr); #include<stdio.h>
} #include<conio.h>
void main()
12.7 What would be the output of the following program? {
register i=161;
#include<stdio.h>
register *j=161;
main()
clrscr();
{
printf(“\n%d%d”, &i, &j);
int num=3, *ptr1, *ptr2;
getch();
ptr1=ptr2=&num;
}
*ptr2+=*ptr2+=num+=4;
printf(“\n%d\t%d\t%d”, num, *ptr1, *ptr2);
}
12.13 What is the output of the program?
#include<stdio.h>
12.8 What would be the output of the following program? void main(); void main (x)
{
#include<stdio.h>
void *v;
main()
v=&x;
{
printf(“%d”, ++*(int *)v);
char *str=”RTUK”;
}
char *ptr=str;
char least=127;
while (*ptr++)
12.14 What is the output of the program ?
least=(*ptr<least)?*ptr:least; #include<stdio.h>
printf(“%d”, least); #include<conio.h>
} main()
{
12.9 What would be the output of the following program? const int *p=5;
int *q;
#include<stdio.h>
clrscr();
void main ()
printf(“\n%d”, p);
{
q=&p;
int num=10, num1=2;
printf(“\n%d”, ++*q);
int *nump= &num, *numlp=&num1;
printf(“\n%d”, p);
int k=*nump/*num1p;
getch();
printf(“%d”, k);
}
}
12.15 What is the output of the program ?
12.10 What is the output of the program?
#include<stdio.h>
#include<stdio.h>
void main()
#include<conio.h>
{
void main()
int const *p=2;
{
*(int *)&p=94;
int a[5]={13, 14, 15, 16, 17};
printf(“\np = %d”, p);
clrscr();
}
printf(“%d\t%d\t\n”, a[a[0|1]-10],3[(a+1)]);
printf(“%d\t%d”,a[1[a]-10]>(*a+2)?(*a<<1)+1:*a,
4[a]);
12.16 What would be the output of the following program?
getch(); #include<stdio.h>
} #include<conio.h>
void main()
12.11 What is the output of the program? {
char str[]=”Peacefull for all”;
#include<stdio.h>
clrscr();
#include<conio.h>
printf(“\n%c”, *(&str[2]));
void main()
printf(“\n%s”, str+5);
{

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 272 Pointers Chapter 12

printf(“\n%s”, str); }
printf(“\n%c”, *(str+2));
getch(); 12.21 What would be the output of the following program?
}
#include<stdio.h>
#include<conio.h>
12.17 What would be the output of the following program? main()
#include<stdio.h> {
#include<conio.h> char str[]={‘a’, ‘b’, ‘c’, ‘\0’, ‘d’, ‘e’, ‘f’};
int len(char *p) char *ptr=“Hello”;
{ clrscr();
static int i; printf(“\nstr = %s”, str);
if(i++, *p++!=‘\0’) *++ptr;
len(p); printf(“\nptr = %s”, ptr);
return i; *++ptr;
} printf(“\nptr = %s”, ptr);
main() }
{
char *srcstr=”hihello”; 12.22 What is the output of the program ?
clrscr();
#include<conio.h>
printf(“\nLength = %d”, len(srcstr)-1);
#include<stdio.h>
getch();
main()
}
{
char ch, chl, *p=”abcdef”;
12.18 What would be the output of the following program? clrscr();
#include<stdio.h> ch=*++p;
#include<conio.h> printf(“\nch = %c,\tp = %s”, ch, p);
main() chl=*(++p);
{ printf(“\nch = %c,\tchl = %c,\tp = %s”,ch,chl,p);
char *ptr= ‘2’; }
int i=100, *j=&ptr;
clrscr(); 12.23 What is the output of the program ?
printf(“\n%d”, i/(*j));
#include<conio.h>
getch();
#include<stdio.h>
}
main()
{
12.19 What would be the output of the following program? char ch, ch1, *p=”abcdef”;
#include<stdio.h> clrscr();
#include<conio.h> ch=++*p;
main() printf(“\nch = %c,\tp = %s”, ch, p);
{ chl=++(*p);
char a[2] = “go”, *p= ‘h’; printf(“\nch = %c,\tch1 = %c,\tp = %s”,ch,ch1, p);
clrscr(); ch=(++*p);
p=&a[0]; printf(“\nch = %c,\tch1 = %c,\tp = %s”,ch,ch1,p);
p=a; }
p++;
a=p; 12.24 What is the output of the program ?
a++;
#include<conio.h>
printf(“%c%c\n”, *p, *a);
#include<stdio.h>
getch();
main()
}
{
int **ptr=45;
12.20 What would be the output of the following program? clrscr();
#include<stdio.h> if(**ptr==*ptr[0])
#include<conio.h> printf(“%d”, ptr);
main() }
{
int *p, j;
clrscr();
for(j=0;j<5;j++) LAB PROGRAMS
{
p=(int *) “0”;
printf (“\np=%c”, ++*p);
12.1. Write a program to illustrate the concept of
}
getch(); pointers.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 12 Pointers Page 273

12.2. Write a program to traversing an array using a in an array using an array of pointers.
pointer. 12.13. Write a program to search for a given character in
12.3. Write a program to illustrate address of ( & ) a string and print the string from start to the point
operator. match.
12.4. Write a program to illustrate the concept of pointer 12.14. Write a program to illustrate the return of pointer
expressions. from a function.
12.5. Write a program to illustrate different types of 12.15. Write a program to reversing an array using
pointers. pointers.
12.6. Write a program to illustrate use of void pointer for 12.16. Write a program to sort the strings (weekdays)
int and float types. alphabetically using array of pointers. Sort the
12.7. Write a program to illustrate pointer to a pointer. pointers to the string, not the actual string.

12.8. Write a program to illustrate dynamic memory 12.17. Write a program for binary search recursively
allocation. on a sorted array given in ascending order using
pointers.
12.9. Write a program for manipulation of an array using
a pointer. 12.18. Write a program for bubble sort using pointers.

12.10. Write a program to find sum of N elements of an 12.19. Write a program for binary search on a sorted array
array A using pointer. given in ascending order using pointers.

12.11. Write a program to print array elements being to 12.20. Write a program for insertion in a sorted array
by an array of pointers. given in ascending order array remains sorted after
insertion.
12.12. Write a program to exchange the position of string

***********

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

13
FILE HANDLING

13.1 INTRODUCTION

Till now we had been dealing with the programs, which held the input-
data temporarily. As soon as the program came to end, the data got
lost. For example, if you enter student’s roll number, name and marks,
using scanf statement, the data will remain available till the time
program is running. As soon as the program will end, these values
will not be available. While writing programs for real life situations,
you will often come across situations, when you will have to hold the
data permanently. For holding the data permanently, you have to read
the data from the keyboard (as we used to do), write it in a file and
later, whenever required, read the data from file. C language supports
different types of file handling operations for using files. Their details
are described in this chapter.

13.2 TYPE OF FILES

C supports three different types of data files, using which you can
ʇ NOTE
hold the data permanently on media and make use of it as and when Since text files are ASCII files
required. These files are: hence you can view them on
your computer screen.
(1) Text Files
(2) Variable Record length files
(3) Constant record length files

13.3 TEXT FILES

Text files are also called stream oriented data files. In there files the
data is written as stream of characters and it is read as stream of
characters. A typical Text file many look like as follows:

Jhunjhunuwala is a text book publishing organization. It has high turnover with high growth
rate. It is committed to deliver good quality content books and promote good books India.

Recall the nature of the files that you create through text editors
and note that the text file mentioned above is just equivalent to any
text editor file. You can create a text file through your system text

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 13 File Handling Page 275

editor and read them through a C program also or you can create a text
file through a C program and read it through your system text editor.

13.4 PERFORMING FILE OPERATIONS

Be it any type of file, read and write operations have to be performed


in the sequence mentioned below:
Writing in a File Reading the File
(a) Establishing a Buffer area (a) Establish a buffer Area
(b) Open the file (b) Open the file
(c) Write the data into file (c) Read the file
(d) Close the file (d) Close the file

13.4.1 Establishing a Buffer Area


While working with files in C language, you have to establish a Buffer
area first. Buffer area is a memory area, where the information is
temporary held then it is transferred to/from file. General format for
establishing a buffer area is as follows:
FILE *pointer_variable;
Here FILE (all upper case letters) is a special structure type that
establishes the buffer area and the pointer-variable is the name of
pointer variable that points to the beginning of the buffer area. Note
that the structure type, FILE is already defined in stdio.h file. This
pointer is often referred to as stream pointer or simple stream.

13.4.2 Opening a Data File


After defining the buffer area, you have to open the data file, so that
read/write operations could be performed. The library function fopen
opens the file. General format for fopen function is as follows:
pointer_variable = fopen(file_name, mode);
Here pointer_variable is the name of pointer variable that was
defined at the time of establishing the buffer area. fopen is the name of
the function, which is to be written as such and file-name is the name
of the file that you want to open. Mode is a string, which indicates the
mode, in which the file is to be opened. It can be opened in any one of
the following modes:
Mode Meaning
“r” Opens the file for read operations only.
“r+” Opens an existing file for both reading and writing.

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Page 276 File Handling Chapter 13

Mode Meaning
“w” Opens the file for writing only. If the mentioned file already exists then it will destroy
that and create a fresh a fresh file for writing.
“w+” Opens the file for both reading and writing. If the mentioned file already exists then it
will destroy that file and create a fresh file for writing.
“a” Opens the file for appending. If the file with mentioned file name does not exist then a
fresh file will be created.
“a+” Opens the file for reading and appending. If the file with mentioned file name does not
exist then it creates a fresh file for operations.

You should remember following points


(1) fopen function returns a pointer to the beginning of the buffer
area associated with the file. A Null value is returned, if somehow
the file could not be opened.
(2) After opening the file, it is identified with pointer variable rather
than by its name. In the subsequent file operations, such as
writing the file, reading the file or closing the file, we mention the
corresponding pointer variable name, instead of the file name.
For examples if you wish to open a file named bell.dat, in read
mode only then you will have to include the following lines in the
program, before you perform any file operation:
FILE *pt1;
Pt=fopen(“bell.dat”, “r”);

Following statements will open the file in write mode:


FILE *pt2;
pt2=fopen(“marks.dat”, “w”);

If an already existing file named, student.dat has to be opened


in append mode then following statements could be used for opening
the file:
FILE *pt3;
pt3 = fopen(“student.dat”, “a”);

13.4.3 Closing the Files


After performing all the operations on files, all the opened files should be
closed. Although, when the program ends, C closes all the opened files
itself. But on the other hand, if you do not close the file then you many
run the risk of loosing the data. So it is a good programming practice
to close all the opened files before you end the program. General format
for closing the file is as follows:
fclose(pointer_variable);

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV

Chapter 13 File Handling Page 277

Here pointer_variable is that variable name, which was


mentioned at the time of opening the file. For example, if you wish to
close all the three files mentioned above then you will can include the
following statements in the program:
fclose(pt1); /* close bell.dat file*/
fclose(pt2); /* close marks.dat file*/
fclose(pt3); /* close student.dat file*/

13.4.4 Writing in a Text File


C provides, putc function, using which you can write a single character
in the file. General format for putc function is as follows:
putc(character, pointer_variable);
Here character is a character or character variable whose value is
to be written in the file. The pointer-variable is that pointer variable,
which refers to the file, in which the value is to be written. For example,
if you wish to write “B” in marks.dat file (mentioned above) then you
can use putc function as follows:
putc(“B”, pt2);

13.4.5 Reading the Test File


C provides getc function for reading a character from the text file.
General format for getc function is as follows:
getc(pointer_variable);
Here pointer_variable refers to that file, from which you wish to
read the character. For example, if you wish to read a single character
form bell.dat file (mentioned above) then you can include the following
statements in the program:
char x;
........
........
x = getc(pt1);

Note that in this example getc function reads a character from


the file and assigns it to character variable x.
Now you are familiar with the characteristics of text files and
the functions, using which you can operate upon them. Let’s write a
program, which accepts stream of characters from keyboard and stores
them in test.dat file. The program continues to accept the input, till
you press Tab and Enter keys.

/*****************************************************************************/
/* Program 13.1 : Illustration of fopen and writing to file */
/*****************************************************************************/
#include <stdio.h>

'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')

You might also like