0% found this document useful (0 votes)
2 views

sanet.st_Concepts_and_Techniques_of_Programming_in_C

The document is a comprehensive guide on programming in C, covering fundamental concepts, algorithms, data types, operators, and various programming constructs. It is designed for undergraduate and postgraduate students, as well as aspiring programmers, and includes detailed explanations and examples across multiple chapters. The book also emphasizes practical applications and includes sections on error handling, memory management, and file operations.

Uploaded by

shrikant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

sanet.st_Concepts_and_Techniques_of_Programming_in_C

The document is a comprehensive guide on programming in C, covering fundamental concepts, algorithms, data types, operators, and various programming constructs. It is designed for undergraduate and postgraduate students, as well as aspiring programmers, and includes detailed explanations and examples across multiple chapters. The book also emphasizes practical applications and includes sections on error handling, memory management, and file operations.

Uploaded by

shrikant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 419

Concepts and Techniques of

Programming in C
Concepts and Techniques of
Programming in C

Dhabal Prasad Sethi


Faculty (Contract)
Department of Computer Science and Engineering
Parala Maharaja Engineering College, Berhampur, Odisha
(A Constituent College of BPUT, Govt. of Odisha)

Manoranjan Pradhan
Professor and HOD
Department of Computer Science and Engineering
Gandhi Institute for Technological Advancement
Bhubaneswar, Odisha
©Copyright 2020 I.K. International Pvt. Ltd., New Delhi-110002.

This book may not be duplicated in any way without the express written consent of the publisher,
except in the form of brief excerpts or quotations for the purposes of review. The information
contained herein is for the personal use of the reader and may not be incorporated in any commercial
programs, other books, databases, or any kind of software without written consent of the publisher.
Making copies of this book or any portion for any purpose other than your own is a violation of
copyright laws.

Limits of Liability/disclaimer of Warranty: The author and publisher have used their best efforts in
preparing this book. The author make no representation or warranties with respect to the accuracy or
completeness of the contents of this book, and specifically disclaim any implied warranties of
merchantability or fitness of any particular purpose. There are no warranties which extend beyond the
descriptions contained in this paragraph. No warranty may be created or extended by sales
representatives or written sales materials. The accuracy and completeness of the information provided
herein and the opinions stated herein are not guaranteed or warranted to produce any particulars
results, and the advice and strategies contained herein may not be suitable for every individual.
Neither Dreamtech Press nor author shall be liable for any loss of profit or any other commercial
damages, including but not limited to special, incidental, consequential, or other damages.

Trademarks: All brand names and product names used in this book are trademarks, registered
trademarks, or trade names of their respective holders. Dreamtech Press is not associated with any
product or vendor mentioned in this book.

ISBN: 978-93-89633-08-5

EISBN: 978-93-89976-52-6

Edition: 2020
Dedicated to
My Father
Digambar Sethi
&
Mother
Kanchan Bala Sethi
Preface

The C programming language is one of the most widely offered courses at many
institutions and universities in the undergraduate programmes (all branches of BTech,
BSc Computer Science, and BCA) as well as various postgraduate programmes (MCA,
MSc Computer Science and others). Apart from students, the book will also be useful
to aspirants of various competitive examinations and budding programmers at work.
The book is straightforward and simple in its approach, deals with fundamentals of
computer, algorithms and flowcharts, error handling, different data types, variables,
operators, input/output operations, decision statements, looping, unconditional
statements, functions, arrays, strings, pointers, dynamic memory management,
structure and union, file and file handling, and preprocessor directives.
Chapter 1 deals with the fundamentals of computer which include the basic block
diagram of a computer, RAM, ROM, input devices, output devices, number systems,
problem solving, etc.
Chapter 2 discusses the algorithm and flowchart.
Chapter 3 presents C programming with introduction, general terminology, different
types of error in C programming.
Chapter 4 deals with different types of data types, variables, rules of naming a
variable, and different types of constant, token, keyword, identifier and others.
Chapter 5 focuses on different types of operator, e.g., arithmetic operator, logical
operator, conditional, increment/decrement operator, relational, logical, bitwise
operator and others.
Chapter 6 deals with input/output operations in C programming and includes
introduction, reading a single character, writing a single character, escape sequences,
delimiters, formatted input and output.
Chapter 7 discusses decision making statements, e.g., if statement, if else statement,
nested if-else statement and switch statement.
Chapter 8 discusses and presents different types of looping in C programming, e.g.,
while loop, do while loop, for loops with their programming examples.
viii Preface

Chapter 9 presents unconditional statements, e.g., breaks, goto, continue and exit
statements.
Chapter 10 focuses on the functions, i.e., library functions and user defined functions,
different types of function, formal parameter, actual parameter, recursion, storage
classes, etc.
Chapter 11 discusses arrays with program and theories of one-dimensional array,
two-dimensional arrays and three-dimensional arrays.
Chapter 12 deals with string which hold different function getchar(), gets(), putchar(),
puts(), strlen(), strcpy(), strcmp(), strcat(), strrev().
Chapter 13 deals with pointer, declaration, null pointer, generic pointer, pointer to
pointer, pointer to array, array of pointer and dynamic memory management.
Chapter 14 discusses the structure, union, type definition, bit filed and others.
Chapter 15 discusses the file, text file vs binary files, file I/O function, file opening
mode, error happed during I/O operation and others.
Chapter 16 deals with the preprocessor directives.

Dhabal Prasad Sethi


Manoranjan Pradhan
Acknowledgements

I wish to express my profound sense of gratitude to my teacher Professor Dr. Manmath


Kumar Roul , Principal, Gandhi Institute for Technological Advancement Bhubaneswar;
my coauthor Dr. Manoranjan Pradhan Professor and HoD Dept of CSE GITA BBSR; Dr.
Trilochan Sahu, Principal Government College of Engineering Keonjhar; Er. Mukesh
Bathre, Assistant Professor and HoD CSE GCE Keonjhar for their encouragement.
I thank Mr. Sanjit Kumar Barik, Lecturer CSE GCE, KJR; Anshuman Mishra,
Senior Lecturer Dept. of CSE BIET, Bhadrak; Alisha Ranasingh, Lecturer in Computer
Application OSME, Keonjhar; and Sisir Kumar Sahu, Cognizant Technologies Kolkata.
I wish to thank students of all branches of GCE, Keonjhar from session 2011 to 2016
batches who participated in my “Programming in C Lecture” helped me to explore
my concepts and ideas as discussed in this book. I would like to thank the first batch
BTECH (2015-16 admission batch) of Computer Science and Engineering students of
GCE KJR for their support, specially Subhajit Das.
Lastly, I wish to express my gratitude to all of my family members for their
encouragement and support. I specially thank my father Digambar Sethi, mother
Kanchan Bala Sethi, brother Jugal Prasad Sethi, and sister Mita Sethi other family
members Golak Prasad Sethi, Kailash Chandra Sethi, Hemanta Kumar Sethi, Nutan
Prakash Sethi, Swadhin Prakash Sethi, and Debendra Kumar Sethi.
Suggestions for improving further editions of the book are welcome and can be sent
to me at: [email protected].
Dhabal Prasad Sethi
Contents

Preface vii
Acknowledgements ix

1. Computer Fundamentals........................................................................................ 1
1.1 Introduction 1
1.2 Block Diagram of a Computer 1
1.3 Bits and Bytes 5
1.4 Memory 6
1.5 Number System Representation 8
1.6 Problem Solving 11

2. Algorithm and Flowchart..................................................................................... 14


2.1 Introduction 14
2.2 Flowchart 19

3. C Programming...................................................................................................... 32
3.1 Introduction 32
3.2 General Terms a Programmer Should Know Before Writing any Program 33
3.3 Types of Errors in C Programming 36
3.4 Logical Steps for Writing a Program 37
3.5 How to Write a Simple C Program 37
3.6 Different Ways to Write the Main () Function 40
3.7 Basic Structure of C Program 42
3.8 Steps of Writing a C Program Using Editor 44
3.9 Diagrammatic Representation of Internal Structure of C Program Execution 45
3.10 Common Mistakes the Beginner Does and Its Correction 47
3.11 Useful C Programing Examples Without Using Control Statement 48
xii Contents

4. Variables, Constants and Data Types................................................................. 63


4.1 Introduction 63
4.2 Declaration of Variables 63
4.3 Initialization of Variables 65
4.4 Rules of Naming a Variable 66
4.5 What is Constant? 67
4.6 Explanation of Different Types of Constants 67
4.7 Symbolic Constant 68
4.8 Character Set 69
4.9 Tokens 70
4.10 Keywords 70
4.11 Identifier 71
4.12 Data Types 71
4.13 Types of Data Types 72

5. C Operator............................................................................................................... 77
5.1 Introduction 77
5.2 Types of Operator 77
5.3 Type Conversion/Type Casting 95
5.4 Precedence and Order of Evaluations 98

6. Input and Output Operations in C................................................................... 109


6.1 Introduction 109
6.2 Reading a Single Character 109
6.3 Writing/Displaying a Single Character 111
6.4 Format Specifications 112
6.5 Escape Sequences 113
6.6 Mostly Used Header Files 113
6.7 Delimiters 114
6.8 Formatted Input 114
6.9 Formatted Output 116

7. Decision Making Statements (Conditional Statements).............................. 123


7.1 Introduction 123
7.2 if Statements 124
7.3 Concepts of switch case Statement 145

8. Looping.................................................................................................................. 160
8.1 Introduction 160
8.2 Concept of Looping 160
Contents xiii

9. Unconditional Statements.................................................................................. 208


9.1 Introduction 208

10. Function............................................................................................................... 220


10.1 Introduction 220
10.2 Function Types 225
10.3 The return Statement 229
10.4 General Structure of Writing the Program Using Function 229
10.5 Types of User Defined Functions 232
10.6 Some Useful Programming Examples
Using Functions (User-Defiend Function) 235
10.7 Formal Parameters vs. Actual Parameters 247
10.8 Parameter Passing Technique 248
10.9 Scope of a Variable 250
10.10 Recursion 251
10.11 Some Useful Programming Examples Using Recursion 252
10.12 Storage Class in C 263

11. Array..................................................................................................................... 275


11.1 Introduction 275
11.2 One-Dimensional Array 277
11.3 Two-Dimensional Arrays 290
11.4 Three-Dimensional Arrays (3D-Array) 300

12. String.................................................................................................................... 306


12.1 Introduction 306
12.2 Reading a String 308
12.3 Writing a String/Displaying a String 309
12.4 String Handling Library Functions 310

13. Pointer.................................................................................................................. 325


13.1 Introduction 325
13.2 Different Ways of Pointer Variable Declaration 328
13.3 Pointer Variable Initialization 328
13.4 Null Pointer 330
13.5 Accessing a Variable by Using the Pointer Concept 331
13.6 Generic Pointer 332
13.7 Pointer to Pointer 332
13.8 Pointer as Function Arguments 337
13.9 Address (Pointer) Arithmetic 339
xiv Contents

13.10 Pointer and One-Dimensional Array 341


13.11 Pointers and Multidimensional Arrays 344
13.12 Pointer to Array 344
13.13 Array of Pointer 347
13.14 Dynamic Memory Management 348
13.15 Command-Line Arguments 351

14. Structure, Union, Type Definition, Bit Field................................................. 359


14.1 Introduction 359
14.2 Defining/Declaring a Structure 360
14.3 Declaration of Structure Variables 361
14.4 Accessing Structure Member 361
14.5 Structure Variable Initialization 362
14.6 Nested Structure 365
14.7 Array of Structure 367
14.8 Structure and Function or Passing Structure as an Argument in Function 368
14.9 Pointer to Structure 371
14.10 Self-Referential Structure 372
14.11 Union 373
14.12 Type Definition 374
14.13 Bit Field 375

15. File......................................................................................................................... 379


15.1 Introduction 379
15.2 Text Files and Binary Files 379
15.3 File I/O Operation 380
15.4 File Opening Mode 381
15.5 Input/Output Functions in File 382
15.6 Error Happened during I/O Operation 387
15.7 Random Access to File 387

16. Preprocessor Directive...................................................................................... 391


16.1 Introduction 391
16.2 Different Types of Preprocessor Directives 391

Appendix.................................................................................................................... 395
Bibliography.............................................................................................................. 397
Index............................................................................................................................ 399
1
Computer
Fundamentals

1.1 INTRODUCTION
A computer is an electronic device or machine (consisting of monitor, central processing
unit, keyboard, mouse, printer and modem) which can accept data as input and
processes it to give expected output and store in a secondary storage unit permanently.
Processing of input data into output is done by software applied on hardware. The
computer has three main parts or components, e.g., hardware, software and people.
The computer system which consists of different equipment or parts is called hardware,
for example, keyboard, mouse, monitor, hard disk, mother board and disk drives. The
computer program which tells the hardware what to do is called software. The software
is again divided into two types, e.g., system software and application software. The
system software is a computer program designed to run computer hardware and
application programs. It is the interface between the hardware and user applications.
Examples of system software are operating system, BIOS (Basic Input Output System),
assembler, compiler, device, driver, etc. Application software is a computer program
designed for end users, for example, Microsoft Office, Excel, Google Chrome, Mozilla
Firefox, Skype and others. People are an important part of computer system who can
use the computer for their requirements.

1.2 BLOCK DIAGRAM OF A COMPUTER


The different parts of a computer are: input device, storage unit, central processing
unit (CPU) and output.

1.2.1 Input Device


It is a hardware device through which the user can input the data into the computer. The
examples of input devices are mouse, keyboard, light pen, BCR (Bar Code Recognizer),
2 Concepts and Techniques of Programming in C

OCR (Optical Character Recognizer), OMR (Optical Mark Reader), MICR (Magnetic
Ink Character Recognizer), BIOMETRIC sensors, Web Camera, Smart Card Reader,
Graphics Tablets, Touch Screen, Joystick, Scanner, Pen Drive. Some of are explained
below.

Fig. 1.1 Block diagram of a computer

(a) Keyboard
The keyboard is the set of keys and it is one of the primary input devices used by
computers. The keyboard design is same as typewriter keyboard which arranges letters
and numbers in such way that it is prevents type bar from getting jammed when typing
quickly.

Fig. 1.2 Block diagram of keyboard

(b) Pen Drive


A pen drive or a USB flash drive is a portable
data storage device. Pen drive is popular and
familiar among the consumer because it is
light, micro and handy and can be carried
easily from one location to another and its
storage capacity ranges from 1 GB to 32 GB
or more which is used to contain music file,
video, photo, document, etc. Fig. 1.3 Block diagram of pen drive
Computer Fundamentals 3

(c) Scanner
A scanner is a device used for capturing the images from photographic prints, magazine
pages, answer sheet of exams and other sources for computer editing and display. The
scanner comes in hand-held, feed-in types and for scanning color or black and white.
High resolution scanners give high quality output.

Fig. 1.4 Block diagram of scanner

(d) Mouse
It is an input device used to control the movement of insertion point on the computer
screen.

Fig. 1.5 Block diagram of mouse

1.2.2 Storage Unit


The storage unit consists of two parts, i.e., secondary memory and primary memory.
The secondary memory is also known as auxiliary memory, auxiliary storage, secondary
storage or external memory. It is a non-volatile memory, i.e., when power is off it does
not lose its data. The examples are floppy disk and hard disk. The floppy disk is an
oxide-coated plastic piece that is used to store data as magnetic sport. In hard disk it
is made of a stack of rotating disks called platters. The data is recorded in the series
of tracks called sectors.
The primary memory is volatile in nature, i.e., when power is turned off all the data
is lost. The alternative names of primary memory are primary storage or main memory.
The examples of primary memory are RAM, ROM, and Cache Memory.
4 Concepts and Techniques of Programming in C

1.2.3 Central Processing Unit (Cpu)


The CPU is the heart of a computer which contains
electronic circuits that cause the computer to follow
instructions from ROM or RAM. The CPU consists of
three parts: a) arithmetic logic unit, and b) control unit.

(a) Arithmetic Logic Unit (ALU)


The ALU is a part of CPU which performs arithmetic
and logic operations on data which is retrieved from the Fig. 1.6 Block diagram of a
storage unit. After processing the operation the result is CPU chip
stored in the storage unit.

(b) Control Unit (CU)


The control unit (CU) acts like a supervisor and its role is coordinating the different
operations using timing diagram. The control unit determines the sequence of
instructions and program execution.

1.2.4 Output Device


The output device is used to display the message or information on the computer screen.
The examples of output devices are Monitor/VDU, LED/LCD screen, printers (inkjet/
bubble jet printer, laser printer), plotter, and speaker. Some of these are explained below.

(a) Monitor
It is an electronic device used for displaying picture on computer screen.

Fig. 1.7 Block diagram of a computer monitor

(b) Printer
Printer is a device which accepts instructions from computer in the form of text and
graphics and transfers the information on paper. Printers vary in speed, size and cost.
Computer Fundamentals 5

The printers are categorised into two types:


one is impact printer and the other is non-
impact printer. The impact printer works like
an automatic typewriter with a key striking an
inked impression on the paper for each printed
character, for example, a dot matrix printer. The
non-impact printers are ink jet printers which
spray ink from an ink reflected from a mirror
to attracted ink (tonner) to selected paper area
on the sheet rolls a drum. The example of non-
impact printer is laser printer.
Fig. 1.8 Shows the block diagram of
printer
1.3 BITS and BYTES
The following are memory related terms.
(a) Bit
Bit stands for binary digits and it is the smallest unit of data storage in a computer
memory. A bit holds the binary value, i.e., either 0 or 1. Binary means it can hold
two logical states, i.e., either true or false, either on or off. In hard disk the binary
value reflects when the bit is on in the magnetic or off not in the magnetic.
(b) Byte
A byte consists of eight binary digits, i.e., it consists of eight 0 or 1 combinations
.In byte the values of byte is stored on the computer hard drive.
(c) Nibble
The combination of four (4) bits is called nibble.
(d) KB (Kilobyte)
A kilobyte (KB) consists of 1024 bytes.
(e) MB (Megabyte)
A megabyte (MB) consists of 1024 kilobyte (KB).
(f) GB (Gigabyte)
A gigabyte consists of 1024 megabyte (MB).
(g) TB (Terabyte)
A terabyte consists of 1024 gigabytes.
(h) PB (Pet byte)
A pet byte consists of 1024 terabytes.
(i) EB (Exabyte)
An exabyte consists of 1024 pet bytes.
(j) ZB (Zeta byte)
A zeta byte consists of 1024 exabytes.
(k) YB (Yotta byte)
A yotta byte consists of 1024 zeta bytes.
6 Concepts and Techniques of Programming in C

1.4 MEMORY
The computer memory is like a human brain. Its work is to store the data and instructions.
It is the storage space in a computer where data is processed and instructions required
for processing are stored. The memory unit consists of a large number of small memory
units called memory cells. Each cell or location has specific address which varies from
0 to memory size minus one. If the computer has 64k words, then the memory unit
has 64*1024=65536 memory cells. The address of memory cells varies from 0 to 65535.
There are three types of memory:
1. Primary memory/main memory
2. Cache memory
3. Secondary memory

EXPLANATION:
1.4.1 Primary Memory/Main Memory
The primary memory holds the instructions and data on the computer when it is
working. It has limited capability to hold the data and when power is switched off all
the data is lost. The primary memory is made of semiconductor device. The primary
memory is again divided into two types, i.e., RAM, and ROM.

1.4.1.1 RAM (Random Access Memory)


Ram stands for Random Access Memory. It is
a temporary memory area/place in a computer
where application programs, operating system,
data are kept, so that they can reach to the
processor quickly. RAM reads and writes data
much faster than other storage devices like hard
disk drive, CD-ROM and floppy disk. In RAM,
data stays there until computer is working and
when the computer is turned off all data in RAM
is lost. When we turn on the computer again,
operating system, data and other files are loaded
Fig. 1.9 Block diagram of a RAM
into the RAM from the hard drive.

1.4.1.2 ROM (Read Only Memory)


ROM stands for Read Only Memory. It is a non-volatile and permanent memory. Non-
volatile means when power is off as data is not lost. ROM contains the programming
code and software instructions which starts the computer. It is helpful to booting.
Computer Fundamentals 7

1.4.2 Cache Memory


Cache memory is a memory which is used for retrieving data from memory faster. It
is placed between the CPU and the main memory. Without using cache memory when
CPU requests data to memory then and it sends back the result by using system bus
to CPU. If the same data is accessed multiple times then cache memory stores that
frequently used data. It responds faster to CPU.

Fig. 1.10 Block diagram of cache memory

1.4.3 Secondary Memory


Secondary memory is the permanent storage memory, i.e., it is a non-volatile memory.
It is the slowest and cheapest form of memory. The CPU cannot directly access the
secondary memory. First the required data accessed by CPU is copied to primary
memory, i.e., RAM, ROM and then CPU uses it. The examples of secondary memories
are: hard disk, floppy disk, CD, CDROM and magnetic tape.

1.4.3.1 Hard Disk


Hard disk is also known as disk drive, hard drive or
hard disk drive. It is a non-volatile memory hardware
device that stores and retrieves the data permanently.
For desktop the size of hard disk is 3.5” and for laptop
the size is 2.5”.A hard drive consists of one or more
platters to which data is written using a magnetic
Fig. 1.11 Block diagram of a
head. computer hard disk

1.4.3.2 Floppy Disk


A floppy disk consists of a thin, flexible magnetic disk
sealed in a square plastic carrier. To use the floppy disk
the computer system should have a floppy disk drive.
It is used to take the software, transfer files and create
back-up copies of the data.

1.4.3.3 CD
Fig. 1.12 Block diagram of
CD (compact disk) is a flat, round, small, portable, a computer floppy
round medium made of molded polymer for electronic disk
recording, storing and playing audio, video, text and
other information in digital form.
8 Concepts and Techniques of Programming in C

1.4.3.4 CD-ROM
CD-ROM stands for compact disk-read only memory is an optical disk which contains
audio or software data whose memory is read only.

Fig. 1.13 Block diagram of a computer CD-ROM

1.5 NUMBER SYSTEM REPRESENTATION


1.5.1 Decimal Representation
In our daily life we need the arithmetic operations therefore we use the decimal number
system. The decimal number system uses ten digits from 0 to 9 and the coefficients
are multiplied with by power of 10. Suppose the decimal number is 125 therefore it
represents as one hundred plus 2 tens plus 5 units. The thousand, hundred, ten, units
are power of 10 implied by the position of the coefficients. Precisely, this 125 number
is: 1*102+2*101+5*100.
To form a decimal number system there are 1’s form, 10’s form, 100’s form and so on.
The tabular form of decimal system is:

105 104 103 102 101 100


100000 10000 1000 100 10 1

Again to represent the number 201 in base 10 we know that the position of 1 is 1’s
column, the position 0 is 10’s column and position of 2 is 100’s column. The tabular
form of 201 whose base is 10 is given below.

102 101 100


2 0 1

In other words the number 203 whose base is 10 is 20310=2*102+0*101+3*100

1.5.2 Binary Representation


For computer arithmetic it uses the binary number system. The binary system uses two
symbols, namely, 0 or 1. The binary system is said to be of a base 2 because it uses two
digits and the coefficients are multiplied by power of 2. To build the binary number
system there are 1’s column, 2’s column, 4’s column, 8’s column, 16’s column and so
on. The tabular form of binary number system is given below:
Computer Fundamentals 9

28 27 26 25 24 23 22 21 20
256 128 64 32 16 8 4 2 1

Representation of the binary number 1111 is equal to 1*23+1*22+1*21+1*20= 8+4+2+1


=15 (decimal form). Binary form of decimal number 201 is:
201=128+64+8+1=27+26+23+20=11001001
The tabular form of 201 in binary representation is

27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
1 1 0 0 1 0 0 1

1.5.3 Octal Number System


In the octal number system there are only eight distinct counting digits starting from
0 to 7 with each digit having a weight or value starting from the least significant bit
8.The base 8 of octal number system represents number of individual numbers used in
the system, so the subscript 8 is used to identify a number expressed in octal. Example
of octal number is 238.
The representation of octal number is given below.

88 87 86 85 84 83 82 81 80
16M 2M 262k 32k 4k 512 64 8 1

Suppose the octal number 1238 and convert into decimal form.
1238=1*82+2*81+3*80=64+16+3=8310
We know that one octal digit or number is equivalent to 3 binary digits.

Decimal number Octal number 3-bit binary number

0 0 000
1 1 001
2 2 010
3 3 011
4 4 100
5 5 101
6 6 110
7 7 111
10 Concepts and Techniques of Programming in C

Suppose the octal number is again 1238 and then convert into binary form. Since
each octal number consists of 3 bits. Then from right side of number choose the 3-bit
form from the above table.
1238=(001 010 111)2

1.5.4 Hexadecimal Number System


This is the number system whose base 16, i.e., counting digits is 16. Starting from 0 to
15 and each number consists of 4 binary digits. The number looks like decimal number
up to the number 0 to 9 but instead of 10, 11, 12, 13, 14, 15 we can write A, B, C, D, E, F.

168 167 166 165 164 163 162 161 160


4.3G 2.6G 16M 1M 65K 4K 256 16 1

Decimal number Hexadecimal number 4-bit binary number

0 0 0000
1 1 0001
2 2 0010
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111

Suppose the hexadecimal number is 1D216 its is converted into binary numbers as:
1D216= (0001 1101 0010)2
The binary form of each hexadecimal digit consists of 4 bits.
Computer Fundamentals 11

1.6 PROBLEM SOLVING


1.6.1 Problem Solving Methods
The different types of problem solving methods are:
1. Understand the problem
2. Making the plan of solution
3. Carrying out the plan
4. Looking back, i.e., verifying

EXPLANATION:
1. Understanding the Problem
If a person does not understand the problem then he cannot solve it. And it is true
that if the person understands the problem definitely he can solve it. To understand
the problem one can extract the important features or part or points of the problem.

2. Making a Plan for Solution


Think about the principal part, i.e., unknown, data, conditions for finding the problem
and hypothesis and conclusion to prove the solution of the problem. After identifying
the principal part and understanding it one can find the facts related to the problem and
refine the facts to get relevant fact similar to the given problem. Lastly, search another
idea which is helpful for solving the same problem in a better way. Even an incomplete
idea should be considered. Go with the new situation and repeat the same process.

3. Carrying out the Plan


It means to continue the plan until you do not get result.

4. Looking Back, i.e., verifying


It means using reverse engineering to verify the solution process.

SUMMARY

1. A computer is an electronic device or machine which can accept data as input


and processes it to give expected output and store in a secondary storage unit
permanently.
2. The computer system which consists of different equipment or parts is called
hardware.
3. The computer program which tells the hardware what to do is called software.
4. Application software is a computer program designed for end users is called
application software, for example, Microsoft Office, Excel, Google Chrome,
Mozilla Firefox, Skype and others.
12 Concepts and Techniques of Programming in C

5. System software is a computer program designed to run computer hardware and


application programs is called system software.
6. The computer system consists of input devices, output devices, CPU and memory.
7. The CPU is the heart of a computer which contains electronic circuits that cause
the computer to follow instructions from ROM or RAM. The CPU consists of three
parts: a) arithmetic logic unit, and b) control unit.
8. RAM stands for Random Access Memory and it is volatile and when the power
is lost then data are deleted.
9. ROM stands for Read Only Memory and it is non-volatile, e.g., data stored is
permanent.

SHORT QUESTIONS

1. What is computer?
2. What is hardware?
3. What is software?
4. What is the difference between system software and application software?
5. What is input device and give its example?
6. What is output device and give its example?
7. What is memory?
8. Differentiate between RAM and ROM?
9. What are ALU and CU?
10. What is cache memory?

LONG QUESTIONS

1. Draw a basic computer block diagram and explain its functional parts.
2. What is memory and explain different types of memory?
3. What is secondary memory and explain different types of secondary memory?

MULTIPLE-CHOICE QUESTIONS

1. In digital computer data is represented as _______


(a) Hexadecimal form (b) binary form
(c) numerical form (d) octal form
[Answer: b]
2. Which of the following memory must be refreshed many times per second?
(a) RAM (b) ROM
(c) Dynamic RAM (d) EPROM
[Answer: c]
Computer Fundamentals 13

3. Which of the following is a secondary memory device?


(a) Disk (b) Keyboard (c) mouse (d) RAM
[Answer: a]
4. The two types of main memory are _________
(a) Primary and secondary (b) Random and sequential
(c) ROM and RAM (d) All of above
[Answer: c]
5. The brain of computer system is called _________
(a) ALU (b) Memory (c) CPU (d) Control unit
[Answer: c]
6. The basic operations performed by a computer are _________
(a) Arithmetic operation (b) Logical operation
(c) Storage and relative (d) All the above
[Answer: d]
7. The term gigabyte refers to _______
(a) 1024 bytes (b) 1024 kilobytes
(c) 1024 megabytes (d) 1024 gigabyte
[Answer: c]
8. Machine level language is _________
(a) Machine dependent (b) Difficult to program
(c) Error prone (d) All of above
[Answer: d]
2
Algorithm and Flowchart

2.1 INTRODUCTION
The word algorithm derives from the phonetic pronunciation of Arabic mathematician
Abu Jafar Mohammad ibn Musa al-Khowarizmi who invented a set of rules for doing
the arithmetic operations, e.g., addition, subtraction, division and multiplication on
decimal number systems. Thus, an algorithm is the formula or step-by-step methods
for solving a particular problem. Algorithms are used for the logical analysis of the
program.

2.1.1 Properties of Algorithm


Table 2.1 Properties of algorithm

1. Finiteness
It means the algorithm should stop in a finite number of steps.
2. Definiteness
Definiteness means each step of the algorithm should be clearly defined.
3. Input
The input of the algorithm is given by the user.
4. Output
The algorithm should have the correct output.
5. Effectiveness
Effectiveness means the algorithm to be developed using basic operations and it
should be complete in a finite amount of time by a person by drawing the paper and
pencil.

2.1.2 Advantages of Algorithm


1. Easy to develop the program.
2. Easy to convert into the program.
Algorithm and Flowchart 15

3. It gives step-wise procedure to refine the problem and get the solution. This
process is called iterative refinement.

2.1.3 Steps to Write a Complete Algorithm


1. Find the actual input-output of the problem.
2. Define the input data to be processed.
3. Processing the data, i.e., compute the data.
4. Write the complete algorithm.

2.1.4 Some Useful Algorithm Design Examples


1. Write the Algorithm of the Average of Three Integer Numbers. (Sequential
Algorithm)
Step 1: Start
Step 2: Declare the variables X, Y, Z, S and A
Step 3: Input the three numbers, i.e., X, Y, Z
Step 4: S=X+Y+Z
Step 5: A=(X+Y+Z)/3
Step 6: print A
Step 7: End
2. Write the Algorithm of Simple Interest Calculation. (Sequential Algorithm)
Step 1: Start
Step 2: Declare the variables P, R, T, SI
Step 3: Input the value of P, R, R
Step 4: SI= (P*R*T)/100
Step 5: print SI
Step 6: End
3. Write the Algorithm of Area and Perimeter of a Circle. (Sequential Algorithm)
Step 1: Start
Step 2: Declare the variables R, A and P
Step 3: Enter the radius R
Step 4: A=3.14*R*R
Step 5: P=2*3.14*R
Step 6: print A, P
Step 7: End
4. Write the Algorithm to Find Roots of a Quadratic Equation. (Sequential
Algorithm)
Step 1: Start
16 Concepts and Techniques of Programming in C

Step 2: Declare the variables A, B, C, X1 and X2


Step 3: Input the values of A, B, C
Step 4: X1= [-B+sqrt(B*B-4*A*C)]/2*A
Step 5: X2= [-B-sqrt(B*B-4*A*C)]/2*A
Step 6: print the roots X1, X2
Step 7: Stop
5. Write the Algorithm to Find Largest Among the Three Numbers using else-if
Statement. (Selectional/Conditional)
Step 1: Start
Step 2: Declare the variables X, Y and Z
Step 3: Input the three numbers, i.e., X, Y, Z
Step 4: if(X>=Y and X>Z)
Step 5: Print Z is greatest
Step 6: else if(Y>=X and Y>Z)
Step 7: print Y is greatest
Step 8: else if (Z>=X and Z>Y)
Step 9: print Z is greatest
Step 10: Stop
6. Write the Algorithm to Check Vowel or Consonant using if-else Statement.
(Selectional/Conditional Algorithm)
Step 1: Start
Step 2: Declare the variable X
Step 3: Input the character as input, i.e., X
Step 4: if(X==’a’ or X==’A’ or X==’e’ or X==’E’ or X==’i’ or X==’I’ or
X==’o’ or X==’O’ or X==’u’ or X==’U’)
Step 5: Print the character is vowel
Step 6: else
Step 7: Print the character is consonant
Step 8: Stop
7. Write the Algorithm to Check a Number is Even or Odd (Selectional/
Conditional)
Step 1: Start
Step 2: Declare the variable X
Step 3: Input the integer number
Step 4: if(X%2==0)
Step 5: Print “even number”
Step 6: else
Algorithm and Flowchart 17

Step 7: Print “odd number”


Step 8: Stop
8. Write the Algorithm of Exchange of Two Numbers using Third Variable
(Sequential)
Step 1: Start
Step 2: Declare the variables X, Y and Z
Step 3: Input the two numbers as input, i.e., X and Y
Step 4: Assign the value X into Z, i.e., Z=X; /*step3 to step5 is the logic of swap*/
Step 5: Assign the value of Y into X, i.e., X=Y;
Step 6: Assign the value of Z into Y, i.e., Y=Z;
Step 7: Print the value of X and Y
Step 8: Stop
9. Write the Algorithm of Exchange of Two Numbers without Third Variable
(Sequential)
Step 1: Start
Step 2: Declare the variables X and Y
Step 3: Input the two integer numbers as input, i.e., X and Y
Step 4: X=X+Y;
Step 5: Y=X-Y;
Step 6: X=X-Y;
Step 7: Print the two integer numbers X and Y
Step 8: Stop
10. Write the Algorithm for Calculating Fahrenheit to Celsius. (Sequential)
Step 1: Start
Step 2: Declare the variable Celsius, Fahrenheit
Step 3: Input the temperature in Fahrenheit
Step 4: Celsus=5.0/9.0* (Fahrenheit-32.0)
Step 5: Print the value of Celsius
Step 6: Stop
11. Write the Algorithm of Converting Celsius to Fahrenheit. (Sequential)
Step 1: Start
Step 2: Declare the variable Celsius, Fahrenheit
Step 3: Input the temp in Celsius
Step 4: Fahrenheit= (Celsius*9.0/5.0)+32.0
Step 5: Print the value of Fahrenheit
Step 6: Stop
18 Concepts and Techniques of Programming in C

12. Write the Algorithm to Convert Days to Months and Days. (Sequential)
Step 1: Start
Step 2: Declare the variable days and months
Step 3: Enter days as input
Step 4: months=days/30
days= days %30
Step 5. Print months, days
Step 6: Stop
13. Write an Algorithm to Find the Sum of the Digits of a Given Positive Integer
Number. (Iteration/Looping)
Step 1: Start
Step 2: input the integer number n
Step 3: sum=0
Step 4: while(n!=0)
Step 5: {
Step 6: reminder=n%10;
Step 7: sum=sum+reminder;
Step 8: n=n/10;
Step 9 :}
Step 10: Print sum
Step 11: Stop
14. Algorithm to Calculate the Factorial of a Number. (Iteration/Looping)
Step 1. Start
Step 2. Initialize the variable I=1, fact=1
Step 3. Read the integer number x
Step 4. Repeat step 4 through 6 until i<=x
Step 5. fact=fact*i
Step 6. i=i+1
Step 7. Print the value of fact
Step 8. Stop

NOTE: Generally, in writing the algorithm or drawing flowcharts, three types of


statements are used. They are sequential, selection and looping/iterations. Sequential
means the statements are executed in the same order as the programmer writes. Selection
means the statements of the program are executed based on conditions. Examples of
selection statements are if, if else, else if and switch statements. Iteration/looping means
sometimes the same statements are needed to execute a number of times. In that case
loop is used. Examples of loops are while, do while and for loop.
Algorithm and Flowchart 19

2.2 FLOWCHART
A flowchart is a diagrammatic/graphical representation of algorithm and it describes
the flow of the solution process. The solution process works by breaking up the problem
into smaller steps or sub/smaller problems and binds them to describe the flow. So
the last step of a flowchart gives the solution. Each step of the solution process is
represented by different symbols and contains the description of the processing steps.
The flowchart symbols are connected with arrow symbols displaying the process flow
direction. A flowchart shows the flow of data in a process and its operations in details
by a pictorial format. A flowchart can be called to drawing the blueprint of the building.
Flowcharts are used in designing, analyzing, documenting a process or the program
in various field.

When Flow Chart is Required?


In writing a small program if its logic is simple then flowchart is not required. But in
real-time problem, e.g., the project done by same company then flowchart is necessary.
Flowchart is briefly described as:
1. To plan the beginning of a new project.
2. Flowchart gives a clear understanding to the team members of the project to
identify the input and output and data collection to increase the efficiency of the
project.
3. It is useful for understanding the logic of the process.

2.2.1 Advantages of Flowchart


1. Effective Analysis: Using flowchart, problem can be analyzed in an efficient way.
2. Communication: It means flowcharts are best way of representing the logic of a
program.
3. Proper Documentation: Program flowcharts serve as documentation of the
program which is required for various purposes.
4. Efficient Coding: During systems analysis and program development phase,
flowchart plays the role of a guide or blueprint.
5. Proper Debugging: It helps in debugging the process.
6. Efficient Program Maintenance: The maintenance of operating program becomes
easy by using the flowchart.

2.2.2 Disadvantages of Flowcharts


There are a few disadvantages of using flowcharts:
1. Complex Logic: When the program logic becomes complicated, then the flowchart
becomes complex and clumsy.
20 Concepts and Techniques of Programming in C

2. Alterations and Modifications: When modifications/alternations are required


then flowchart may required drawing again completely.

2.2.3 The Symbols used for Drawing the Flowchart

1. Terminator

DESCRIPTION
The terminator symbol is visualized as oval symbol and it is used to start/begin
and stop/end of the flowchart.

2. Process

DESCRIPTION
The process symbol is visualized as rectangle to represent any single operation
in an algorithm. Generally, this operation is either a calculation or an assignment
statement. In calculation phase one or more inputs are converted into a result by
using either arithmetic or logical operations.

3. Input/output

DESCRIPTION
The input/output symbol is visualized as a parallelogram with text inside
indicating the type of input or output operation.

4. Decision

DESCRIPTION
The decision symbol is visualized as a diamond with text inside indicating the
condition to be evaluated.
Algorithm and Flowchart 21

5. Connector

DESCRIPTION
The connector symbol is visualized as a circle and it is used to connect to flow
line symbols on a logical path.
6. (Arrow/flow lines)
DESCRIPTION
The flow line symbol is visualized as a unidirectional arrow connecting to
flowchart items. Flow line symbol connects the various steps of the logical
process. A flowline symbol should be thought of a logical path between the steps
of a logical process.

2.2.4 Some Useful Flowcharts Examples


1. Draw Flowchart of Area and Circumference of a Circle. (Sequential Flowchart).

Start

Input
Radius R

Area=3.14*R*R
Circum=2*3.14*R

Print Area,
Circumference

Stop

Fig. 2.1 Area and circumference of circle


22 Concepts and Techniques of Programming in C

2. Draw the Flowchart for Finding the Average of Three Numbers. (Sequential
Flowchart)

Start

Input
X, Y, Z

SUM=X+Y+Z

AVG=SUM/3

Display
AVG

Stop

Fig. 2.2 Flowchart for finding average of three numbers

3. Find the Greatest Number between Two Integer Numbers (Selection Flowchart)

Start

Input X, Y

X>Y

Print X Print Y

Stop

Fig. 2.3 Flowchart for finding the greatest number between two integer numbers
Algorithm and Flowchart 23

4. Draw a Flowchart to Find the Largest among Three Numbers X, Y, and Z.


(Selection Flowchart)

Start

Input X, Y, Z

True False True


Is Is Is
Y>Z? X>Y? X>Z?

False Yes

Print Y Print Z Print X Print Z

Stop

Fig. 2.4 Flowchart of the greatest number between three numbers

5. Draw the Flowchart to Find the Roots of a General Quadratic Equation.


(Sequential Flowchart)

Start

Input
A, B, C

D = sqrt (B*B-4*A*C)

X1 = (-B+D)/(2*A)

X2 = (-B–D)/(2*A)

Display
X1, X2

Stop

Fig. 2.5 Flowchart displaying the roots of a quadratic equation


24 Concepts and Techniques of Programming in C

6. Draw a Flowchart to Print the Sum of the Digits of a Given Number. (Iteration/
Looping Flowchart)

Start

Sum=0

Input N

False
N!=0?

True

Remainder=N%10

Sum=Sum+Remainder

N=N/10

Display
sum

Stop

Fig. 2.6 Flowchart for finding the sum of digits of an integer number
Algorithm and Flowchart 25

7. Draw the Flowchart of Factorial Value of a Number. (Iteration Flowchart)

Start

Input
num

I=1
Fact=1

Is False
I<=Num
?

True

I=I+1

Fact=Fact*I

Print
fact

Stop

Fig. 2.7 Flowchart for finding factorial of a number


26 Concepts and Techniques of Programming in C

8. Draw the Flowchart of the Number is Even or Odd. (Selection Flowchart)

Start

Declare num

Input
num

Is False
nium%2==
0?

True Print
odd

Print
even

Stop

Fig. 2.8 Flowchart for checking the number is even or odd


Algorithm and Flowchart 27

9. Draw the Flowchart for Checking the Number is Armstrong Number or Not.
(Iteration Flowchart)

Start

Read num,
sum=0

X=num

Is False
num>=1?

True
R=X%10

Sum=Sum+(R*R*R*)

Num=Num/10

True Is False
X==Sum

Display Display
num is num is not
armstrong armstrong

Stop

Fig. 2.9 Shows to check the number is Armstrong number or not


28 Concepts and Techniques of Programming in C

10. Draw the Flowchart of Converting Fahrenheit to Celsius. (Sequential


Flowchart)

Start

Input Fahrenheit

Celsius=5.0/9.0(Fahrenhit-32.0)

Display Celsius

Stop

Fig. 2.10 Flowchart for conversion of Fahrenheit to Celsius

11. Draw Flowchart of Celsius to Fahrenheit. (Sequential Flowchart)

Start

Input Celsius

Fahrenheit=
(Celsius*9.0/5.0)+32.0

Display
Fahrenheit

Stop

Fig. 2.11 Flowchart for conversion of Celsius to Fahrenheit


Algorithm and Flowchart 29

12. Draw The Flowchart of Exchange Two Integer Numbers using Third Variable.
(Sequential Flowchart)

Start

Input X, Y

X=X
X=Y
Y=Z

Display X, Y

Stop

Fig. 2.12 Flowchart for swapping two integer numbers using third variables

13. Draw Flowchart of Exchange Two Integer Numbers without using Third
Variable. (Sequential Flowchart)

Start

Input X, Y

X=X+Y
X=Y–Y
Y=Z–Y

Display X, Y

Stop

Fig. 2.13 Flowchart for swapping two integer numbers without the third variable
30 Concepts and Techniques of Programming in C

Summary

1. Algorithm was developed by Abu Jafar Mohammed ibn Musa al-khowarizmi.


2. The properties of algorithms are finiteness, definiteness, input, output,
effectiveness.
3. The advantage of algorithms is easy to develop the program.
4. Flowchart is a pictorial representation of algorithm.
5. It consists of different symbols to represent the algorithm.
6. The advantages of flowchart are communication, proper documentation, efficient
coding, proper debugging, and efficient program maintenance.

Short Questions

1. What is algorithm?
2. Why is algorithm required?
3. What are the advantages and disadvantages of algorithm?
4. What is flowchart?
5. What are the advantages and disadvantages of flowchart?

Long Questions

1. Write the algorithm and flowchart of converting decimal to binary number using
looping.
2. Write the algorithm and flowchart of multiplication of digits of an integer number.
3. Write the algorithm and flowchart of factorial of a number using recursion.
4. Write the algorithm and flowchart of Fibonacci series.
5. Write the algorithm and flowchart of checking palindrome.
6. Write the algorithm and flowchart of finding the roots of a quadratic equation
using if else statements.
7. Write the algorithm and flowchart of a leap year.
8. Write the algorithm and flowchart to find the prime numbers between the input
m and n.
9. Write the algorithm and flowchart of GCD of two integer numbers using recursion.

Multiple-Choice Questions

1. The diamond symbol used in flowcharts is called ________


(a) Decision making box (b) Statement box
(c) Error box (d) if-statement box
[Answer: a]
Algorithm and Flowchart 31

2. The rectangle with the horizontal lines on two side’s symbol in a flowchart is
used for ________
(a) Defined statements (b) Predefined process
(c) Error fix (d) Variable defined
[Answer: b]
3. The connectors or link with another part of the program in a flowchart is
represented as_____________
(a) Rhombus (b) Parallelogram
(c) Circle (d) Trapezoid
[Answer: c]
4. The part of algorithm which is repeated for a fixed number of times is called
______________________
(a) Iteration (b) Selection
(c) Reverse action (d) None of the above
[Answer: a]
3
C Programming

3.1 Introduction
C program is a structured, high level and machine independent language. The structured
oriented programming means it divide a larger problem in top down manner as
smaller modules which are called functions or procedures and each of the function
does its own calculation. The structured programming uses three control statements
sequence, selection and iteration or looping. It restricts the use of GOTO statement.
High level language means it is a language which is written in English language.
Machine independent language means the language which can run in any platform
(operating system) with small modification or no modification.
C programming language was developed from the disadvantages of ALGOL, BCPL
and B programming language. It was developed by Dennis Ritchie at Bell Laboratories
in 1972. The C programming language uses the concepts of data types and many
additional features. Preliminarily C programming language was associated with UNIX
operating systems. Because UNIX operating system was developed by using the C
programming. The ALGOL was the first computer programming language introduced
in 1960. Then BCPL (Basic Combined Programming Language) was written by Martin
Richards in 1967. In 1970 B programming language was developed by Ken Thompson
which was the improved version of BCPL. Then C programming language came
in 1978 by Brian Kerningham and Dennis Ritchie. Then ANSI C came in 1989 by
American National Standard Institute (ANSI). In 1990, C++ programming language
came based on C programming with a number of changes called a true object-oriented
programming. The applications of C programming languages are development of
Operating Systems, Compilers, Assemblers, Text Editors, Print Spoolers, Network
Drivers, Modern Programs, Databases, Interpreters, etc.
C Programming 33

ALGOL programming BPCL programming B programming


language language language

C programming
language

Fig. 3.1 Evolution of C programming language

Table 3.1 Programming languages and their inventors

Sl No. Inventor Year Programming Language


1 International Group 1960 ALGOL
2 Martin Richards 1967 BCPL
3 Ken Thomson 1970 B
4 Dennis Ritchie 1972 C

3.1.1 Features of C Programming Language


1. Portability: The C programming is a portable language because it can be run by
any compiler with small or no modification in different operating systems.
2. Powerful: The C programming is powerful because it provides variety of data-
types, functions and decision making and looping statements.
3. Reliability: The C programming is a reliable language because it increases the
portability of the program.
4. Modularity: The C programming is modular programming because a larger
program is divided into smaller program and then integrated these solved smaller
ones into one complete program.
5. Flexibility: The C programming is a flexible language because the programmer
can control that language. There are 32 reserved keywords through which a
programmer can control the usages of language and modify the structure of the
program.

3.2 GENERAL TERMS A PROGRAMMER SHOULD KNOW


BEFORE WRITING ANY PROGRAM
3.2.1 Instruction
Instruction is the set of commands given to the computer to perform some specific task.
34 Concepts and Techniques of Programming in C

3.2.2 Program
Program is the set of instructions.

3.2.3 Software
Software is the set of programs.

3.2.4 High Level Language


It is a machine independent language. High level languages are generally English-
like language. It is easy to write and understand. Examples are FORTRAIN, COBOL,
BASIC, C , C++, Java, C# , small talk, etc.

3.2.5 Low Level Programming Languages


Machine level languages and assembly level languages are low level programming
languages. Machine level language means binary languages, i.e., 0 and 1 that the
computer only understands. Writing machine level languages is difficult because it is
not easy to write programs using binary code.
Assembly level language is the modified version of machine level language. In
assembly level language instructions are written in English like words ADD, MOV and
SUB, etc. It is easy to write and understand assembly level language.

3.2.6 Compiler
A compiler is a system software which is used to translate the entire program written
in high level language into machine language. The basic work of a compiler is detecting
the syntax errors in the entire program if any; otherwise it translates into object file.
When compiling the entire program its runtime increases and occupies large amount
of memory space and its execution speed becomes slow. Because the compiler compiles
the entire program at a time and converts it into the machine code only once. If a
compiler runs on a computer and produces the machine code for the same computer
then it is called a self compiler. If a compiler runs on a computer and produces the
machine code for some other computer then that compiler is called a cross compiler.

3.2.7 Interpreter
The interpreter is the system software which is used to execute the entire programming
statements by interpreting line by line. The interpreter does not check the error in the
entire program once at a time but it would interpret line by line multiple times. We can
again say that it reads one statement at a time and translates it into machine code and
executes it. Then it reads next statement of the program and translates it to machine
code and executes until it reaches the end of the program.
C Programming 35

3.2.8 Assembler
Assembler is a system software which is used to translate assembly level language
into machine level language. The assembler is classified into two types, i.e., one pass
assembler and two pass assemblers. In one pass assembler memory address is assigned
to the variables and it translates the source code to the machine code in the first pass
simultaneously. But in two-pass assembler which reads the source code two times,
i.e., in the first pass, it reads all the variables and creates the memory location. In the
second pass, it reads the source code and translates the source code into object code.

3.2.9 Linker
Linker is the last step of the compilation process. It links the object file with library
function to create .exe file. The library file is the predefined functions which are
essential for executing the program. If the linker does not find the library functions used
in the source program then it informs the compiler and generates an error. Example of
linking error is variable or function is used, but not defined anywhere in the program.

3.2.10 Loader
Loader is the part of the operating system that loads the machine codes of a program
into the system memory and brings the execution file from system memory into
primary memory (e.g. RAM) and starts it running.

3.2.11 Source Code


The source codes are the programming codes that are written in English type language
by the programmer by using a text editor and then saved in a file with their extension.

3.2.12 Object Code


When the source code gets compiled with a C compiler and the resulting compiled file
is called object file. The object code file which contains the sequence of instructions that
the pre-processor can understand.

3.2.13 Executable Code


An executable file is a computer program which contains machine code, i.e., 1’s and 0’s
from the instruction that can be run directly by an operating system. The file consists of
table of contents, a number of code blocks and data blocks. The operating system can
run an executable file or less by loading blocks of code and data at the indicated address.

3.2.14 Operating System


The operating system is the software which coordinates all the hardware and software
on the computer. Suppose there are many programs running at the same time and
36 Concepts and Techniques of Programming in C

they all need to access the CPU, memory and storage in that case the OS coordinates
all of these. All modern operating systems are graphical user interface. In GUI user
can choose any icon on the desktop using mouse. The examples of OS are Microsoft
Window xp, Window 7, Window 8 and other higher versions, Linux, Google android.
The applications of OS are:
1. It manages the sharing of internal memory among multiple applications.
2. It supports multitasking which means that multiple programs can run
simultaneously (at the same time). In that case the OS determines which program
will run in what order and how much time it will take before allowing the other
application program.
3. It manages input and output to and from attached hardware device, i.e., hard
disks, printers, etc.
4. It can send information to each application program about error that may have
occurred.

3.3 TYPES OF ERRORS IN C PROGRAMMING


3.3.1 Syntax Error
A syntax error is an error which is detected in the source program. Generally, syntax
errors are the common grammatical mistakes done by the programmer and are identified
during compilation process of a program. Examples of syntax errors are: missing
comma among variables, missing semicolon at the end of a line or extra bracket at the
end of a function may create a syntax error.

3.3.2 Runtime Error


The runtime error is an error occurring while executing a program. The different types
of runtime errors are: overflow, divide by zero, memory errors and uninitialized data
access. Overflow means numeric calculation produces the result which is too large.
Divide by zero means dividing a numeric value by zero. Memory errors means to access
a memory which produces undefined result, i.e., array outside its bound. Uninitialized
data access means accessing memory before the memory has been initialized.

3.3.3 Logical Error


Logical errors are difficult to find and fix in a program because there is no indication of
a error. Again we are told that in logical error programming, programs run successfully
but do not give the output of the program correctly. The causes of logical errors are:
writing a program without understanding the logic of the program. Some beginner
carelessly wrote the program and made mistake.
C Programming 37

3.4 LOGICAL STEPS for WRITING A PROGRAM


Before writing any program the programmer should:
1. Understand/define the problem and then solve it. The problem is a puzzle that
requires logical thought or mathematics to solve it.
2. Then he has the problem solving skill. Problem solving is the act of defining a
problem; determining its cause; identifying, prioritizing and selecting alternative
solution; and implementing that solution. The problem solving process is a
creative work.
3. Then select a method to solve the problem. The different methods to solve the
problem are Heuristic (straight line), greedy and divide and conquer. The better
method among the two is divide and conquer because if the problem is complex
then this method divides the logic of the problem into sub-problems and then
solves each sub-problem individually and combines all the sub-problems to a
final solution of the problem.
4. Then designing the solution. It means to write the algorithm and draw the
flowchart.
5. Then develop the solution. It means to write the complete program.
6. Test the solution for its correctness. After writing the program, the programmer
should check that it gives the expected output or not.
From the above six steps we have learnt how the logical steps work for writing a
program.

SUGGESTION
Overall, if the programmer knows the logic of the problem then he/she can easily write
any program.

3.5 HOW TO WRITE A SIMPLE C PROGRAM


/*************************************************************************
FILE NAME: sample.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTE: 31/7/2015
NAME OF THE PROGRAM: C program to print I LOVE MY INDIA.
*************************************************************************/
#include<stdio.h> /*link section*/
void main(void) /*main function*/
{
printf(“I LOVE MY INDIA”);
}

Output:
I LOVE MY INDIA
38 Concepts and Techniques of Programming in C

EXPLANATION:
From the above program we find the format for writing a C program.
(a) The first line is called comment line statement e.g. /*****/ which holds or
contains different pieces information about the program, e.g., name of the file
with their extension name, name of the program, name of the author, date on
which the program was executed and name of the files with their extension
names. The comment line is optional to write a program. It only gives the
information about the programming details to the unknown person. You can
write comments in between the /* */ starting asterisk and end asterisk.
/*******************************************************************
FILE NAME: simple(program name).c
AUTHOR DETAILS: Write Full Name, Semester, Branch Name, Your College
Name, Place.
DATE OF PROGRAM EXECUTE: 31/7/2015
NAME OF THE PROGRAM: simple C program
*******************************************************************/

In the above comment line the FILE NAME may be given by your name
(only first name not full name) with extension.c e.g. suppose my name is
Dhabal Prasad Sethi so we can give the file name as dhabal.c and do not write
dhabalprasadsethi.c. Alternatively, the file name may be given as program
name, i.e., simple.c and do not write simpleprogram.c.
(b) The second line #include<stdio.h> is called a preprocessor directive, which
tells or gives data (or information) to the C compiler to include the standard
input output (e.g. “stdio.h”) file with the programming statements written in
the editor before compilation of the program.
(c) Third line void main () is called the entry point of the C program (e.g. where the
program execution starts and it does not return any value, since void keyword
is used).
(d) Fourth line { (left curly brace) indicates it is the start of the main function.
(e) Fifth line printf(“I LOVE MY INDIA”); The printf statement is used to display
the message on the computer screen and the message is generally written
in between the double quotes of printf function. The double quotes are not
displayed on the computer screen and it only helps to display the output
(message).
(f) Sixth line (right curly brace) } is called the end/stop of the main function
program execution.
C Programming 39

TIPS TO REMEMBER
1. If arguments (e.g. int argc, char** argv) are passed inside the main() function.
It is called command line arguments. A good programmer always uses these
arguments. It is optional, i.e., you may or may not use the int argc, char** argv
as an argument.
Example:
void main(int argc, char** argv) { }
2. printf(“ ”); function is used to display the message where scanf(“ ”); function is
used to take input from the keyboard and stored in a variable.

The above programs are tested under Turbo c4.5 editor. If you want to write the
above program in Turbo C editor then type the program as
/*************************************************************************
FILE NAME: simple.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA.
DATE OF PROGRAM EXECUTE: 31/7/2015
NAME OF THE PROGRAM: simple C program
*************************************************************************/
#include<stdio.h>
#include<conio.h>
int main(void)
{
clrscr();
printf(“I LOVE MY INDIA”);
getch();
return 0;
}

Output:
I LOVE MY INDIA

EXPLANATION:
Here #include<conio.h> is a header file which is used for clrscr(); and getch(); function.
The clrscr(); function is used for clearing the screen. Generally, when a program is
written and after executing, it will display the output on the screen and again when
write the another program and run it. After running, it will display the previous output
along with the current output. So to remove previous output clrscr() is used. The benefit
of other function getch() ; is that when we press any key from the keyboard we will
see the next line but won’t see the key which is pressed. After displaying the output
window when any key is again pressed it will close the window.
40 Concepts and Techniques of Programming in C

TIPS TO REMEMBER
If you are using Turbo C editor for writing C program then you may write
#include<conio.h> after #include<stdio.h> and use clrscr(); and getch(); function
inside the main()function for normal program execution. If you are using Turbo
C4.5 editor or other higher version editor it is not mandatory to use clrscr(); and
getch();function inside the main() function and #include<conio.h> header file. Its
uses is optional.

3.6 DIFFERENT WAYS TO WRITE THE main ( ) FUNCTION


Whenever a programmer wants to write a program he chooses any one entry point
from the list.
1. /* Entry point main() function uses */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
}

Output:
I AM DHABAL PRASAD SETHI

EXPLANATION:
In the above program the entry point is main function. The empty parenthesis shows
that there is no parameter.
2. /* Entry point int main() function uses */
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
return 0;
}

Output:
I AM DHABAL PRASAD SETHI
C Programming 41

EXPLANATION:
In the above program the entry point is int main() function therefore int before main()
function shows that the function returns an integer type value to the operating system.
When int is used before the main function then we should write return 0; at the end
of the program.
3. /*Entry point void main() function uses */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
}

Output:
I AM DHABAL PRASAD SETHI

EXPLANATION:
In the above program the entry point, void main(), shows that the keyword void before
main function indicates the function does not send replay any value to the operating
system.
4. /* Entry point main(void) function uses */
#include<stdio.h>
#include<conio.h>
main(void)
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
}

Output:
I AM DHABAL PRASAD SETHI

EXPLANATION:
In the above program the entry point, void inside the parenthesis of main function,
shows that nothing is passed as an argument.
5. /* Entry point void main(void) function uses */
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
42 Concepts and Techniques of Programming in C

printf(“I AM DHABAL PRASAD SETHI”);


getch();
}

Output:
I AM DHABL PRASAD SETHI

EXPLANATION:
In the above entry point void main(void) void indicates no value returns to OS with
no argument is passed as an argument.
6. /* Entry point int main(void) function uses */
#include<stdio.h>
#include<conio.h>
int main(void)
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
return 0;
}

Output:
I AM DHABAL PRASAD SETHI

EXPLANATION:
In the above entry point, int main(void) means int before main()shows, it returns a
value to OS and void inside the parenthesis shows that no argument is passed as an
argument.

3.7 BASIC STRUCTURE OF C PROGRAM


Line 1:
Document part
Line 2:
Linking part/preprocessor directive
Line 3:
Definition part
Line 4:
Global Declaration part
Line 5:
Function prototype part
Line 6:
main() function part
{
Declaration section
Executable section
}
Line 7: Subprogram part/user-defined functions
{
Local variable declaration;
Function statements;
Return statement;
}
C Programming 43

EXPLANATION:
Line 1: The document part is the comment line part and it contains the details about a
program, i.e., program name, program name with their extension, name of the author,
date on which program is executed by author.
Line 2: The link part gives information to the compiler to link the functions used in the
program from C library. Generally, header files are included in this link part.
Line 3: The definition part is to define the symbolic constant.
Line 4: The global declaration part is the declaration of global variable.
Line 5: The function prototype part gives the details about a function to the compiler,
i.e., return type, function name and parameter list, etc.
Line 6: In each C program the programmer must define one main() function and this
is called the entry point of a C program . The declaration part and execution part
inside the main function indicate the declaration of variables and later these variables
are used for execution. In each C program there should be minimum one statement for
execution. Program execution should start with opening brace and stop by using the
closing brace. The opening and closing braces generally are the logical opening and
stop of the main function. The declaration statements and executable statements of a
C program always end with a semicolon.
Line 7: The alternative name of subprogram part is the user-defined part/function part
and it is called from the main function. These user-defined functions are placed after
the main function or before the main function. If it is placed before the main function
then the function declaration does not require else it requires to declare the function.

TIPS TO REMEMBER
Before writing the complete C program, the programmer should know a preprocessor
directive? main function, variables, constant, data types, local variable, global
variable, functions. Some are described in this chapter and others are described in
next chapter.

/***********************************************************************
FILE NAME: x.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c basic program example
***********************************************************************/
#include <stdio.h> /* Link section */
#include<conio.h>
int x,y,z; /* Global declaration and definition section */
int mul(int p, int q); /* Function declaration(function prototype) section */
44 Concepts and Techniques of Programming in C

void main (void) /* Main function */


{ /*program execution starts*/
printf (“This is the examples of basic structure of c program \n”);
clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&y,&z);
x=mul(y,z);
printf(“Multiplication of inputted two integer numbers is :%d”,x);
getch();
} /*program execution ends*/

int mul(int p,int q) /* User defined function(function definition section) */


{
return(p*q);
}

Output:
This is an example of basic structure of C program
Input the two numbers: 4 6
Multiplication of inputted two integer numbers is: 24

3.8 STEPS OF WRITING A C PROGRAM USING EDITOR


3.8.1 If You Want to Execute using Turbo C Editor
Executing a C program consists of a number of steps:
(a) Step 1 consists of creating the program by following the sub-steps
1. Double click the editor
2. From menu click the new
3. Write the program name with the extension .c
4. Save it
(b) Writing the complete program and save it again.
(c) Compile it using ALT +F9.
[If some errors are there then correct these. Compilation errors are common
mistakes, e.g., not given semicolon at the end of each statement; not giving comma
in each variable; invalid keyword; mismatch data types and so on. Compilation
error means syntax error. Logical error means the steps of solving a problem are
not correct.]
(d) Link the program with library functions (e.g., stdio.h, conio.h, math.h, etc.) to
create exe file by using the keyword CTR +F9
(e) Display the output using keyword ALT +F5
C Programming 45

3.8.2 If You Want to Execute using Turbo C 4.5 Editors


(a) Double click the editor
(b) Click the menu of editor and select new
(c) Write the complete program
(d) Save it with extension .c
(e) Go to debug button and click it and see the result.

3.9 DIAGRAMMATIC REPRESENTATION OF INTERNAL STRUCTURE OF


C PROGRAM EXECUTION

Source program
(x.c)

Preprocessor directive

Expanded source
program (x.i)

Compiler

Assembly program
(x.asm)

Assembler

Object code Library


function

Linker

Executable code (x.exe)

Fig. 3.2 Translation process of a program


46 Concepts and Techniques of Programming in C

1. Source Program
While writing a C program the language used in the editor is called the source program
(code) and after writing it, again it is stored as x.c. Then it is further expanded by the
preprocessor directive, e.g., #include and stored in the intermediate code with the file
extension. i, example: x.i. The expanded source program x.i is the C language. The
extension .i varies from compiler to compiler.

2. Role of Complier
The compiler then finds out the syntax error, i.e., comma (,), semicolon (;) etc, of
the expanded source code. If the expanded source code/program is an error-free
program then the role of the compiler is to convert the expanded source program into
assembly programming language. The assembly programming language is stored with
an extension .asm in the file e.g. x.i is converted into x.asm.

3. Role of Assembler
The assembler converts the source code x.asm into x.obj file. The object file is the
combination of machine instruction, data and information and it is required to place
in proper place of the memory.
The format of object file is

Table 3.2 Format of object file

Object file Text Data Relocation Symbol Dubbing


header segment segment information table information

The object file header describes the size and position of the other pieces of the
file. Text segment holds the machine instructions and it is same as expanded source
program. Data segment holds binary representation of data in assembly file. Relocation
information identifies instructions and data that depend on absolute addresses. Symbol
table associates addresses with external labels and lists unresolved references.

4. Role of Linker
The linker links the object code with library function to form exe file. Generally, the
linker detects the errors like miss spelled library function name in the source program.
If the linker does not find the error then it searches the memory locations that code from
each module will occupy and relocates its instructions by adjusting absolute reference.

5. Role of Loader
When .exe file is created then it is stored in the hard drive and it is ready for execution.
When a beginner executes it, at that time the operating system is brought from the
C Programming 47

hard drive into RAM called program loader. The program loader places the .exe file
any vacancy locations in the drive.

3.10 COMMON MISTAKES THE BEGINNER DOES AND ITS CORRECTION


1. Wrong: Some beginners give the semicolon at the end of while loop and for loop.
Correct: It is not required.
Example:
Wrong
a) while(x<=10);
{
}
b) for(int i=0;i<10;i++);
{
total=total+i;
}
Correct
a) while(x<=10)
{
}
b)
for(int i=0;i<10;i++)
{
total=total+i;
}
2. Wrong: Did not give semicolon at the end of the each statement.
Correct: Every C program statement should end with a semicolon.
Example:
Wrong
int x,y
Correct
int x,y;
3. Wrong: In function definition user gives semicolon at the end of function header.
Correct: But it is not required.
EXAMPLE:
Wrong
int add(int x,int y); ----Æfunction header
{
int z=x+y;
}
Correct
int add(int x,int y)
{
int z=x+y;
}
48 Concepts and Techniques of Programming in C

4. Wrong: Use & operator in printf function but do not use in scanf function.
Correct: Do not use “& “operator in printf statement but use “&” in scanf function.
Example:
Wrong
scanf(“%d”,x);
printf(“%d”,&x);
Correct
scanf(“%d”,&x);
printf(“%d”,x);
5. Wrong: The comment line starts with /* and should not end properly.
Correct: Every comment line should start with /* and end with */. All the statements
about a program are written inside the given symbol.
Example:
Wrong
/* my first c program
Correct
/*my first c program*/
6. Wrong: The programmer gives semicolon in function definition but does not give in
function declaration.
Correct: The programmer should not give semicolon in function definition but should
give in function declaration.
7. Wrong: In reading the string by using scanf(); function, the programmer uses &
operator.
Correct: Do not use & operator in reading the string by using scanf(): function.

TIPS TO REMEMBER
Students should ensure that printf(); function is used to print the value or message,
scanf();function is used to take data values through keyboard or read data values
through keyboard and both functions, header file is #include<stdio.h>. The stdio.h
stands for standard input output dot header.

3.11 USEFUL C PROGRAMING EXAMPLES WITHOUT


USING CONTROL STATEMENT
The following programs are tested under Turbo C4.5 editor. Here #include<conio.h>
header file is placed after #include<stdio.h> along with clrscr();and getch(); is placed
inside the main() function. If we do not want to use the above clrscr();, getch(); and
#include<conio.h>mentioned functions in Turbo C4.5 editor then it does not affect the
normal program execution. If you are using other editor then check whether the above
discussed header file and other functions are essential or not.
C Programming 49

TIPS TO REMEMBER
Sometimes after running the programs if the output is infinite and we do not stop
that program then try to use the keyword: CTR + BREAK.

Q1. C Program to Convert Days to Months and Days.


Solution:
/*************************************************************************
FILE NAME: prog1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to convert days to months and days
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,y;
clrscr();
printf(“Input the number of days:”);
scanf(“%d”,&y);
x=y/30;
y=y%30;
printf(“The conversion of days into months and days is:%d months and %d
days”, x, y);
getch();
}
Output:
Input the number of days: 100
The conversion of days into months and days is: 3 months and 10 days
EXPLANATION:
Here in this program the user enters the number of days 100 through scanf(); function
then applying the logic gets the output, i.e., x= 100/30=3 months because in division
the result is the dividend part and hence, y= 100%30=10 days because the result is the
remainder part.
Q2. C Program to Calculate the Area and Perimeter of a Circle.
Solution:
/*************************************************************************
FILE NAME: prog2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to calculate the area and perimeter of a
circle
*************************************************************************/
50 Concepts and Techniques of Programming in C

#include<stdio.h>
#include<conio.h>
#define PI 3.14 /*symbolic constant*/
void main(void)
{
float x, y, z;
clrscr();
printf(“Input the radius of circle:”);
scanf(“%f”, &x);
y=PI*x*x;
z=2*PI*x;
printf(“The area of circle is:%5.2f\n”, y);
printf(“The perimeter of circle is:%5.2f”,z);
getch();
}

Output:
Input the radius: 2.0
The area of circle is: 12.56
The perimeter of circle is: 12.56

EXPLANATION:
Here the user input the radius as 2.0 .Then apply the formula to find the area of the
circle e.g. formula is 3.14*radius*radius and to find the perimeter of the circle the
formula is 2*3.14*radius. Here x is declared radius and instead of 3.14, PI is used which
is called symbolic constant. Here symbolic constant is used because 3.14 is used two
times to avoid typing exact value of 3.14 programmer gives a name PI which is called
symbolic constant. So first PI is multiplied with radius two times and the results is
stored in y and then to find perimeter 2 is multiplied with PI and x. The result of the
perimeter is stored in z and last prints the y and z to get the result.
Q3. C Program to Calculate the Area and Perimeter of a Rectangle.
Solution:
/*************************************************************************
FILE NAME: prog3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to calculate the area and perimeter of a
rectangle
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x,y,z,m;
clrscr();
C Programming 51

printf(“Input the length, breadth of a rectangle:”);


scanf(“%f%f”,&x,&y);
z=x*y;
m=2*(x+y);
printf(“The area of rectangle is:%5.2f\n”, z);
printf(“The perimeter of rectangle is:%5.2f”,m);
getch();
}

Output:
Input the length and breadth of a rectangle: 3.0 2.0
The area of rectangle is: 6.0
The perimeter of rectangle is: 10.0

EXPLANATION:
Here the user input length and breadth of a rectangle through scanf() function and
the variable x is taken as length and y as breadth. To find the area of a rectangle the
formula is length*breadth and to find the perimeter of the rectangle the formula is
2*(length +breadth).Therefore, x is multiplied with y and the result is stored in variable
z. Then to find the perimeter multiply 2 with sum of length and breadth e.g2*(x+y) and
the result is stored in variable m. Lastly print the variable z and m to get the results.
Q4. C Program to Convert Temperature in Fahrenheit to Celsius.
Solution:
/*************************************************************************
FILE NAME: prog4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to convert temperature in Fahrenheit to
Celsius
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x,y;
clrscr();
printf(“Input the temperature in Fahrenheit :”);
scanf(“%f”,&x);
y=5.0/9.0*(x-32.0);
printf(“The conversion of temperature in Fahrenheit to Celsius is:%5.2f”,y);
getch();
}

Output:
Input the temperature in Fahrenheit: 98
The conversion of temperature in Fahrenheit to Celsius is: 36.67
52 Concepts and Techniques of Programming in C

EXPLANATION:
To find the Celsius the formula is 5.0/9.0*(farenhit-32.0) and in the printf() statements
%5.2f means it is the formatted out e.g. the output will be displayed in a fomat.5.2f
means the length of the output is 5 memory locations and after dot there will be 2
decimal memory locations. e.g. 36.67 is stored in the form shown below.

3 6 . 6 7

Q5. C Program to Convert Temperature in Celsius to Fahrenheit.


Solution:
/*************************************************************************
FILE NAME: prog5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to convert temperature in Celsius to
Fahrenheit
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x,y;
clrscr();
printf(“Input the temperature in Celsius :”);
scanf(“%f”,&x);
y=(x*9.0/5.0)+32.0;
printf(“The conversion of temperature in Celsius to Fahrenheit is:%5.2f”,y);
getch();
}

Output:
Input the temperature in Celsius: 37
The conversion of temperature in Celsius to Fahrenheit is: 98.60

EXPLANATION:
Here the user enters the Celsius and to define the formula of converting the Celsius
to Fahrenheit, i.e., Fahrenheit = (Celsius*9.0/5.0)+32.0 and in the last printf function
displays the Fahrenheit.
Q6. C Program to Compute the Sum and Average of Three Integer Numbers.
Solution:
/*************************************************************************
FILE NAME: prog6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
C Programming 53

DATE OF PROGRAM EXECUTION: 31/7/2015


NAME OF THE PROGRAM: c program to compute the sum and average of three
integer numbers
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,y,z;
clrscr();
int sum;
float avg;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
/*mathematical calculation of sum and average*/
sum=x+y+z;
avg=sum/3;
printf(“The sum of inputted three integer numbers is:%d\n The avg
is:%f”,sum,avg);
getch();
}

Output:
Input the three integer numbers: 2 3 4
The sum of input three integer numbers is: 9
The avg is: 3.000000

EXPLANATION:
In the above program the user entered three integer numbers 2, 3 and 4 then sum
variable stores the results and then divides the sum into 3 and stores the result in avg
variable then print that value.
Q7. C Program to Swap/Exchange Two Numbers using the Third Variable.
Solution:
/*************************************************************************
FILE NAME: prog7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to swap/exchange to numbers using third
variable
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
54 Concepts and Techniques of Programming in C

int x,y,z;
clrscr();
printf(“Input the two integer numbers to be swapped:”);
scanf(“%d%d”,&x,&y);
/*logic of swapping two integer numbers using third variable*/
z=x;
x=y;
y=z;
printf(“After swapping/exchanging the two integer numbers are:%d %d”,x,y);
getch();
}

Output:
Input the two integer numbers to be swapped: 5 6
After swapping/exchanging the two integer numbers are: 6 5

EXPLANATION:
Logic of swap two numbers using third variable:
Step1:z=x;
Step2:x=y;
Step3:y=z;
x=5, y=6, z is the third variable which holds data temporary according to our logic.
z=x, i.e., value of x is assigned to z, So z=5
after value of x becomes blank then
x=y, i.e., value of y is assigned to x, So x=6
after value of y becomes blank
y=z, i.e., value of z is assigned to y, So y=5
After applying the logic the value of x becomes 6 and value of y=5
Q8. C Program to Swap Two Numbers without using Third Variable.
Solution:
/*************************************************************************
FILE NAME: prog8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to swap two numbers without using third
variable
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,y,z;
clrscr();
printf(“Input the two numbers to be swapped:”);
C Programming 55

scanf(“%d%d”,&x,&y);
/*logic of swapping without third variable*/
x=x+y;
y=x-y;
x=x-y;
printf(“After swapping/exchanging the numbers are:%d %d”,x,y);
getch();
}

Output:
Input the two numbers to be swapped: 3 4
After swapping/exchanging the numbers are: 4 3

EXPLANATION:
Logic of swapping two numbers without using the third variable:
Step1: x=x+y;
Step2: y=x-y;
Step3: x=x-y;
Example:
x=3 ,y=4
step1:x=3+4=7
step2:y=7-4=3
step3:x=7-3=4
thus after swapping the value of x=4 and value of y=3
Q9. C Program to Calculate the Simple Interest.
Solution:
/*************************************************************************
FILE NAME: prog9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to calculate the simple interest
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,y,z,m;
clrscr();
printf(“Input the price, time and rate:”);
scanf(“%d%d%d”,&x,&y,&z);
m=(x*y*z)/100;
printf(“After calculation the simple interest is:%d”,m);
getch();
}
56 Concepts and Techniques of Programming in C

Output:
Input the price, time and rate: 100 2 5
After calculation the simple interest is: 10

EXPLANATION:
In the above program the user enters the price, time and rate of interest as 100,2,5
then multiplies all of them, i.e., 100*2*5=1000 and divides it by 100 and the result 10
is stored in variable interest and last print it. Here, the variable x is declared as price,
y is time and rate is z.
Q10. C Program to Find Area of Any Triangle.
Solution:
/************************************************************************
FILE NAME: prog10.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to find area of any triangle
*************************************************************************/
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main(void)
{
float x,y,z;
float s,area;
clrscr();
printf(“Input the size of each side of triangle:”);
scanf(“%f%f%f”,&x,&y,&z);
s=(x+y+z)/2;
area=sqrt(s*(s-x)*(s-y)*(s-z));
printf(“The area of triangle is: %.3f”,area);
getch();
}

Output:
Input the size of each side of triangles: 2 3 4
The area of triangle is: 2.905

EXPLANATION:
Here the user enters the sides of the triangle then sums these sides and divides by 2
and stores in s. Then applies the formula, area = √(s*(s-x)*(s-y)*(s-z)), where s = (x + y
+ z)/2. And last print the area.
math.h is the header file used for mathematical operation.
C Programming 57

x y

Q11. C Program to Find Area of Equilateral Triangle.


Solution:
/*************************************************************************
FILE NAME: prog11.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to find area of equilateral triangle
*************************************************************************/
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main(void)
{
float x;
float area;
clrscr();
printf(“Input the size of side of the equilateral triangle : “);
scanf(“%f”,&x);
area = sqrt(3)/4*(x*x);
printf(“The area of equilateral triangle is: %.3f”,area);
getch();
}

Output:
Input the size of side of the equilateral triangle: 3
The area of equilateral triangle is: 3.897

EXPLANATION:
Formula of area of equilateral triangle:
area = (√3)/4 * x2

x x
58 Concepts and Techniques of Programming in C

Q12. C Program to Find the Area of a Right Angled Triangle.


Solution:
/*************************************************************************
FILE NAME: prog12.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to find area of right angled triangle
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x,y,z;
clrscr();
printf(“Input the height and width of the right angled triangle : “);
scanf(“%f%f”, &x, &y);
z = 0.5 *x*y;
printf(“The area of right angled triangle is: %.3f”,z);
getch();
}

Output:
Input the height and width of the right angled triangle: 3 2
The area of right angled triangle is: 3.000

EXPLANATION:
Here the user input the height and width of the right angled triangle, e.g., 3 as
height and 2 as width. The formula of calculating the area of right angled triangle is
½*height*width. So after multiplying (0.5*3*2=3) the result is 3. Since the data type is
float so 3.000 is the result.

w
C Programming 59

Q13. C Program for Calculating Compound Interest.


Solution:
/*************************************************************************
FILE NAME: prog13.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: C program for calculate compound interest.
*************************************************************************/
#include<stdio.h>
#include<math.h>
#include<conio.h>
int main(void)
{
float p,r,t,c;
clrscr();
printf(“Input the principal amount:”);
scanf(“%f”,&p);
printf(“Input the rate of interest:”);
scanf(“%f”,&r);
printf(“Input the time period in year:”);
scanf(“%f”,&t);
/*calculate compound interest */
c=p*(pow((1+r/100),t)-1);
printf(“\n After calculation the compound interest is:%f”,c);
getch();
return 0;
}

Output:
Input the principal amount: 200
Input the rate of interest: 4
Input the time period in year: 2
After calculation the compound interest is: 16.320000
Q14. C Program to Convert Centimeter into Meter and Kilometer.
Solution:
/************************************************************************
FILE NAME: prog14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: C program to convert centimeter into meter and kilometer
*************************************************************************/
#include <stdio.h>
#include<conio.h>
60 Concepts and Techniques of Programming in C

void main(void)
{
float x;
clrscr();
float y,z;
printf(“Input the length in centimeter: “);
scanf(“%f”, &x);
y=x/100.0;
z=x/100000.0;
printf(“The length in Meter is:%.2f\n”,y);
printf(“The length in Kilometer is:%.2f”,z);
getch();
}

Output:
Input the length in centimeters: 100000
The length in meters is: 1000.00
The length in kilometer is: 1.00

EXPLANATION:
Here the user input the length as 100000. Then that length in cm was divided by 100
to get meter, i.e., 1000 meters and to convert again cm into km again divide centimeter
into 100000 to get km.

Summary

1. C is a structured, high level and machine independent programming language.


2. Machine independent means it can run on any platform/operating system.
3. C was developed by Dennis Ritchie at Bell Laboratories in 1972.
4. It is portable, efficient, effective reliable and modular in programming.
5. Compiler is a system software which converts program written in high level
language into machine language.
6. Interpreter is a system software which interprets the program each line by line
while executing.
7. Linker links the object file with library function to create exe file.
8. Loader loads the program into memory.
9. Syntax errors are the common grammatical errors found in writing programs.
10. The runtime errors are found during program execution.
11. Logical errors are due to carelessly writing the program.
12. The main() function is a user-defined function which is the entry point of the
program.
C Programming 61

13. The printf ()function is used to display the output on the computer screen.
14. The scanf()function is used to take input through the keyboard into the memory.
15. The preprocessor directive is an instruction to the preprocessor.
16. #include<stdio.h> is called preprocessor directive, which tells to the C compiler
to include the standard input output, i.e., stdio.h file before compilation of the C
program.

SHORT QUESTIONS

1. What is a C program? Who developed C programming?


2. What are compiler, loader, linker and interpreter?
3. What are syntax error and semantics error?
4. What is preprocessor?
5. Difference between the preprocessor and preprocessor directives.
6. What is macro?

LONG QUESTIONS

1. Write a C program to find the area and perimeter of circle and rectangle.
2. Write a C program to covert temperature in Fahrenheit to Celsius.
3. Write a C program to convert temperature from Celsius to Fahrenheit.
4. Write a C program to exchange to exchange the two integer numbers using third
variable.
5. Write a C program to exchange the two integer numbers without using the third
variable.
6. Write a C program to compute simple interest.
7. Write a C program to compute the compound interest.
8. Write a C program to find the area of right angled triangle.
9. Write a C program to find area of any triangle.
10. Write a C program to find area of equilateral triangle.

MULTIPLE-Choice QUESTIONS

1. C programming language is a___________.


(a) High level language (b) Low level language
(c) Assembly level language (d) Machine level language
[Ans: a]
62 Concepts and Techniques of Programming in C

2. Who developed C programming language and in which year?


(a) Bjarne Strostup (b) Dennis Ritchie, 1972
[Ans: b]
3. Which among the list below is called system software?
(a) Compiler (b) Loader
(c) Linker (d) Assembler
(e) All of the above
[Ans: e]
4. Which among the list below is called library function?
(a) scanf() and printf() (b) main()
(c) Both
[Ans: a]
4
Variables, Constants
and Data Types

4.1 Introduction
When a person sits in a chair then it takes some physical space. Like that in programming
concept when a variable is declared it takes some logical memory space. So we can say
that a variable is a memory location which is used to store some data values. Someone
can also say that a variable is a place holder because it holds some memory. At different
times during program execution, a variable can take different data values. But at a
single time the variable cannot take many values instead of single values. A variable
name should be given by the programmer in such a way that it is easy to execute the
program.

TIPS TO REMEMBER
Try to choose a simple variable name. So that it easy to perform the operation/
implementation.

4.2 DECLARATION OF VARIABLES


The declaration of a variable consists of two parts, i.e., one is data types and the other
is variable name. Data types determine what types of data values the variable will hold.
It may determine integer type values, float type, char type or double type values. The
variable name means the programmer has given the name of the variable which should
be simple (described in Section 3.4). The declaration of variable is necessary because it
can be used later in a program.

The syntax of declaring a single variable is:


data-type variable_name;
64 Concepts and Techniques of Programming in C

EXPLANATION:
The above variable declaration shows that the first position in the syntax is the place
of data type then the variable name. The programmer chooses a single data type
according to his requirement from the fundamental types and the fundamental data
type means int, char, float and double.

Example:
int x; /*one variable declaration*/

EXPLANATION:
In the above example is the declaration of single variable. Here x is the variable name
and int is the integer data type. So x is a variable of data type int. In the declaration of
variable both data type and variable names are important to place in their position and
without both of these we cannot say that it is a valid variable declaration. We cannot
change their position also.
1000

1735

Fig. 4.1 Memory representation of variable x

Here 1735 is the garbage value assigned by the compiler to variable x when it is
declared and the address of variable x is 1000. The variable stores the garbage value
1735 because the variable is not initialized. Therefore, we know that unused/initialized
variable will take the garbage value.
Like integer variable declaration we can also declare char type, float and double type
variable and the examples are:
char c;
float x;
double r;

EXPLANATION:
Here c is a variable which stores char type value, x is a variable which stores floating
type values and r is a variable which stores double precision floating type values.

The syntax of multiple variable in one statement is:


data-type variable1,variable2------variable-N;
Variables, Constants and Data Types 65

EXPLANATION:
Here the first position is the place of fundamental data type and then variable1 is the
name of first variable, variable2 is the name of second variable-----variable-N is the
name of last variable.

Example:
int x,y,z; /*multiple variable declaration in single line*/

EXPLANATION:
In the above syntax the three variables x, y, z are declared in a single statement instead
of multiple statement. So x is a variable of int type and same y and z are variables of
int data type.

4.3 INITIALIZATION OF VARIABLES


When a programmer declares the variable it automatically assigns the undefined
values. The undefined values may be positive or negative integer values depending
on the computer and which are called garbage values or uninitialized values. When
the programmer assigns some values to that variable then it is called initialization of
variables. So initialization of variable means giving (assigning) values to variable.

The syntax of initialization of variable is:


data-types variable_name=constants;

EXPLANATION:
The above declaration consists of data type, variable name, assignment operator and
constant values.

Example:
int x=20;
Here 20 is an integer constant value that is assigned to the variable x. e.g. in the location
x, 20 is stored. The logical representation of storing a variable x is shown below.

x Variable name
20 Value
2000 Address of variable x
Fig. 4.2 Initialization variable x
66 Concepts and Techniques of Programming in C

4.4 RULES OF NAMING A VARIABLE


The programmer cannot give any name to the variable. The name of the variable
follows some specific rules and regulations followed by C compiler. The variable name
is the combination of letters, digits, and underscores, character according to specific
conditions. The conditions are

Table 4.1 Naming of a variable

1. The variable name can begin with underscore (-), letter (it may be a lower case letter
or upper case letter).
Examples: _Total; or Total; or total; or TOTAL;
2. The length of a variable should not exceed 31 characters. But many compilers allowed
normally maximum eight characters.
3. The variable names are case sensitive, i.e., upper case and lower case alphabets are
different, e.g., number is not same as NUMBER.
4. Keywords are not allowed, e.g., for, if, while, do while.
Example:
wrong: int for;
correct: int student_id;
5. White space/blank spaces are not allowed.
Example:
wrong: int student id;
correct is: int student_id;
6. Special characters e.g. %, $, #, @ are not allowed.
Example:
wrong: int #student_id;
correct is: int student_id;

TIPS TO REMEMBER
From Table 4.1 we conclude that name of the variable can be written in lower case
or upper case letters. But a good programmer always prefers lower case letters.

/*Simple Example of Addition of Two Integer Numbers Input by User*/


#include<stdio.h>
void main()
{
int x,y,z; /*x,y,z are variables*/
printf(“Input two integer numbers:”);
scanf(“%d%d”,&x,&y);
Variables, Constants and Data Types 67

z=x+y;
printf(“Sum of two integer numbers is:%d”,z);
}

Output:
Input two integer numbers: 2 3
Sum of two integer numbers is: 5

4.5 WHAT IS CONSTANT?


Constant is a fixed value that does not change during program execution.

4.5.1 Different Types of Constants


The constants are divided into two categories, i.e., numeric constant and character
constant. Again numeric constants are divided into two types, i.e., integer constant,
real constant. The character constants are further divided into two types, i.e., single
character constant and string constant. The diagrammatic representation of different
types of constants are shown in below.

Constant

Numeric Character
constant constant

Integer Real
constant constant Single character
constant
String
constant

Fig. 4.3 Types of constants

4.6 EXPLANATION OF DIFFERENT TYPES OF CONSTANTS


4.6.1 Numeric Constant
(A) Integer Constant
Integer constants are constants which do not have any decimal part/fractional part,
i.e., (.). There are three types of integer constants, i.e., decimal integer constants, octal
integer constants, hexadecimal integer constants.
68 Concepts and Techniques of Programming in C

Examples of integer constant are 10, 4,–20,+40


Octal constant consists of digits from 0 to 7, with leading zero. Example: 050, 0200,
0567, etc.
Hexadecimal constants are sequences of digits preceded by 0x,0X, i.e., they start with
alphabet from A to F. Value of A is 10,B=11,C,12,D=13,E=14,F=15.
Examples of hexadecimal integers are:
0X7,0x10E

(B) Real Constants


These constant have fractional parts. These are also known as floating point constants.
Examples are: 0.67,+234.9

4.6.2 Character Constant


(A) Single Character Constant
A single character constant or character constant contains a single character enclosed
within a single quote. Examples are: ‘10’,’h’,’J’, etc.

(B) String Constant


String constants are the sequences of characters that are generally enclosed within
double quotes. Or we can say those characters which are enclosed within double quotes
are called string constants. These characters are numbers, letters, blank space or special
characters. Examples are: “I LOVE MY INDIA”,
”hello”, etc.

4.7 SYMBOLIC CONSTANT


A symbolic constant is a substitute name of the set of characters. The symbolic constants
may be character constant, string constant or a numeric constant.

When is it Required?
When the programmer wants to use a constant multiple times then he can use a
substitute name for that character, for example, if the programmer is to use the p (pi)
value 3.14 in several places of the program, then he can give the alternative name PI
or other instead of 3.14 and use it everywhere in the program. This type of constant
is called symbolic constant.
Variables, Constants and Data Types 69

The syntax is
#define new_name constant_value

In the above declaration the new_name is the symbolic name for that substitute of
constant value and it is generally written in upper case letters. The constant_value may
be numeric, string or character.

TIPS TO REMEMBER
In symbolic constant do not give semicolon at the end of the statements, e.g.,
#define new_name constant_value;
Because #define is not a statement rather it is a preprocessor directive.

Examples of symbolic constant are


(a) #define PI 3.14
(b) #define NAME “Dhabal”
In using the above constant the program improves the readability.
/*Programming Example of Symbolic Constant*/
#include<stdio.h>
#define NAME “DHABAL”
void main()
{
printf(“%s”,NAME);
}

Output:
DHABAL

4.8 CHARACTER SET


The character plays an important role in creating word, sentence or paragraph .But
there are some characters which the computer can understand. These are:
Lower case character-- Æa-z
Upper case characterÆA-Z
Digits------------------- Æ0-9
White space------ Ætab or new line or space
Special character--------- Æ%@$&^*!
70 Concepts and Techniques of Programming in C

Special character set

. ------------dot or period , --------------comma


: -----------colon ; --------------semicolon
“ ------double quotes ‘ -------------------apostrophe
/ --------forward slash \ ------------------backward slash
__ ------------------underscore ~ --------tild
? ------question mark $ ------dollar
*---------asterisk & ---ampersand
^ ------to the power - -------minus
+---------plus |--------vertical bar
()-----parenthesis []-----square bracket
{}------left and right braces @----at the rate
= --equal to #-----hash
% -----percentage < -------less then
>------greater then !------not equal to

4.9 TOKENS
A token is the smallest individual unit in C programming. In text messages each word
and punctuation symbols are called tokens. There are six types of tokens in C. They
are: Keywords, constants, strings, operators, identifier, special symbols.

Tokens

Special
Keywords Constants Strings Operators Identifier symbols

Fig. 4.4 Shows the different types of tokens

4.10 KEYWORDS
Keywords are the words which are reserved in C compiler and its meaning has been
explained to the compiler and these word meaning cannot be changed. There are 32
keywords reserved in C programming. These keywords are generally written in lower
case character. They are:
Variables, Constants and Data Types 71

Table 4.2 List of keyword reserved by C compiler

1. auto 7.  default 14. for 20. return 27. typedef


2. break 8.  do 15. goto 21. short 28. union
3. case 9.  double 16. if 22. signed 29. unsigned
4. char 10. else 17. int 23. sizeof 30. void
5. const 11. enum 18. long 24. static 31. volatile
6. continue 12. extern 19. register 25. struct 32. while
13. float 26. switch

4.11 IDENTIFIER
Identifier means the naming of function, array and variables. These are user-defined
names and consist of letters and digits. Lowercase and upper case are allowed to give
identifier name. But lower case letters are generally used by the programmer.
Example:
(a) int x;
(b) int y[10];
(c) int z()
{
}
In the above first example int x; where x is called the variable or identifier. Liked
second example int y[10]; y is the array name or identifier y, int z(){ } where z is the
called the identifier or function name.

Identifier

Variable Array Function

Fig. 4.5 Types of identifiers

4.12 DATA TYPES


Definition: The data type determines the type of values and the range of values that
can be stored in a variable.
72 Concepts and Techniques of Programming in C

4.13 TYPES OF DATA TYPES


C programming supports three categories of data types. These are:
1. Fundamental data types or primary data types (int, char, float and double).
2. Derived data types (e.g. arrays, functions, structure and pointers).
3. User-defined data types (e.g. typedef and enum).

Data types

Fundamental data Derived data types


User-defined data types
types (int, char, (array, functions,
(typedef, enum)
float, double) structure and pointers)

Fig. 4.6 Different types of data types

4.13.1 Explanation of Data Types


The fundamental data types are of four types, e.g., integer, character, float and double
type. The data type integer is represented as int, character is char, float is float, double
is double.

Table 4.3 Different types of fundamental data types and its sizes

int --- ÆThese data type stores the integer value whose size is ---- Æ2 bytes (16-bit
compiler)
char- ÆThese data types stores the single character values whose size is------ Æ1 byte.
(16-bit compiler)
float - ÆThese data types stores floating point numbers whose size is ---- Æ4 bytes.
(16-bit compiler)
double ÆThese data type stores double precision floating point numbers whose size is
---8 bytes. (16-bit compiler)
long double - ÆThese data types whose size is ---- Æ10 bytes. (16-bit compiler)

Two types of qualifiers are used in the above fundamental data type, i.e., sign qualifier
and size qualifier. Sign qualifier is again of two types, i.e., signed and unsigned. When
signed qualifier is used before an integer number it means that the integer may be a
positive number or negative number. Unsigned integer means only positive integer
numbers. When no qualifier is mentioned, its default is signed. The size of data types
is a machine dependent. In some platform int data types occupy two bytes of memory
whereas in some other platform it may occupy four bytes of memory.
Variables, Constants and Data Types 73

Table 4.4 Fundamental data types on 16-bit machines

Data Types Range of Values


int --------------------32,768 to 32,767
char --------------------128 to 127
float --------------------3.4e-38 to 3.4e+e38
double ------------------1.7e-308 to 1.7e+308

4.13.2 Derived Data Types are described in next chapters.


4.13.3 User-defined Data Types

1. typedef Data Type


The typedef is known as type definition which allows the programmer to define a new
variable that would represent the existing data type.

The syntax of the typedef is:


typedef data-type variable;

Example:
typedef int marks;

2. enum Data Type


The enum is the user-defined data type which consists of a list of values and it starts
with the index 0 by default and value is sequentially incremented by 1 in that list.

The syntax of enumerator is:


enum variable
{
value1,value2,value3----------value-N
};

Example 1:
enum months
{
January, February, march
};

Here January, February, March is assigned to 0, 1, 2 by default respectively.


74 Concepts and Techniques of Programming in C

Example 2:
enum month
{
January=1,february,march
};

Here January is assigned to 1 and by default February and March will be assigned to
2 and 3 respectively
/*Programming Example 3 of Enumerator*/
#include <stdio.h>
void main()
{
enum MONTH
{
January=0,February,March,April
};
enum MONTH month =April;
if(month == 0)
printf(“Value of January”);
else if(month == 1)
printf(“Month is February”);
if(month == 2)
printf(“Month is March”);
if(month == 3)
printf(“Month is April”);
}

Output:
Month is April

EXPLANATION:
In the above program the output is April because January starts width index 0, so
February index is 1, March index is 2 and April index is 3. Since enum variable is
initialized with April .Therefore 3 is assigned to variable month and when it matches
with last condition then it displayed the output “month is April”.
/*Programming Example 4 of Enumerator*/
#include<stdio.h>
enum numbers
{
zero,one,two,three,four=3,five,six,seven=0,eight
};
void main()
{
printf(“%d,%d,%d,%d,%d,%d,%d,%d,%d”,zero,one,two,three,four,five,six,seven,eight);
}
Variables, Constants and Data Types 75

Output:
0,1,2,3,3,4,5,0,1

EXPLANATION:
In the above program enum member begins at zero with default index 0 then one with
index 1, two with index 2, three with index 3, four initialized with index 3, five increase
the next index of previously initialized index so five assigned with index 4, six with
5, seven initialed with 0 and then eight increase the previous member index with one
e.g. eight with one.

Summary

1. A variable is a memory location used for storing data values.


2. A variable name should be simple so that it is easy to execute.
3. Assigning values to variables is called initialization of variables.
4. Without assigning values the variable contains garbage values.
5. A constant is a fixed value which does not change its value during execution of
a program.
6. There are different types of constants. They are numeric constant and character
constant. Numeric constant is again divided into integer constant, real constant.
The character constant is again divided into single character and string constant.
7. A symbolic constant is the substitute name of set of characters.
8. Each individual word in a text message is called token. The different types of
tokens are keywords, constant, string, operator, identifier, special symbol.
9. Keyword is the reserved words in C compiler.
10. There are 32 reserved keywords in C programming.
11. Identifier is the alternative names of variables, functions and array.
12. Data types determine what type of data value the variable will hold.
13. There are three types of data types in C, i.e., fundamental data types, derived
data types and user-defined data types.

Short questions

1. What is a variable?
2. What is a constant?
3. What is a symbolic constant. Give examples?
4. What are tokens? Explain different types of token.
5. How many keywords are availed in C program?
6. What is an identifier? Give examples.
76 Concepts and Techniques of Programming in C

7. What are data types? What are fundamental data types?


8. What is the size of integer, character, float, double data types?

Long question

1. What is constant? Explain different types of constant in C programming.

Objective questions with answers

1. What will be the output?


#include<stdio.h>
void main()
{
int x=10,y=4,z=5;
printf(“%d %d”,x,y,z);
}
Output:
10 4
2. What will be the output?
#include<stdio.h>
void main()
{
int x=10,y=4;
printf(“%d %d %d”,x,y);
}
Output:
10 4 4
3. What will be the output?
#include<stdio.h>
#define x 5+2
void main()
{
int i;
i=x*x*x;
printf(“%d”,i);
}
Output:
27
5
C Operator

5.1 INTRODUCTION
An operator is a symbol used in C programming to perform (or do) the mathematical and
logical operations (calculations) in an expression. These operators are generally added
with constants or variables in the expression. Operators are used in C programming
to input data values to the variables. Generally, an expression consists of operator,
variables and function constant. Examples: a*b-5 is an expression where a, b are
operands,*.- are operators and 5 is the constant.

5.2 TYPES OF OPERATOR


C programming operators are broadly categorized into different types. They are:
1. Arithmetic operator
2. Assignment operator
3. Increment and decrement operator
4. Relational operator
5. Logical operator
6. Conditional operator
7. Special operator

EXPLANATION:
5.2.1 Arithmetic Operator
The arithmetic operators are used to do arithmetic calculations.
78 Concepts and Techniques of Programming in C

Table 5.1 Arithmetic operators

Operator Basic Purpose (Operation) Example


+ ----------------- Æ addition operation------------------- Æ 3+3=6
- ------------------ Æ subtraction operation---------------- Æ 9-3=6
* ------------------ Æ multiplication operation------------ Æ 3*5=15
% ---------------- Æ reminder /module operation ----- Æ 15/2=7
/------------------ Æ division operation-------------------- Æ 10%3=1(1 is the reminder)

Q1. C Program to Add, Sub, Mul, Div, Mod of Two Integers Numbers using
Arithmetic Operator.
Solution:
/*************************************************************************
FILE NAME: operator1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: C program to add, sub, mul, div, mod of two integer
numbers using arithmetic operator.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,a,s,m,d,r;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
a=x+y;
s=x-y;
m=x*y;
d=x/y;
r=x%y;
printf(“Addition of inputted two integer numbers is:%d\n”,a);
printf(“Subtraction of inputted two integer numbers is:%d\n”,s);
printf(“Multiplication of inputted two integer numbers is:%d\n”,m);
printf(“Division of inputted two integer numbers is:%d\n”,d);
printf(“Remainder of inputted two integer numbers is:%d\n”,r);
}

Output:
Input the two integer numbers: 2 3
Addition of input two integer numbers is: 5
Subtraction of input two integer numbers is:-1
Multiplication of input two integer numbers is: 6
Division of input two integer numbers is: 0
Module of input two integer numbers is: 2
C Operator 79

We can alternatively represent the above program as:


#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“Input the two integer numbers”);
scanf(“%d%d”,&x,&y);
printf(“The arithmetic operations (sub, add, multiply ,div and mod) done
on %d and %d are:\n %d\t%d\t%d\t%d\t%d”,x,y,x-y,x+y,x*y,x/y,x%y);
getch();
}

Output:
Input the two integer numbers: 12 4
The arithmetic operations (sub, add, multiply, div and mod) done on 12 and 4 are:
8 16 48 3 0

5.2.2 Assignment Operator


The assignment operator (“=”) is used to assign the result of an expression to the
variable.
Example:
int x=9;
Here the constant 9 is assigned to variable x.
Q2. C Program of Using Assignment Operator.
Solution:
/*************************************************************************
FILE NAME: operator2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: c program of using assignment operator.
*************************************************************************/
#include<stdio.h>
void main()
{
int x=5;
printf(“value of x is:%d”,x);
}

Output:
Value of x is: 5
80 Concepts and Techniques of Programming in C

EXPLANATION:
Here = symbol is used to assign value 5 to variable x.

5.2.3 Increment/Decrement Operator


There are two useful operators which are used in C programming language for
incrementing and decrementing the variable. They are ++ and -- operators. The ++
operator is called increment operator and -- operator is called decrement operators.
These operators increment or decrement the variable's value by 1. These operators
(++ and --) are called unary operators because they are applied to only one operand
for operation. These operators are also called prefix and postfix operators because it
depends on where the operators will be used.

The syntax of increment/decrement operator applied in single operand is:


1. ++variable;/--variable;
2. variable++;/variable--;

(a) ++x; /* prefix increment operator with operand*/


Or
x++; /*postfix increment operator with operand*/
(b) --x; /*prefix decrement operator with operand*/
Or
x--; /*postfix decrement operator with operand*/
(c) ++x is same as x=x+1 or x+=1
(d) --x is same as x=x-1 or x-=1
Generally, these operators are used in for loop and while loop.

What is the major difference between prefix operators applied to single operand
vs. postfix operator applied to single operand?
Answer: When the operator is applied to single operand, e.g., x++ and ++x, then the
result will be same. But when it applies in an expression of right side of assignment
operator then the result will be different.

Let’s see the difference of prefix operator and postfix operator applied in single
operand x from Example 1 to Example 4, i.e., x++ and ++x.
/*Example 1 of Postfix Operator*/
#include<stdio.h>
void main()
C Operator 81

{
int x=1;
x++;
printf(“Value of x is:%d”,x);
}

Output:
Value of x is: 2
/*Example 2 of Prefix Operator*/
#include<stdio.h>
void main()
{
int x=1;
++x;
printf(“Value of x is:%d”,x);
}

Output:
Value of x is: 2

EXPLANATION OF EXAMPLE 1 AND EXAMPLE 2


In Example 1 postfix operator is applied and Example 2 prefix operator is used. In
the above two examples the results are same because the operator is applied to single
variable.
/*Example 3 of Postfix Operator*/
#include<stdio.h>
void main()
{
int x=1;
printf(“Value of x is:%d”,x++);
}

Output:
Value of x is: 1
/*Example 4 of Prefix Operator*/
#include<stdio.h>
void main()
{
int x=1;
printf(“Value of x is:%d”,++x);
}

Output:
Value of x is: 2
82 Concepts and Techniques of Programming in C

EXPLANATION OF EXAMPLE 3 AND EXAMPLE 4


In Example 3 the output is 1 and Example 4 it is 2 because in Example 3 the value
prints first then x value increments. If we print the value of x then it will be 1. In the
Example 4 the value increments first then it prints the output 2.
/*Example 5 of PostFix Operator applied in an Expression*/
#include<stdio.h>
void main()
{
int x=4,y;
y=x++;
printf(“Value of x is:%d\n”,x);
printf(“Value of y is:%d”,y);
}

Output:
Value of x is: 5
Value of y is: 4
/*Example 6 of Prefix Operator applied in an Expression*/
#include<stdio.h>
void main()
{
int x=4,y;
y=++x;
printf(“Value of x is:%d\n”,x);
printf(“Value of y is:%d”,y);
}

Output:
Value of x is: 5
Value of y is: 5

EXPLANATION OF EXAMPLE 5 AND EXAMPLE 6


The output of y in Example 5 is 4 and Example 6 is 5 because in Example 5 the value
of x is assigned to y first and then increments the value of x, i.e., y=4 and x=5. But in
Example 6 the value of x increments first then assigned to variable y, i.e., y=5 and x=5.

So result of Example 5 and Example 6 is


1. x=5,y=4
2. x=5,y=5
C Operator 83

/*Example 7*/
#include<stdio.h>
void main()
{
int x=5;
x=x++ + ++x;
printf(“%d”,x);
}

Output:
13

Explanation:
Here the x value is 5 and after incrementing the values of x++ becomes 6 and it assigns
to variable x, i.e., x value becomes 6, and then ++x becomes 7 and last addition of x++
and ++x value 6+7 becomes 13 and stored in variable x=13.
/*Example 8*/
#include<stdio.h>
void main()
{
int x=5,y;
y=x++ + ++x;
printf(“%d”,y);
}

Output:
12
/*Example 9*/
#include<stdio.h>
void main()
{
int x=5;
x=x++ + x++;
printf(“%d”,x);
}

Output:
12

Explanation:
Here x value is 5 and after increments the x++ value is 6 and stored in variable x and
then x++ value becomes
84 Concepts and Techniques of Programming in C

/*Example 10*/
#include<stdio.h>
void main()
{
int x=5,y;
y=x++ + x++;
printf(“%d”,y);
}

Output:
10

Explanation:
More increment and decrement programming examples are shown in objective question
with answer section of this chapter.
/*Example 11*/
#include<stdio.h>
void main()
{
int x=5;
printf(“%d %d %d %d %d”,x++,x--,++x,--x,x);
}

Output:
45545

Explanation:
Here the values of x are pushed into the stack format. Stack is a collection of elements
where values are inserted or deleted into the stack trough top, e.g., value of x=5 is
pushed first then - -x, ++x, x- -, x++.
Let’s see the input of x into the stack.

x++ (4)
x--(5)
++x( 5)
--x (4)
x( 5)
Stack

Let’s see more explanation about increment and decrement values of the stack are
pushed into the stack.
C Operator 85

(a)

5 Top
(b)

4 Top
5
(c)

5 Top
4
5
(d)

5 Top
5
4
5
(e)
4 Top
5
5
4
5

Output
The inputs of stack are stored from bottom to top. But the results will not display from
bottom to top. These will display from top to bottom. So the result is: 4 5 5 4 5.
86 Concepts and Techniques of Programming in C

5.2.4 Relational Operator


Relational operators are known as comparison operator and the objective of this
operator is to compare the two values. Example: compares the values of two integers.
These comparisons are done through the relational operator. Table below show the
different types of relational operators.

Table 5.2 Shows the relational operator lists

Operator Purpose Example True(1)/False(0)


< ---------------------- Æ less then ----------------------- Æ 3<2 ---------- Æ 0
< = ------------------- Æ less than or equal to -------- Æ 5<=5 -------- Æ 1
> ---------------------- Æ greater then ------------------- Æ 3>2 ---------- Æ 1
> = ------------------- Æ greater than or equal to ---- Æ 5>=4 -------- Æ 1
== -------------------- Æ equal to ------------------------ Æ 3==4 -------- Æ 0
! = -------------------- Æ not equal to ------------------- Æ 4!=4 --------- Æ 0

Q3. Example of Relational Operator Use


Solution:
/*************************************************************************
FILE NAME: operator3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: example of relational operator use
*************************************************************************/
#include<stdio.h>
void main()
{
int x,y;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
if(x>y)
printf(“Among the inputted two %d is the greatest number”,x);
if(x<y)
printf(“Among the inputted two %d is the greatest number”,y);
if(x==y)
printf(“ Both inputted %d and %d are same”,x,y);
}

Output:
Input the two integer numbers: 2 3
Among these two numbers 3 is the greatest number
C Operator 87

TIPS TO REMEMBER
The difference between = and == is that first one (=) is the assignment operator. The
objective of this assignment operator is to assign the value to the variable, e.g., a=10.
But the second one (==) is the comparison operator and it is used to compare the
two values for measuring the equality, e.g., if (a==5)

5.2.5 Logical Operator


Logical operators are used in an expression which consists of more than one condition.
An expression consisting of logical operator is called logical expression.

Table 5.3 Logical operator

Operator Purpose Example True(1)/False(0)


&& -------------- Æ logical AND -------------- Æ 4>3&&4<8 -------------- Æ 1
|| --------------- Æ logical OR ----------------- Æ 7>6||7<5 --------------- Æ 1
! ------------------ Æ logical NOT --------------- Æ 4!=4 ----------------------- Æ 0

/*Examples of Logical Operator*/


#include<stdio.h>
void main()
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
if(x>y&&y>z) /*&& is the logical operator*/
printf(“Among the inputted three numbers %d is greater”,x);
}

Output:
Input the three integer numbers: 3 2 1
Among these three numbers 3 is the greatest
Q. What will be the Output?
#include<stdio.h>
int main()
{
int i=6;
if(((++i<7)&&(i++/6))||(++i<=9));
printf(“%d\n”,i);
return 0;
}

Output:
8
88 Concepts and Techniques of Programming in C

5.2.6 Conditional Operator


Conditional operator is a ternary operator which consists of two operators’, e.g., (? : )
and are applied in an expression which consists of three expressions.

The syntax of conditional operator:


expression1? expression2: expression3

The expression1 is evaluated first and it is the conditional part. If expression 1/


conditional part is true then expression 2 becomes the result of the whole expression
otherwise expression 3 becomes the result.
Let’s see some programming examples.
Q4. C Program to Find Greatest Number between Two using Conditional Operator.
Solution:
/*************************************************************************
FILE NAME: operator4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: c program to find greatest number between two using
conditional operator.
*************************************************************************/
#include<stdio.h>
void main()
{
int x, y, z;
printf(“Input the two integer numbers:”);
scanf(“%d%d”, &x, &y);
z=x>y? x: y;
printf(“The greatest number between inputted two integer numbers is:%d”, z);
}

Output:
Input the two integer numbers: 5 9
The greatest number between input two integer numbers is 9

EXPLANATION:
Here suppose the user entered the input 5 and 9 then if condition checked, i.e., 5>9?
5:9. In the conditional expression since the condition 1, i.e., 5>9 is not satisfied, so, i.e.,
condition 2 became the output, i.e., 9 is assigned to variable z and printf statement
printed the output 9 is the greatest.
C Operator 89

Q5. C Program for Finding the Greatest Number between Three Integer Numbers
using Conditional Operator.
Solution:
/************************************************************************
FILE NAME: operator5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: c program of finding greatest number between three
integer numbers using conditional operator.
*************************************************************************/
#include<stdio.h>
void main()
{
int x, y, z, a;
printf(“Input the three numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
a=(x>y)? (x> z)? x: z:(y>z)?y:z;
printf(“Greatest number among inputted three numbers is:%d”, a);
}

Output:
Input the three numbers: 2 3 4
Greatest number among three numbers is: 4

EXPLANATION:
Here one conditional statement is nested with another conditional statement in
expression1.if x>y condition becomes true then the second conditional statement x>z
will check. If condition is satisfied then x value is assigned to variable a otherwise z
value is assigned to variable a. else if y>z is satisfied then y value is assigned to a or z
value assigned to a. Then last printf statement prints the value of a.

TIPS TO REMEMBER
Instead of the expression a=(x>y)?(x>z)?x:z:(y>z)?y:z; We can also write a=(x>y?(x>z?
x:y):(y>z? y:z));

Q6. C Program to Check the Number is Even or Odd using Conditional Operator.
Solution:
/*************************************************************************
FILE NAME: operator6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
90 Concepts and Techniques of Programming in C

NAME OF THE PROGRAM: c program to check the number is even or odd using
conditional operator.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
printf(“Input an integer number:”);
scanf(“%d”,&x);
x%2==0?printf(“Inputted %d is an even number”, x): printf(“Inputted %d is
Odd number”, x);
getch();
}

Output:
Input an integer number: 6
Number 6 is an even number

EXPLANATION:
Here the user input the number 6 then expression will be evaluated, i.e., 6%2==0
condition is satisfied then expreesion 2 is the output, i.e., 6 is an even number.
Q7. C Program to Check Vowel or Consonant using Conditional Operator.
Solution:
/*************************************************************************
FILE NAME: operator7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: C program to check vowel or consonant using conditional
operator.
*************************************************************************/
#include<stdio.h>
void main()
{
char x;
printf(“Input the character:”);
scanf(“%c”, &x);
(x==’a’||x==’A’||x==’e’||x==’E’||x==’i’||x==’I’||x==’o’||x==’O’||x==’u’||x
==’U’)?printf(“Inputted character %c is the vowel”, x): printf(“Inputted
character %c is the consonant”, x);
}

Output:
Input the character: r
Input character r is a consonant
C Operator 91

EXPLANATION:
Here input r is matched with the given condition. Since r does not match so the third
expression is the output, e.g., r is the consonant.

5.2.7 Special Operator


The special operator consists of comma (,), sizeof() and pointer operators * and &.
(a) Examples of “sizeof” Operator
/*C program to Check Size of Integer Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
int x;
printf(“Size of integer data type is:%d”,sizeof(int));
}

Output:
Size of integer data type is: 2

EXPLANATION:
The sizeof() is the keyword which is used to measure the size of each fundamental data
types. Here it measures the sizeof( int) data type.

TIPS TO REMEMBER
Instead of sizeof(int) ,we can also write sizeof(x), e.g., x is a variable which is int data
types and both give the same result according to respective data type.

/*C program of Checking Size of Character Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
char x;
printf(“Size of character data type is:%d”,sizeof(char));
}

Output:
Size of character data type is: 1
/*C Program for Checking Size of Float Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
92 Concepts and Techniques of Programming in C

float x;
printf(“Size of float data type is:%d”, sizeof(float));
}

Output:
Size of float data type is: 4
/*C program to Check Size of Double Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
double x;
printf(“Size of double data type is:%d”, sizeof(double));
}

Output:
Size of double data type is:8
Q. What will be the Output?
#include<stdio.h>
#define int char
void main(void)
{
int x=65;
printf(“Size of variable x is:%d”,sizeof(x));
}

Output:
Size of variable x is: 1

EXPLANATION:
The output is 1 instead of 2 because the before main function the symbolic constant is
defined e.g. size of char is assigned to integer e.g. int size become 1.
(b) Examples of “&” Operator
#include<stdio.h>
void main()
{
int x=3;
printf(“ address of variable x is:%d”,&x);
}

Output:
Address of variable x is: 8698

EXPLANATION:
The address 8698 is address generated by system. It may vary from one operating
system to another.
C Operator 93

(c) Example of “ * ” Operator


#include<stdio.h>
void main()
{
int x=3;
printf(“ value of x is:%d”,*(&x));
}

Output:
Value of x is:3

EXPLANATION:
This *(pointer) is called indirect operator and it indirectly prints the variables value.

5.2.8 Bitwise Operator


Bitwise operators are used for testing the bits or shift them right or left. In float and
double data types bitwise operator may not applied.

Table 5.4 Bitwise operator

Operator Purpose
& ------------- Æ bitwise AND
|--------------- Æ bitwise OR
<< ------------ Æ shift left
>> ------------ Æ shift right
^ ------------- Æ bitwise exclusive OR

Q8. C Programs to Check the Number Even or Odd using Bitwise Operator.
Solution:
/*************************************************************************
FILE NAME: operator8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: c program to check the number even or odd using
bitwise operator
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
94 Concepts and Techniques of Programming in C

printf(“Input an integer number to check even or odd:”);


scanf(“%d”,&x);
if(x&1==1)
printf(“Inputted number is Odd “);
else
printf(“Inputted number is Even “);
getch();
}

Output:
Input an integer number to check even or odd: 6
Input number is even
Q9. C Program to Swap Two Numbers using Bitwise XOR.
Solution:
/*************************************************************************
FILE NAME: operator9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: C program to swap two numbers using bitwise XOR
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”, &x, &y);
printf(“Before swapping the inputted two integer numbers are :x = %d\ y
=%d\n”, x, y);
x=x^y;
y=x^y;
x=x^y;
printf(“After swapping the inputted two integer numbers are :x = %d\ y =
%d\n”, x, y);
getch();
}

Output:
Input the two integer numbers: 6 7
Before swapping the input two integer numbers are: x=6 y=7
After swapping the input two integer numbers are: x=7 y=6
C Operator 95

5.3 TYPE CONVERSION/TYPE CASTING


Type casting refers to the conversion of one data type into another data type. There are
two types of type casting. They are 1) implicit type casting, and 2) explicit type casting.

5.3.1 Implicit Type Casting


In some situations the compiler will automatically convert one data type into another
data type. This is called implicit type casting/automatic conversion.
Example 1 of Implicit Type Casting
float x=98.92;
int y=x;/*automatic type casting*/

EXPLANATION:
In the following Example 1 will give the result 98. Since the variable y is an integer
type it holds the value 98.
Let’s convert it into programming.
/*Programming Conversion of Example 1*/
#include<stdio.h>
void main()
{
float x=98.92;
int y=x;/*automatic type casting*/
printf(“Value of x is:%f and value of y is:%d”, x, y);
}

Output:
Value of x is: 98.920000 and value of y is: 98
Example 2 of Implicit Type Casting
float y;
y=9/2;

EXPLANATION:
In the above Example 2 will give the result 4.0 instead of 4.5. Because 9/2 is taken
as an integer division and its result is integer type. To get the floating type value the
expression should like this:
y=9.0/2;
or
y=9.0/2.0;
or
y=9/2.0;
The above expression can give the result 4.5.
96 Concepts and Techniques of Programming in C

/*Programming Conversion of Example 2*/


#include<stdio.h>
void main()
{
float x=9/2.0;
printf(“Value of x=%f”, x);
}

Output:
Value of x=4.50000
Example 3 of Implicit Type Casting
float z;
int x=5;
int y=2;
z=x/y;

EXPLANATION:
In the example the z value will be 2.0 instead of 2.5. To get the value 2.5 we need to
convert it into explicit type.
Example 4 of implicit Type Casting:
int z;
float x=3.0;
float y=2.0;
z=x/y;

EXPLANATION:
The output will be 1 because after dividing the two float values the result will be 1.5.
But compiler will type cast it to int type and assigned to z. so the value will be 1.
/*Programming Conversion of Example 6*/
#include<stdio.h>
void main()
{
int z;
float x=3.0;
float y=2.0;
z=x/y;
printf(“Value of z=%d”,z);
}

Output:
Value of z is: 1
C Operator 97

5.3.2 Explicit Type Conversions


In some situations, the programmer/beginner wants to convert one data type into
another data type forcefully is called explicit type casting.
Example 4:
float z=(flaot)9/2;
Example 5:
float z=x/(float)y;
float(y) means convert y to float type.
Or
z=(float)x/(float)y;

/*Programming Conversion of Example 4*/


#include<stdio.h>
void main()
{
float x=(float)9/2;
printf(“Value of x=%f”, x);
}

/*Programming Conversion of Examples 5 of Explicit Type Casting*/


#include<stdio.h>
void main()
{
float z;
int x=5;
int y=2;
z=x/float(y);
printf(“Value of z is:%f”,z);
}

Output:
Value of z is: 2.50000
/*Program to Input Two Floating Point Numbers and Add the Two Values and Print
the Result as Integer Value*/
#include<stdio.h>
void main()
{
float x,y;
int z;
printf(“Input two floating values:”);
scanf(“%f%f”,&x,&y);
z=(int)x+(int)y;
printf(“Value of z:%d”,z);
}
98 Concepts and Techniques of Programming in C

Output:
Input two floating values: 5 4.8
Value of z is: 9

TIPS TO REMEMBER
When converting one data type to another data types it is best to convert lower data
types to higher data types because it avoids loss of data values.
When higher data type is going to convert into lower data type then data is truncated.

5.4 PRECEDENCE AND ORDER OF EVALUATIONS


When the arithmetic expressions do not have the parenthesis then it is evaluated from
left to right.
Arithmetic Expression Evolution Steps
1. During the first pass find out the highest priority and evaluate the first.
2. During the second pass find the lowest priority and evaluate it.
There are two priority levels of arithmetic operator. They are:

Table 5.5 Priorities of operators

Highest priority operator: * / %


Lowest priority operator: + -

Example:
PASS 1:
Q: X=8-6/2+5*2-1
Step 1:
Q: X=8-6/2+5*2-1
Go to the expression from left to right. Since in the first pass the objective is to find out
the highest priority operator, i.e., in that expression there are two operator, i.e., and
*.Since these two operators have equal priority, so these come first and it will evaluate
it, i.e., operator will be evaluated first.
Ans: X=8-3+5*2-1
Step 2:
Q: X=8-3+5*2-1
Ans: X=9-3+10-1
C Operator 99

PASS 2:
Q: X=9-3+10-1
Step 3:
Q: X=9-3+10-1
Ans: X=6+10-1
Step 4:
Q: X=6+10-1
Ans: X=16-1
Step 5:
Q: X=16-1
Ans: X=15 (FINAL)

Summary

1. Operator is a symbol which performs arithmetic and logical operations.


2. There are different types of operator, e.g., arithmetic, assignment, increment or
decrement, relational, logical, conditional and special operator.
3. Type casting refers to temporary conversion of one data type into another data
type.
4. There are two types of type casting
(a) Implicit type casting
(b) Explicit type casting
5. Implicit type casting automatically converts one data type into another data type.
6. Explicit type casting forcefully converts one data type into another data type.

SHORT QUESTIONS

1. What is an operator?
2. What is the difference between prefix operators and postfix operators?
3. What is major difference between = and == operator?
4. What is the role of sizeof operator?
5. What is relational operator. Give examples.
6. What two symbols are used in conditional operator?
7. What is a conditional operator?
8. What is increment and decrement operator?
9. What is type casting?
10. What is implicit type casting?
11. What is explicit type casting?
100 Concepts and Techniques of Programming in C

LONG QUESTIONS

1. Write short notes on automatic type conversion and type casting.


2. What is an operator? Discuss different types of operator with suitable examples.
3. Write a C program to find the greatest number among three using conditional
operator.

OBJECTIVE QUESTIONs WITH ANSWERs

1. What will be the output?


#include <stdio.h>
void main(void)
{
int x=5,y;
y=sizeof(x++);
printf(“X is: %d\n”, x);
printf(“Y is:%d”, y);
}
Output:
X is: 5
Y is: 2
2. What will be the output?
#include <stdio.h>
void main(void)
{
int z,x=5,y=1;
z=x++ + ++y;
printf(“%d %d %d”, z, x, y);
}
Output:
7, 6, 2
3. What will be the output?
#include <stdio.h>
void main(void)
{
int z,x=5,y=1;
z=x++ +++y;
printf(“%d %d %d”, z, x, y);
}
Output:
Compilation error
C Operator 101

4. What will be the output?


#include <stdio.h>
void main(void)
{
int x=5,y=5,z;
z=x++ + y;
printf(“%d %d %d”, z, x, y);
}
Output:
10, 6, 5
5. What will be the output?
#include <stdio.h>
void main(void)
{
int x=2,y=3,z=1;
printf(“%d, %d, %d”,++x + ++x+x++,x++ + ++y,++z + z++ + x++);
}
Output:
17, 7, 6
6. What will be the output?
#include <stdio.h>
void main(void)
{
int x=5,y=6;
if(x=6)
{
y--;
}
printf(“%d, %d”,x,y--);
}
Output:
6, 5
7. What will be the output?
#include <stdio.h>
void main(void)
{
int x=10,y;
y=x++ + x;
printf(“%d\n”, y);
}
Output:
20
102 Concepts and Techniques of Programming in C

8. What will be the output?


#include <stdio.h>
void main(void)
{
int x=6,y;
y=++x + x;
printf(“%d\n”, y);
}
Output:
14
9. What will be the output?
#include <stdio.h>
void main(void)
{
int x=6;
x=x++ + x;
printf(“%d”, x);
}
Output:
13
10. What will be the output?
#include <stdio.h>
void main(void)
{
int z=6,x,y;
x=z++;
y=++z;
printf(“%d %d\n”,x,y);
}
Output:
6, 8
11. What will be the output?
#include <stdio.h>
void main(void)
{
int x=12,y,z;
y=--x;
z=x--;
printf(“%d %d %d”,x,y,z);
}
Output:
10, 11, 11
C Operator 103

12. What will be the output?


#include <stdio.h>
void main(void)
{
int x=4,y=-5,z=2,a;
a=++x&&++y||++z;
printf(“\n%d %d %d %d”,x,y,z,a);
}
Output:
5, –4, 2, 1
13. What will be the output?
#include <stdio.h>
void main(void)
{
int x=12;
int z=(x++,++x);
printf(“%d”,z);
}
Output:
14
14. What will be the output?
#include<stdio.h>
void main(void)
{
char x[]=”C programming and Data Structure”;
int y=11;
printf(y>15?”C++ programming”:”%s”,x);
}
Output:
C programming and Data Structure
15. What will be the output?
#include<stdio.h>
void main(void)
{
int x,y=12;
x=(y<10)?20:15;
printf(“%d”,x);
}
Output:
15
104 Concepts and Techniques of Programming in C

16. What will be the output?


#include<stdio.h>
void main(void)
{
int x,y=4;
x=(y<12)?40:20;
printf(“%d %d”,x,y);
}
Output:
40, 4
17. What will be the output?
#include <stdio.h>
void main(void)
{
int x=10,y=5,z=15;
x>y?printf(“%d”,z):return z;
}
Output:
Compilation error
18. What will be the output?
#include <stdio.h>
void main(void)
{
int y=5;
if(y=4)
printf(“GOOD MORNING”);
else
printf(“GOOD EVENING”);
}
Output:
GOOD MORINING
19. What will be the output?
#include <stdio.h>
void main()
{
int x=12;
int y=0==1&&x++;
printf(“%d %d\n”,y,x);
}
Output:
0, 12
C Operator 105

20. What will be the output?


#include <stdio.h>
void main(void)
{
char x=’z’;
int y=(x%10)++;
printf(“%d\n”,y);
}
Output:
Compile time error
21. What will be the output?
#include <stdio.h>
void main(void)
{
unsigned int y=-20;
printf(“%d”,y);
}
Output:
–20
22. What will be the output?
#include <stdio.h>
void main(void)
{
int x=10,y=5;
x *= x + y;
printf(“%d\n”,x);
}
Output:
150
23. What will be the output?
#include <stdio.h>
void main(void)
{
int x=20,y=5;
x/=x/y;
printf(“%d\n”,x);
}
Output:
5
106 Concepts and Techniques of Programming in C

24. What will be the output?


#include <stdio.h>
void main(void)
{
int x=5,y=2;
x&&=y;
printf(“%d\n”,x);
}
Output:
Compile time error
25. What will be the output?
#include <stdio.h>
void main(void)
{
int x=9,y=8,z=10;
int m=x&&y||++z;
printf(“%d”,z);
}
Output:
10
26. What will be the output?
#include <stdio.h>
void main(void)
{
int x=1,y=0,z=10;
int m=x&&y&&z++;
printf(“%d”,m);
}
Output:
0
27. What will be the output?
#include <stdio.h>
void main(void)
{
int x=2,z=5;
int y=x<<4;
printf(“%d\n”,y);
}
Output:
32
C Operator 107

28. What will be the output?


#include <stdio.h>
void main(void)
{
int x=4,y=4,z=3;
int m=x&y|z;
printf(“%d”,m);
}
Output:
7
29. What will be the output?
#include <stdio.h>
void main(void)
{
int x=2;
if(x++&&(x==2))
printf(“INDIA\n”);
else
printf(“ODISHA\n”);
}
Output:
ODISHA
30. What will be the output?
#include<stdio.h>
void main()
{
int x=20,y=35;
x=y++ + x++;
y=++y + ++x;
printf(“x=%d,y=%d\n”,x,y);
}
Output:
x=57,y=94
31. What will be the output?
#include<stdio.h>
void main()
{
int x=3,y=6;
printf(“%d”,++(x+y));
}
Output:
Compilation error
108 Concepts and Techniques of Programming in C

32. What will be the output?


#include<stdio.h>
void main()
{
float a[15];
printf(“%d”,sizeof(a));
}
Output:
60
33. What will be the output?
#include<stdio.h>
void main()
{
int a=2;
if(a==2)
{
a=~a+2<<1;
printf(“%d”,a);
}
else
{
break;
}
}
Output:
Compilation error
Explanation:
Misplaced break and ambiguous operators and parenthesis.
6
Input and Output Operations in C

6.1 INTRODUCTION
In writing a complete computer program three basic operations are required. They
are reading data (taking data as input), processing the data and writing the data
(displaying the data). Generally, in writing any computer program the dates are taken
as input through keyboard and displayed on the computer screen as output. We have
seen in programming concept two important techniques are used to provide data to the
variable of that program. First one is assigning the values to the variable and second
one is to use the scanf() function which can take data from a keyboard. For displaying
the output the printf() function is used.
The C program does not have any built-in input or output statements as a part in
its syntax. So the input output operations are done through by using the scanf() and
printf() functions. There are several functions which are used for input and output
operations are called standard input/output library function. These functions are
predefined functions by the compiler. If the programmer wants to use any functions
from the standard I/O library then he should use the header file stdio.h in two different
ways, i.e., #include”stdio.h” or #include<stdio.h> compulsory.
In the current chapter we will study the different I/O functions that are not changed
by any machine.

6.2 READING A SINGLE CHARACTER


The getchar() function is used to read single character. This function is an alternative
of scanf() function.
/*Example of Reading a Character using scanf() Function*/
#include<stdio.h>
void main(void)
110 Concepts and Techniques of Programming in C

{
char m;
printf(“Search your Name\n”);
printf(“If yes type in keyboard X :”);
scanf(“%c”,&m);
if(m==’X’)
printf(“ I AM DHABAL PRASAD SETHI”);
else
printf(“your name do not find”);
}

Output:
Search your Name
If yes type in keyboard X: X
I AM DHABAL PRASAD SETHI

The syntax of reading a character using getchar() function is


variable_name=getchar();

Here in the above declaration getchar() function reads/takes only a single character
as input through keyboard and assigns it to the variable.
Example:
char ch;
ch=getchar();

/*Example of Reading a Character using getchar() Function*/


#include<stdio.h>
void main(void)
{
char m;
printf(“Search your name\n”);
printf(“if yes type X :”);
m=getchar();
if(m==’X’)
printf(“I AM DHABAL PRASAD SETHI”);
else
printf(“your name do not find”);
}

Output:
Search your name
If yes type X: X
I AM DHABAL PRASAD SETHI
Input and Output Operations in C 111

6.3 WRITING/DISPLAYING A SINGLE CHARACTER


The putchar() is a function used for writing character or displaying a single character
on the computer screen. It is an alternative of printf function.

The syntax of displaying a single character is:


putchar(variable);

Where the variable is a character variable containing a character.


/*Displaying a Character using printf() Function*/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input a character:”);
scanf(“%c”,&x); /*reading a character*/
printf(“The inputted character is:%c”,x); /*writing a character*/
}

Output:
Input a character: r
The inputted character is: r
/*Displaying a Character using putchar() Function*/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input a character:”);
x=getchar(); /*Reading(taking) input by using getchar() function*/
printf(“The inputted character is:”);
putchar(x); /*Displaying output by using putchar() function*/
}

Output:
Input a character: d
The input character is: d
/*Another Example of putchar() Function*/
#include<stdio.h>
#include<ctype.h>
void main(void)
{
112 Concepts and Techniques of Programming in C

char x;
printf(“Input the alphabet(lowercase or uppercase):”);
x=getchar();
if(islower(x))
{
printf(“The Upper case is:”);
putchar(toupper(x));
}
else
{
printf(“The Lower case is:”);
putchar(tolower(x));
}
}

Output:
Input the alphabet (lower case or upper case): d
The upper case is: D

6.4 FORMAT SPECIFICATIONS


Table 6.1 Format specifications used in the printf and scanf functions

integer data type----- short signed--------------------------- %d or %i


short unsigned------------------------ %u
long signed----------------------------- %ld
long unsigned------------------------- %lu
unsigned hexadecimal-------------- %x
unsigned octal------------------------- %o

real data type------- float-------------------------------------- %f


double----------------------------------- %lf
character data type-- signed character--------------------- %c
unsigned character------------------ %c
string data type---------------------------------------------------- %s

EXPLANATION:
The specifications are used in printf and scanf functions to read/take the data as input
or display output on the computer screen. If you want to read integer type data then
use %d. If you want to print the address of a variable then use %u. If you want to read
floating type input then use %f. If you want to read character type input then use %c.
If you want to read string types input then use %s.
Input and Output Operations in C 113

6.5 ESCAPE SEQUENCES


Table 6.2 Escape sequences

Escape sequences Meaning


\n New line (It moves the cursor to the next line)
\b Backspace (It moves the cursor to the previous position of the
current line)
\f Form feed (It moves the cursor to the beginning of the next logical
page)
\t Tab (It moves the cursor to the next horizontal tab position)
\v Vertical tab (It moves the cursor to the next vertical tab position)
\r Carriage return()
\a Alert (By using it the system produces the sound automatic)
\’ Single quote
\\ Backslash
\” Double quote

EXPLANATION:
The above table contains the escape characters .These are non-printable characters but
they have special meaning in displaying the output. These characters are generally used
in printf and scanf functions and must be preceded by a back slash (\).

6.6 MOSTLY USED HEADER FILES


Table 6.3 Header files

Header file Purpose


stdio.h This header file is used for standard input/output operation.
conio.h This header file is used for console input/output operation.
string.h This header file is used for string related function operation.
stdlib.h This header file is used for general function operation.
math.h This header file is used for mathematics related function operation.
time.h This header file is used for time and clock related operation.
ctype.h This header file is used for all character related function operations.

These header files are frequently used by programmers whenever they write a C
program.
114 Concepts and Techniques of Programming in C

6.7 DELIMITERS
These are the symbols used in C programming for syntactic meaning (Table 6.4).

Table 6.4 Delimiters list

Symbol Meaning
:------------------colon Used for label
;-------------------semicolon Used for end of the statement
()------------------parenthesis Used for passing arguments
[]-----------------square braces Used in array
{}-----------------curly braces Used for block of statements
#------------------hash Used for preprocessor directive
,-------------------comma Used for separating the variables

6.8 FORMATTED INPUT


Formatted input refers to reading of an input data through the keyboard arranged in
a specific format.
Example:
20.0 45 dhabal
The above sentence consists of three data, i.e., 20.0 45 and dhabal that are arranged
in a sequential order. The data has to be read to the format as it appears. So 20.0 will
read through the variable of type float, 45 will be read through the variable of type
integer and dhabal will be read through the variable of type char.
Reading the formatted input through scanf() function.

The syntax of scanf function is


scanf(“control string”,address1,address2------address-N);

The control string which contains the conversion specification character/format


specifiers and it should be within double quotes. The conversion specification character
may be one or more. Adress1, address2---address-N is the address of location where
data is stored. Control strings and address variable are separated by comma.

6.8.1 Inputting Integer Numbers


The field specification for reading an integer number is:
%wd
Input and Output Operations in C 115

The percentage (%) specifies that the conversion specification character, w stands for
integer number that represents the field width of the integer number, d is the format
specification character.
Example:
scanf(“%3d %5d”,&x,&y);

Input data are: 300 40555

In above data 300 is assigned to variable x and 40555 to y. if we reverse the above
data then

Input data are: 40555 300

Here, the first three digits 405 are assigned to variable x because %3d and rest value
of 40555, e.g., 55 is assigned to variable y. The value of 300 will be assigned to the next
scanf call. Let’s see the example
/*Examples of Inputting Integer Numbers*/
#include<stdio.h>
void main(void)
{
int x,y,a,b;
printf(“Input the two integer numbers:”);
scanf(“%3d%5d”,&x,&y);
printf(“You have inserted:”);
printf(“%3d %5d”,x,y);
printf(“\nInput the second two integer numbers:”) ;
scanf(“%3d %5d”,&a,&b);
printf(“You have inserted:”);
printf(“%3d %5d”,a,b);
}

Output:
Input the two integer numbers: 30455 300
You have inserted: 304 55
Input the second two integer numbers: 200 30455
You have inserted: 300 200

Explanation:
To solve the above error, do not use the width of the conversion specification character,
i.e., write the simple code of the scanf function.
scanf(“%d %d”,&x,&y);
116 Concepts and Techniques of Programming in C

If we use the same data 30455 300 then 30455 will be assigned to x and 300 are
assigned to y.

6.8.2 Inputting Real/Float Number


Inputting real numbers, the field width of real numbers is not specified, so scanf
function reads real numbers using simple specification %f. Examples is
scanf(“%f %f”,&x,&y);
If we give the data 34.60 20.78 as input then 34.60 will be assigned to x and 20.78
will be assigned to y.

6.9 FORMATTED OUTPUT


Formatted output means displaying the input data through keyboard in the computer
screen in a particular format.

The syntax of printf statements is


printf(“control string”,variable1,varibale2-----varibale-N);

The control string contains the format specification character and it should be within
double quotes. The variable should not be preceded by an ampersand (&) sign.
Example:
#include<stdio.h>
void main(void)
{
int x=10,y=20,z;
z=x+y;
Printf(“Sum of two number is:%d”,z);
}

Output:
Sum of two number is: 30

6.9.1 Formatted Output of Integer Numbers


The format specification for printing an integer number is:
%wd
where w stands for the minimum field width for the output, d is the format specification
character for integer number.
Input and Output Operations in C 117

(a) If the input number is greater than the field width, then it will print the full
number.
Let’s see the example
#include<stdio.h>
void main(void)
{
printf(“%2d”,590);
}

Output:

5 9 0

(b) If the input number is less then the specified field width then that number is
right justified with leading blank.
Let’s see
#include<stdio.h>
void main(void)
{
printf(“%5d”,590);
}

Output:

0 0 5 9 0

(c) It is possible to left justify the input number by placing the sign(-)minus after
the percentage sign.
#include<stdio.h>
void main(void)
{
printf(“%-5d”,590);
}

Output:

5 9 0

(d) It is possible to add zero, the leading blank, by placing a zero (0) after percentage
sign.
#include<stdio.h>
void main(void)
{
printf(“%05d”,590);
}
118 Concepts and Techniques of Programming in C

Output:

0 0 5 9 0

6.9.2 Output of Real Numbers


The syntax of displaying the output of a real number is:
%w.p f
where w is the field width of the input data, p is the number of digits to be displayed
after the decimal point (precision) and f is the conversion specification character.
Let’s see the example:
#include<stdio.h>
void main(void)
{
float x=20.345;
printf(“%6.3f\n”,x);
printf(“%f\n”,x);
printf(“%6.2f\n”,x);
printf(“%-6.2f”,x);
}

Output:

2 0 . 3 4 5

2 0 . 3 4 4 9 9 9

0 2 0 . 3 4

2 0 . 3 4

SUMMARY

1. The library functions which are used for input and output operations are called
input and output in C.
2. The getchar() function is used to read a single character.
3. The putchar() function is used to display/write a single character.
4. Formatted input means the input data is arranged in a particular format.
5. Formatted output means the output data is displayed in a particular format.
Input and Output Operations in C 119

SHORT QUESTIONS

1. What is input and output in C programming?


2. What is getchar() function?
3. What is putchar() function?
4. What is escape sequence?
5. What is conversion specification character?
6. What is delimiter?
7. What is formatted input?
8. What is formatted output?

LONG QUESTION

1. What is input/output operation in C? Also explain the formatted input and


output operations.

OBJECTIVE Questions WITH Answers

1. What will be the output?


#include <stdio.h>
void main()
{
int x;
scanf(“%d”,x);
printf(“%d”,x);
}
Output:
no output
2. What will be the output?
#include <stdio.h>
void main()
{
char *x;
scanf(“%s”,x);
}
Output:
no output
120 Concepts and Techniques of Programming in C

3. What will be the output?


#include <stdio.h>
void main(void)
{
char x[]=”LORDJAGATTNATH!”;
char y[13];
sscanf(x,”%s”,y);
printf(“%s\n”,y);
}
Output:
LORDJAGATTNATH
4. What will be the output?
#include <stdio.h>
void main()
{
short int x;
scanf(“%hd”, &x);
printf(“%hd”,x);
}
Output:
no output
5. What will be the output?
#include <stdio.h>
void main()
{
short int x;
scanf(“%*d”, &x);
printf(“%hd”,x);
}
Output:
no output
6. What will be the output?
#include <stdio.h>
void main()
{
int x=10,y=2;
printf(“%d\n”, printf(“%d %d “,x,y));
}
Output:
10 2 5
Input and Output Operations in C 121

7. What will be the output?


#include <stdio.h>
void main()
{
int x=10,y=3;
printf(“%d %d %d”,x,y);
}
Output:
10 3 3
8. What will be the output?
#include <stdio.h>
void main()
{
int x=10,y=5,z=6;
printf(“%d %d “,x,y,z);
}
Output:
10 5

MULTIPLE-Choice QUESTIONS

1. Find out the different one among the list?


(a) printf() (b) fprintf()
(c) putchar() (d) scanf()
[Answer: d]
2. Find out the different one among the list, which one is used to read input _______.
(a) scanf() (b) Files
(c) Command-line (d) None of the mentioned
[Answer: a]
3. What is the default return-type of getchar()?
(a) char
(b) char *
(c) Reading character doesn’t require a return-type
(d) int
[Answer: d]
4. The value of EOF is_____.
(a) 1 (b) 0
(c) –1 (d) 10
[Answer: c]
122 Concepts and Techniques of Programming in C

5. What is the use of getchar()?


(a) The next input character each time it is called
(b) EOF when it encounters end of file.
(c) Both a & b
(d) none of the above
[Answer: c]
6. What is the use of putchar() function?
(a) Nothing (b) The character written
(c) EOF is an error occurs (d) both b & c
[Answer: d]
7
Decision Making Statements
(Conditional Statements)

7.1 INTRODUCTION
When a beginner starts writing a C program, he tries to write the programming
statements which are generally executed in one sentence after another because he /she
does not know about selection or looping statements and these programming sentences
are called sequential programming. But practically all real-time programs are not
always executed in sequential order. There are some programming statements which
require to give condition. These statements are called decision making statements or
selection statements or branching statements or conditional statements. And there
are some other programming statements which require to be executed a number of
times and these statements are called iteration statements or looping statements. The
examples of conditional statements are: if the weather condition is sunny then probably
T20 cricket match may be played otherwise it will be cancelled. Other condition is, if
the bowler bowls fultos then it may be six/four otherwise he may be out.
There are three selection statements present in C programming. They are: 1) if
statement, 2) switch statement, 3) conditional operator.
In the above decision making or selection statements, the if statement is a two-way
branching statement whereas switch statement is a multiway branching statement.
Another decision making statement named conditional operator is explained in chapter
on operator.

TIPS TO REMEMBER
From the above statements we conclude that decision making statements mean
that it is a subset of control statements which decide some statements are going
to execute based on condition and other statements are going to execute based on
other condition.

Let’s discuss one of the decision statements, i.e., if statements first.


124 Concepts and Techniques of Programming in C

7.2 if STATEMENTS
The if statements are broadly categorized into different forms; e.g.

(a) simple if statement,


(b) if---else statement,
(c) nested if----else statement,
(d) else---if statement.

BRIEF DESCRIPTION OF if STATEMENT


7.2.1 Concepts of Simple if Statement
The simple if statement is a decision making or selection statement which is used to
make a test for each/individual/separate condition. If the condition becomes true then
the set of statement block inside the curly braces will be executed. If the condition does
not become true then the statement block will not execute and the control will jump
(move) to the next statements of if condition. If the statement block contains single
statement then it is mandatory to give curly braces, it is optional, e.g., you may give
curly braces or may not. If the statement block contains multiline statements then it is
compulsory to use the curly brace. Let’s see the different forms of simple if statements.

The syntax of if statement is


if (condition)
{
Set of statement block;
}
next statement;

The other syntax of if statement is:


if(condition)
statement1;
Or
if(condition)
{
statement1;
}

TIPS TO REMEMBER ABOUT if STATEMENT


When the condition of if statement becomes true then both the statement block as
well as next statements are executed in sequential manner.
Decision Making Statements (Conditional Statements) 125

False
Condition

True

Statements

Fig. 7.1 Flowchart of simple if statement

TIPS TO REMEMBER ABOUT if STATEMENT


• When there is one statement followed by if, there is no need for braces. But a good
programmer always tries to give curly braces while using if statements.
• The ‘if’ statement does not end with a semicolon.

7.2.2 Some Useful Programming Examples of If Statements


Q1. C Program Comparing Two Integer Numbers for Equality using if Statement
Solution:
/*************************************************************************
FILE NAME: if1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program comparing two integer number for equality
using if statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=10,y=10;
if(x==y)
{
printf(“x and y are equal”);
}
}

Output:
x and y are equal
126 Concepts and Techniques of Programming in C

EXPLANATION:
Here both x and y are initialized with the value 10.The if condition compared the two
values of x and y. Since the two values of x and y are matched, therefore x and y are
equal.
Q2. C Program for Finding Greatest Number between Two Integer Numbers using
if Statement
Solution:
/*************************************************************************
FILE NAME: if2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program of finding Greatest number between two integer
numbers using if statement
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main( void)
{
int x,y;
clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
if (x > y )
{
printf(“Inputted %d is greater than %d”,x,y);
}
getch();
}

Output:
Input the two integer numbers: 4 3
Input 4 is greater than 3
EXPLANATION:
Here the user entered the value 4 and 3 through keyboard by using the scanf() function.
Since the if condition is satisfied, i.e., if(4>3) so printf statement prints 4 is greater than 3.
Q3. C Program to Calculate the Absolute Value of an Integer Number.
Solution:
/*************************************************************************
FILE NAME: if3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to calculate the absolute value of an
integer number
*************************************************************************/
Decision Making Statements (Conditional Statements) 127

#include<stdio.h>
void main(void)
{
int x;
printf(“Input the integer number:”);
scanf(“%d”,&x);
if(x<0)
{
x=-x;
}
printf(“The absolute value of inputted integer number is:%d”,x);
}

Output:
Input the integer number:-5
The absolute value of input integer number is: 5

EXPLANATION:
Here the user entered the value as -5. The if condition checked, i.e., if( -5<0). Since
condition is satisfied then body part of if statement becomes x=-(-5), i.e., 5. So the printf
statement prints the absolute value is 5.
Q4. C Program to Find Greatest Number between Three Integer Numbers using if
Statement
Solution:
/************************************************************************
FILE NAME: if2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to find greatest number between three integer
numbers using
if statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
if(x>=y&&x>z)
printf(“Among the inputted three integer numbers %d is the largest”,x);
if(y>x&&y>=z)
printf(“Among the inputted three integer numbers %d is the largest”,y);
if(z>=x&&z>y)
printf(“Among the inputted three integer numbers %d is the largest”,z);
if(x==y&&y==z)
printf(“All three integer numbers are equal”);
}
128 Concepts and Techniques of Programming in C

Output:
Input the three integer numbers: 3 10 1
Among the input three integer numbers 10 is the largest

EXPLANATION:
Here the user entered the three integer numbers, i.e., 3, 10 and 1. Then each if condition
is checked. In the above program the second condition, i.e., if(10>1&&10>=1) is satisfied.
So 10 is the largest number. When more than one if condition are satisfied then each
printf statement followed by if will print the value.

7.2.3 Concepts of if-else Statement


The if-else statement is a two-way branching statement. When the if condition becomes
true then a single statement or block of statements inside the curly braces are executed
otherwise it becomes false and control moves to the else block and executed.

The syntax of if-else statement is:


if(condition)
{
statement block1;
}
else
{
statement block2;
}
next statements;

False
Condition?

True

Statement Statement
block 1 block 2

Statement
block 3

Fig. 7.2 Flowchart of else-if statements


Decision Making Statements (Conditional Statements) 129

7.2.4 Some Useful Programming Examples of if-else Statements


Q1. C Program to Check the Number is Even or Odd Number.
Solution:
/*************************************************************************
FILE NAME: ifelse1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the number is even or odd number.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x;
printf(“Input the integer number:”);
scanf(“%d”,&x);
if(x%2==0)
printf(“Inputted %d is the even number”, x);
else
printf(“Inputted %d is the odd number”, x);
}

Output:
Input the integer number: 4
Input 4 is an even number

EXPLANATION:
Here suppose the user entered the integer number as 4. The if condition is checked,
i.e., if (4%2==0). Since that condition is true so 4 is an even number. Here % is called
module operator or remainder operator.
Q2. C Program to Check the Character is Vowel or Consonant using if-else
Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the character is vowel and consonant
using if-else statements.
*************************************************************************/
#include<stdio.h>
void main(void)
{
char x;
130 Concepts and Techniques of Programming in C

printf(“Input a character:”);
scanf(“%c”,&x);
if(x==’a’||x==’A’||x==’e’||x==’E’||x==’i’||x==’I’||
x==’o’||x==’O’||x==’u’||x==’U’)
printf(“Inputted %c is the vowel “,x);
else
printf(“Inputted %c is the consonant “,x);
}

Output:
Input a character: a
Inputted a is the vowel

EXPLANATION:
Here the user entered the character ‘a‘ as input. Since ’a’ is matched with the given
condition so ‘a’ is a vowel. Hereafter if statement curly braces are not used because after
if statement single printf statement is there. Therefore, it is optional to use curly braces.
Q3. C Program to Check the Character is an Alphabet or Not.
Solution:
/*************************************************************************
FILE NAME: ifelse3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the character is alphabet or not
*************************************************************************/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input the character(alphabet or any /,’,””.etc):”);
scanf(“%c”,&x);
if((x>=’a’&&x<=’z’)||(x>=’A’&&x<=’Z’))
printf(“Inputted %c is an alphabet”, x);
else
printf(“Inputted %c is not the alphabet”,x);
}

Output:
Input the character (alphabet or any/, ’, ””, .etc): .
Input is not the character

EXPLANATION:
Here the user entered the character (.) as input. Then it checked the if condition. The
if condition does not match with(.) So else bock is executed, i.e., it prints(.) is not the
alphabet.
Decision Making Statements (Conditional Statements) 131

Q4. C Program to Check the Year is Leap Year or not using if-else Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the year is leap year or not using
if else statements
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x;
printf(“Input the year to check leap year:”);
scanf(“%d”,&x);
if((x%4==0 && x%100!=0)||(x%400==0))
{
printf(“Inputted %d is a leap year”,x);
}
else
{
printf(“Inputted %d is not a leap year”,x);
}
}

Output:
Input the year to check leap year: 2020
Input 2020 is a leap year

EXPLANATION:
Here the user entered the year 2020 to check the year is leap year or not. The if statement
is used to check the condition, i.e., if(2020%4==0&&2020%100!=0)||(2020%400==0).
As 2020%4==0 true and 2020%100=20 is true and condition 2020%400==0 is false. So
in if statement two conditions are given, i.e., first condition inside parenthesis true and
second condition inside parenthesis is false. Since in between two conditions OR symbol
is used. It means any of the above two conditions if any one condition becomes true
then the expression becomes true. As a result the year 2020 is a leap year.
Q5. C Program to Find Roots of the Quadratic Equation using if-else Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
132 Concepts and Techniques of Programming in C

DATE OF PROGRAM EXECUTION: 3/8/2015


NAME OF THE PROGRAM: C program to find roots of the quadratic equation
using if else statements.
*************************************************************************/
#include<stdio.h>
#include<math.h>
void main(void)
{
float x,y,z,d,m1,m2;
printf(“Input the floating values of x, y, z:”);
scanf(“%f%f%f”,&x,&y,&z);
d=y*y-4*x*z;
if(d>0)
{
m1=(-y+sqrt(d))/(2.0*x);
m2=(-y-sqrt(d))/(2.0*x);
printf(“root1 is:%5.2f,root2 is:%5.2f”,m1,m2);
}
else
printf(“roots are imaginary”);
}

Output:
Input the floating values of x, y, z: 2.0 4.0 -20.0
root1 is: 2.32, root2=-4.32

EXPLANATION:
Here the user entered the floating values 2.0, 4.0 and -20.0 as input. Then find the
discriminate. Since the discriminate values is greater than 0, so if condition is satisfied
and prints the two roots values.
Q6. C Program to Find the Greatest Number between Two Integer Numbers using
if-else Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to find greatest number between two integer
numbers using if-else statements.
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void )
{
int x,y;
Decision Making Statements (Conditional Statements) 133

clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
if (x > y )
{
printf(“Inputted %d is greater than %d”,x,y);
}
else
{
printf(“Inputted %d is less than %d”,x,y);
}
getch();
}

Output:
Input the two integer numbers: 2 3
Input 2 is less than 3

EXPLANATION:
Here the two inputs x and y are given, i.e., 2 and 3. In if condition the x value is not
greater than y. So the else block prints the result 2 is less than 3.

7.2.5 Concepts of Nested if-else Statement


Nested if-else means we may write the if-else statement within the body of the if
statement or within the body of the else statement.
Different forms of nested if-else statements syntax are:
1)if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else
{
statment3;
}
2)
if(condition)
statement1;
else
{
if(condition)
statement2;
else
statement3;
}
134 Concepts and Techniques of Programming in C

False
Condition 1?

True

False
Condition 2?

True

Statement Statement Statement


block 1 block 2 block 3

Statement
block 4

Fig. 7.3 Flowchart of a nested if-else statement

7.2.6 Some Useful Programming Examples of nested if-else Statements


Q1. C Program to Determine the Grade from user entered Marks using nested if-else
Statements
Solution:
/*************************************************************************
FILE NAME: nestif1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to determine the grade from user entered
marks using nested if-else statements
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x;
printf(“Input the marks between[90-60]:”);
scanf(“%d”,&x);
if(x>=90)
printf(“your grade is O”);
else
{
Decision Making Statements (Conditional Statements) 135

if(x>=80&&x<90)
printf(“Your grade is E”);
else
{
if(x>=70 &&x<80)
printf(“your grade is A”);
else
printf(“your grade is B”);
}
}
}

Output:
Input the marks between [90-60]:80
Your grade is E

EXPLANATION:
Here the user entered the marks 80 as input. That marks will check with the given
condition. In the above program if(80>=80&80<90) condition is satisfied. So it prints
your grade is E.
Q2. C Program for Finding the Greatest Number between Three Integer Numbers
using nested if-else Statements.
Solution:
/*************************************************************************
FILE NAME: nestif2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program of finding greatest number between three
integer numbers using nested if-else Statements
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
if(x>=y)
{
if(x>z)
{
printf(“Among the inputted three integer numbers %d is the greatest”,x);
}
else
{
printf(“Among the inputted three integer numbers %d is the greatest”,z);
}
}
136 Concepts and Techniques of Programming in C

else
{
if(y>z)
{
printf(“Among the inputted three integer numbers %d is the greatest”,y);
}
else
{
printf(“Among the inputted three integer numbers %d is the greatest”,z);
}
}
}
Output:
Input the three integer numbers: 3 18 1
Among the input three integer numbers 18 is the greatest
EXPLANATION:
Here the three inputs are entered, i.e., 3 18 and 1. The three values are checked in each
condition. In nested if else statement if the first condition is true then it will check the
inner condition. Since the first condition is not true so control goes to the else block.
In else block the if conditions satisfied, i.e., if(18>1) So 18 is the result as the greatest
number.

7.2.7 Concepts of else-if Statement/Ladder


The else-if statement is used to check the condition in sequential order, i.e., one statement
after another. When any one condition among the list of conditions becomes true, it
does not require to check the next condition. When the first condition becomes false,
the it checks for all conditions one after one until it becomes true. When all conditions
become false then else block is the default to execute.

The syntax of else-if statement is:


if (condition1)
{
Statement block1;
}
else if(condition2)
{
Statement block2;
}
else if(condition-n)
{
Statement block-n;
}
else
{
Default statement;
}
Next statement;
Decision Making Statements (Conditional Statements) 137

The else if is the way of arranging the else statement with the if statement.
Let’s see the difference in the boxes

if(x==1)
printf(“good morning”);
else
{
if(x==2)
printf(“good evening”);
}

if(x==1)
printf(“good morning”);
else if(x==2)
printf(“good evening”);

Condition 1?

Condition 2?

Statement
block1
Condition-N?
Statement
block2
Default
statement

Statement
block-N

Fig. 7.4 Flowchart of else-if statement

7.2.8 Some Useful Programming Examples of else-if Statements/Ladder

Q1. C Program to Find Greatest Number between Three using Else if Statement.
138 Concepts and Techniques of Programming in C

Solution:
/************************************************************************
FILE NAME: elseif1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to find greatest number between three using
else if statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”, &x, &y, &z);
if(x>=y&&x>z)
printf(“Among the inputted three integer numbers %d is the greatest “, x);
else if(y>x && y>=z)
printf(“Among the inputted three integer numbers %d is the greatest “, y);
else if(z>=x&&z>y)
printf(“Among the inputted three integer numbers %d is the greatest “, z);
else
printf(“All the three integer numbers are equal”);
}

Output:
Input the three integer numbers: 3 10 6
Among the input three integer numbers 10 is the greatest

EXPLANATION:
Here inputs are x as 3, y as 10 and z as 6. The inputs are checked with each condition.
When any one condition satisfies then it will stop for checking next condition and
control does not move to the next statements. In the above three inputs are checked
with the first condition, i.e., 3 is not greater than equal to y and 3 is not greater than 6
so the first condition is not satisfied. Then it check with the second condition, i.e., 10>3
and 10>6. Since this condition is satisfied so it will print 10 as the greatest number.
Q2. C Program to Determine the Year is Leap Year or not using else-if Statement.
Solution:
/************************************************************************
FILE NAME: elseif2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to determine the year is leap year or not
using else if statement.
*************************************************************************/
Decision Making Statements (Conditional Statements) 139

#include <stdio.h>
#include<conio.h>
int main(void)
{
int y;
clrscr();
printf(“Input the year to check leap year or not:”);
scanf(“%d”,&y);
if(y%400== 0)
printf(“Inputted %d is a leap year”, y);
else if(y%100== 0)
printf(“Inputted %d is not a leap year”, y);
else if(y%4==0)
printf(“Inputted %d is a leap year”, y);
else
printf(“Inputted %d is not a leap year”, y);
getch();
return 0;
}

Output:
Input the year to check leap year or not: 2012
Input 2012 is a leap year.

EXPLANATION:
Here the user entered the year 2012. The input is checked with each condition. In the
above example the first condition 2012%400 is not equal to zero, then it checked the
second condition, i.e., 2012 %100 is not equal to zero so checked the third condition,
i.e., 2012%4 is equal to zero. So the third condition will print the 2012 is a leap year.
Q3. C Program to Determine the Temperature Condition of each Day entered by User
using else-if Statements.
Solution:
/*************************************************************************
FILE NAME: elseif3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to determine the temperature condition of
each day entered by user using else if statements
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x;
clrscr();
printf(“Input the Temperature:”);
140 Concepts and Techniques of Programming in C

scanf(“%f”,&x);
if(x<=0)
{
printf(“The weather condition of today is very cold”);
}
else if(x>0&&x<=10)
{
printf(“The weather condition of today is cold”);
}
else if(x>10&&x<=20)
{
printf(“The weather condition of today is cool out”);
}
else if(x<=30&&x>20)
{
printf(“The weather condition of today is warm”);
}
else
{
printf(“The weather condition of today is hot”);
}
getch();
}

Output:
Input the temperature: 50
The weather condition of today is hot.

EXPLANATION:
The input 50 is checked in the above each condition. Since the input is not matched
with the above condition so else block will display the output.
Q4. C Program to Select your Favorite Color using else-if Statements.
Solution:
/************************************************************************
FILE NAME: elseif4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to select your favorite color using else
if statements
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x;
printf(“MY FAVORITE COLORS\n”);
Decision Making Statements (Conditional Statements) 141

printf(“1.RED COLOR\n2.GREEN COLOR\n3.YELLOW COLOR\n4.BLUE COLOR\n5.PINK


COLOR\n6.ORANGE COLOR\n”);
printf(“ From[ 1 to 6] to select the colors:”);
scanf(“%d”,&x);
if(x==1)
{
printf(“ My favorite color is RED COLOR”);
}
else if(x==2)
{
printf(“My favorite color is GREEN COLOR”);
}
else if(x==3)
{
printf(“My favorite color is YELLOW COLOR”);
}
else if(x==4)
{
printf(“My favorite color is BLUE COLOR”);
}
else if(x==5)
{
printf(“My favorite color is PINK COLOR”);
}
else if(x==6)
{
printf(“My favorite color is ORANGE COLOR”);
}
else
{
printf(“ You did not select your favorite color”);
}
getch();
}

Output:
1st Run
MY FAVORITE COLORS
1. RED COLOR
2. GREEN COLOR
3. YELLOW COLOR
4. BLUE COLOR
5. PINK COLOR
6. ORANGE COLOR
From [1 to 6] to select the colors: 6
My favorite color is ORANGE COLOR
2nd Run
MY FAVORITE COLORS
142 Concepts and Techniques of Programming in C

1. RED COLOR
2. GREEN COLOR
3. YELLOW COLOR
4. BLUE COLOR
5. PINK COLOR
6. ORANGE COLOR
From [1 to 6] to select the colors:7
You did not select your favorite color

EXPLANATION:
Here the user enters the number 6 .The else if statement tells that when one condition
in the above conditions is true then it does not go to the next condition. When all
conditions become false the else block is the result. So from the definition, the condition,
i.e., else if(6==6) is satisfied so orange color is the output.
Q5. C Program to Print Day of Your Birthday.
Solution:
/*************************************************************************
FILE NAME: elseif5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to print day of your birthday name
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x;
printf(“WEEK_SRNO BIRTHDAY\n1.MONDAY\n2.TUESDAY\n3.WEDNESDAY\n4.THRUSDAY\
n5.FRIDAY\n 6.SATURDAY\n”);
printf(“Input your birthday serial number[1-7]:”);
scanf(“%d”,&x);
if(x==1)
{
printf(“My birthday falls on MONDAY”);
}
else if(x==2)
{
printf(“My birthday falls on TUESDAY”);
}
else if(x==3)
{
printf(“My birthday falls on WEDNESDAY”);
}
else if(x==4)
{
printf(“My birthday falls on THURSDAY”);
Decision Making Statements (Conditional Statements) 143

}
else if(x==5)
{
printf(“My birthday falls on FRIDAY”);
}
else if(x==6)
{
printf(“My birthday falls on SATURDAY”);
}
else if(x==7)
{
printf(“My birthday falls on SUNDAY”);
}
else
{
printf(“Invalid number”);
}
}
Output:
WEEK_SRNO BIRTHDAY
1. MONDAY
2. TUESDAY
3. WEDNESDAY
4. THURSDAY
5. FRIDAY
6. SATURDAY
Input your birthday in serial number [1-7]:6
My birthday falls on SATURDAY
EXPLANATION:
Follow the same principle of above else if condition.
Q6. C Program to Print Number of Days in a Month.
Solution:
/************************************************************************
FILE NAME: elseif6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to print number of days in a month.
*************************************************************************/
#include <stdio.h>
int main(void)
{
int x;
printf(“Input the month number[1-12]:”);
scanf(“%d”,&x);
144 Concepts and Techniques of Programming in C

if(x==1)
{
printf(“The month Jan is 31 days”);
}
else if(x==2)
{
printf(“The month Feb is 28/29 days”);
}
else if(x==3)
{
printf(“The month March is 31 days”);
}
else if(x==4)
{
printf(“The month April is 30 days”);
}
else if(x==5)
{
printf(“The month May is 31 days”);
}
else if(x==6)
{
printf(“The month Jun is 30 days”);
}
else if(x==7)
{
printf(“The month July is 31 days”);
}
else if(x==8)
{
printf(“The month August is 31 days”);
}
else if(x==9)
{
printf(“The month September is 30 days”);
}
else if(x==10)
{
printf(“The month October is 31 days”);
}
else if(x==11)
{
printf(“ The month November is 30 days”);
}
else if(x==12)
{
printf(“The month December is 31 days”);
}
else
{
Decision Making Statements (Conditional Statements) 145

printf(“You choose Invalid month number”);


}
return 0;
}
Output:
Input the month number [1-12]:2
The month Feb is 28/29 days

EXPLANATION:
Follow the same principle of above else if condition.

7.3 CONCEPTS OF switch case STATEMENT


The switch statement is another selection control statement. It is also known as multi-
way decision making statement. It is the alternative of many if statements and has
many conditions. It runs faster than if statement. The switch statement is used to select
a choice from a larger number of choices. When any one choice matches among the
series of choices then associate block of statements with that case is executed otherwise
default statement is the optional case to execute, i.e., when any case does not match
with given input values then default statement will be executed.
The break statement is used in each case statement to stop a particular case statement
and the control moves from switch statement to the next statement. If we do not write
break statement in each case then the result of the program will be unexpected, e.g., if
we select one case among the list then it will display the selected case along with the
rest of the cases in the list.

The syntax of switch case statement is


switch(variable or expression)
{
case constant1:
statements;
break;
case constant2:
statements;
break;
case constant3:
statements;
break;
-----------
-----------
default:
statements;
break;
}
Next statements;
146 Concepts and Techniques of Programming in C

Examples of Valid Case Statements are


case 2:
case’e’:
case4+3:
case’b>’c’:

Examples of Invalid Case Statements are


case “third”:
case 6.3:
case z:
case d>e:
case z+2:
case 4,2,9:
case 2:7:3:

7.3.1 Some Useful Programming Examples of switch case Statements


Q1. Example of Not using Break Statement in switch case Statements.
Solution:
/*************************************************************************
FILE NAME: switch1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: example of not using break statement in switch case
statements
*************************************************************************/
#include<stdio.h>
void main(void)
{
int ch;
printf(“1.BTECH\n 2.MTECH\n 3.MCA\n 4.BPHARMA\n 5.MPHARMA\n 6.DIPPLOMA”);
printf(“Select your favorite courses[1-6]:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“You liked BTECH\n”);
case 2:
printf(“You liked MTECH\n”);
case 3:
printf(“You liked MCA\n”);
case 4:
printf(“You liked BPHARMA\n”);
case 5:
printf(“You liked MPHARMA\n”);
case 6:
printf(“You liked DIPPLOMA\n”);
default:
Decision Making Statements (Conditional Statements) 147

printf(“ You entered Invalid choice”);


}
}

Output:
1. BTECH
2. MTECH
3. MCA
4. BPHARMA
5. MPHARMA
6. DIPPLOMA
Select your favorite courses [1-6]:3
You liked MCA
You liked BPHARMA
You liked MPHARMA
You liked DIPPLOMA

EXPLANATION:
In the above program the menu contains different courses. When the user entered the
choice 3 then four statements are displayed instead of selecting one. Because break
statement is not used in that program. Therefore, to select any one course in the list,
always use break keyword in each case statement at the end. The correct program is
written in Q2.

TIPS TO REMEMBER ABOUT switch case STATEMENT


• Always use break statement in case of switch case statement.

Q2. C Program to Select the Favorite Courses using switch case Statement without
using Break Statement.
OR
Q. Example of not using Break Statement in switch case Statements.
Solution:
/*************************************************************************
FILE NAME: switch2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to check the selecting the favorite courses
using switch case statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
148 Concepts and Techniques of Programming in C

int ch;
printf(“1.BTECH\n 2.MTECH\n 3.MCA\n 4.BPHARMA\n 5.MPHARMA\n 6.DIPPLOMA”);
printf(“Select your favorite course[1-6]:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“You liked BTECH\n”);
break;
case 2:
printf(“You liked MTECH\n”);
break;
case 3:
printf(“You liked MCA\n”);
break;
case 4:
printf(“You liked BPHARMA\n”);
break;
case 5:
printf(“You liked MPHARMA\n”);
break;
case 6:
printf(“You liked DIPPLOMA\n”);
break;
default:
printf(“You entered Invalid choice”);
break;
}
}
Output:
1. BTECH
2. MTECH
3. MCA
4. BPHARMA
5. MPHARMA
6. DIPPLOMA
Select your favorite course [1-6]:4
You liked BPHARMA
EXPLANATION:
Since break keyword is used in each case statement at the end therefore when the user
enters 4 as his choice then it will display BPHARAMA.
Q3. C Program for Selecting the Favorite Day using switch case Statement.
Solution:
/*************************************************************************
FILE NAME: switch3.c
Decision Making Statements (Conditional Statements) 149

AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program of selecting the favorite day using switch
case statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int day;
printf(“1.Sunday\n 2.Monday\n 3.Tuesday\n 4.Wednessday\n 5.Thrusday\n
6.Friday\n 7.Saturday\n”);
printf(“Select your favorite day[1-6]:”);
scanf(“%d”,&day);
switch(day)
{
case 1:
printf(“You liked Sunday”);
break;
case 2:
printf(“You liked Monday”);
break;
case 3:
printf(“You liked Tuesday”);
break;
case 4:
printf(“You liked Wednesday”);
break;
case 5:
printf(“You liked Thursday”);
break;
case 6:
printf(“You liked Friday”);
case 7:
printf(“You liked Saturday”);
break;
break;
default:
printf(“you entered invalid choice”);
}
}

Output:
1. Sunday
2. Monday
3. Tuesday
4. Wednesday
5. Thursday
150 Concepts and Techniques of Programming in C

6. Friday
7. Saturday
Select your favorite day [1-6]:2
You liked Monday
Q4. C Program of Simple Calculator using switch case Statement.
Solution:
/*************************************************************************
FILE NAME: switch4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program of simple calculator using switch case
statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“Menu\n1.Addition\n2.Subtarction\n3.Multiplication\n4.Division\
n5.Reminder\n”);
printf(“Select your choices[1-5]:”);
scanf(“%d”,&m);
switch(m)
{
case 1:
z=x+y;
printf(“The addition of inputted two integer numbers is:%d\n”,z);
break;
case 2:
z=x-y;
printf(“The subtraction of inputted two integer numbers is:%d\n”,z);
break;
case 3:
z=x*y;
printf(“The multiplication of inputted two integer numbers is:%d\n”,z);
break;
case 4:
z=x/y;
printf(“The division of inputted two integer numbers is:%d\n”,z);
break;
case 5:
z=x%y;
printf(“The reminder of inputted two integer numbers is:%d\n”,z);
break;
default:
Decision Making Statements (Conditional Statements) 151

printf(“You have selected invalid choice”);


}
}
Output:
Input the two integer numbers: 2 8
Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Remainder
Select your choices [1-5]:1
The addition of input two integer numbers is: 10

EXPLANATION:
In the above program the output is 10 because the two integer numbers 2 and 8 are
added.
Q5. C Program to Check the Alphabet is a Vowel or a Consonant.
Solution:
/*************************************************************************
FILE NAME: switch4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the alphabet is vowel or consonant
*************************************************************************/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input the alphabets:”);
scanf(“%c”,&x);
switch(x)
{
case’a’:
case ‘A’:
case’e’:
case ‘E’:
case’i’:
case ‘I’:
case’o’:
case ‘O’:
case’u’:
case ‘U’:
printf(“%c is the vowel”,x);
break;
152 Concepts and Techniques of Programming in C

default:
printf(“The Inputted %c is the consonant”);
}
}

Output:
Input the alphabets: u
The inputted u is a vowel
Q6. C Program of Award Grades by Bput In Lieu of Marks in the Ranges using
switch case Statement.
Solution:
/************************************************************************
FILE NAME: switch5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program of award grades by BPUT in lieu of marks
in the ranges using switch case statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,marks;
printf(“ BPUT GRADATAION SYSTEM\n1.90% and above\n 2.80% to 89%\n 3.70% to
79%\n 4.60% to 69%\n 5.50% to 59%\n 6.37% to 49%\n 7.Less then 37%\n”);
printf(“Select the choice[1-6]:”);
scanf(“%d”,&x);
printf(“Input the marks:”);
scanf(“%d”,&marks);
switch(x)
{
case 1:
if(marks>=90&&marks<=100)
printf(“Your grade is O”);
break;
case 2:
if(marks>=80&&marks<=89)
printf(“Your grade is E”);
break;
case 3:
if(marks>=70&&marks<=79)
printf(“Your grade is A”);
break;
case 4:
if(marks>=60&&marks<=69)
printf(“Your grade is B”);
break;
Decision Making Statements (Conditional Statements) 153

case 5:
if(marks>=50&&marks<59)
printf(“Your grade is C”);
break;
case 6:
if(marks>=37&&marks<=49)
printf(“Your grade is D”);
break;
case 7:
if(marks>=0&&marks<37)
printf(“Your grade is F”);
break;
default:
printf(“Invalid choice”);
}
}

Output:
BPUT GRADATION SYSTEM
1. 90% and above
2. 80% to 89%
3. 70% to 79%
4. 60% to 69%
5. 50% to 59%
6. 37% to 49%
7. Less then 37%
Select the choice [1-6]:2
Input the marks: 85
Your grade is E

TIPS TO REMEMBER ABOUT switch case STATEMENT


• The case statement in switch case statements may be placed in any order, i.e., case
3 may come before case 1.
• When you want to execute a common set of statements for multiple cases use
switch case statements. Program of checking vowel and consonant is an example.
• Multiple statements to be executed in each case do not require the curly braces
like if else statements.
• In switch case statement if a statement does not belong to any case the compiler
does not give the error report.
• If we compare the switch statement with the if statement, which one is better?
Answer is: switch is better because it gives a better choice of writing the program
in comparison to if statement.
• When no break statement is written in the case statement then when the user
selects one case statement all other case statements after that case will be displayed.
154 Concepts and Techniques of Programming in C

Summary

1. In if statement the condition is tested, if condition becomes true then statement


block will be executed otherwise control jumps to the next statements.
2. In if-else statements when condition becomes true then statement block of if will
execute, otherwise else block will be executed.
3. The else-if statements are used to check the condition in sequential manner. When
one condition becomes false it checks another condition. When all conditions
become false else block is executed.
4. Switch statements are used to select a choice from a number of choices.

SHORT QUESTIONS

1. What is if statements?
2. What is an if-else statement?
3. What is an else-if statement?
4. What is switch statement?

LONG QUESTIONS

1. C program to find the greatest number between the three using else-if statements.
2. C program to find roots of the quadratic equation using if-else statements.
3. C program to check alphabet is a vowel or a consonant.
4. C program for detecting the grade of marks in the ranges using switch case
statements.
5. C program to evaluate the power series ex=1+x+x2/2!+x3/3!+----------xn/n! Using
if else statement

OBJECTIVE Questions WITH Answers

1. What will be the output?


#include<stdio.h>
void main()
{
int x=y=z=10;
x=y=z=20;
printf(“%d%d%d”,x,y,z);
}
Output:
Compilation error
Decision Making Statements (Conditional Statements) 155

2. What will be the output?


#include<stdio.h>
void main()
{
int x=4;
float y=4.0;
if(x==y)
printf(“Both y and z are equal”);
else
printf(“Both y and z are not equal”);
}
Output:
Both y and z are equal
3. What will be the output?
#include<stdio.h>
void main()
{
char x;
if(x=printf(“”))
printf(“INDIA\n”);
else
printf(“ODISHA\n”);
}
Output:
ODISHA
4. What will be the output?
#include<stdio.h>
void main()
{
float a=0.4;
if(0.4>a)
printf(“ODISHA\n”);
else
printf(“INDIA\n”);
}
Output:
ODISHA
Explanation:
Here out is ODISHA because 0.4 inside if statement is double type whose size is
8 bytes and size of variable a is 4 bytes because it is a floating type.
156 Concepts and Techniques of Programming in C

5. What will be the output?


#include<stdio.h>
void main()
{
int x=25,y,z;
if(x>=40)
{
y =25;
}
z=20;
printf(“%d,%d,%d\n”,x,y,z);
}
Output:
25, garbage value, 20
Explanation:
In the above program the value of x is 25 so printf statement prints the value 25
then since the condition if is not true, i.e., if(25>=40) is not true therefore value
of y=25 will not print. Therefore, value of y is not initialized therefore prints the
value garbage. Next value of z is assigned 20 so z value will display 20.
6. What will be the output?
#include<stdio.h>
void main()
{
int x=1;
if(!x)
printf(“C++ PROGRAMMING”);
else
{
printf(“C PROGRAMMING”);
}
}
Output:
C PROGRAMMING
7. What will be output?
#include<stdio.h>
void main()
{
int x=10,y=8,z=4;
if(x>y>z)
printf(“INDIA”);
else
Decision Making Statements (Conditional Statements) 157

printf(“ODISHA”);
}
Output:
ODISHA
Explanation:
The relational operator (>) is uses only two operands. Since it is applied on three
operands, inside the if condition therefore it is false. As a result else block will
display output as ODISHA.
8. What will be the output?
#include<stdio.h>
void main()
{
auto int x=6;
if(--x)
{
printf(“%d”,x);
}
}
Output:
5
9. What will be the output?
#include<stdio.h>
void main()
{
int x=3;
switch(x)
{
case 1:
printf(“INDIA\n”);
case 2:
printf(“ODISHA\n”);
case 3:
continue;
default:
printf(“LORD JAGATTNATH\n”);
}
}
Output:
Error(misplaces continue)
Explanation:
The output is error because continue keyword should not be used in switch case
statement. Continue keywords are allowed in looping.
158 Concepts and Techniques of Programming in C

10. What will be the output?


#include<stdio.h>
void main()
{
int x=4;
switch(x)
{
default:
printf(“This is default\n”);
case 1:
printf(“INDIA\n”);
break;
case 2:
printf(“ODISHA\n”);
break;
case 3:
printf(“PURI\n”);
}
}
Output:
This is default
Explanation:
Since the value of x=4 does not match with any case therefore default statement
will print the message.
11. What will be the output?
#include<stdio.h>
void main()
{
int x =1;
switch(x)
{
printf(“INDIA\n”);
case 1:
printf(“ODISHA\n”);
break;
case 2:
printf(“\nPURI\n”);
break;
}
}
Output:
ODISHA
Decision Making Statements (Conditional Statements) 159

Explanation:
The output is ODISHA because x value is 1 and it matched with case 1.
12. What will be the output?
#include<stdio.h>
void main()
{
int a=1;
switch(a/2)
{
case NULL:
printf(“case NULL\n”);
break;
case 0:
printf(“case ZERO\n”);
break;
default:
printf(“DEAFAULT”);
break;
}
}
Output:
Compilation error
Explanation:
Duplicate case in function main, i.e., case NULL: and case 0: both are same.
8
Looping

8.1 INTRODUCTION
8.1.1 When is Looping Required?
Loops are very useful and basic needs to programmers. When he/she wants to execute
any block of statements repeatedly and can be controlled by giving the condition. The
advantage of looping is that it saves time as well as writing the same programming
code multiple times. Suppose beginner wants to write a C program to print your name
and address 20 (or more) times. So, it creates headache for beginner to write 20 printf
statements to display the name and address. So to solve this problem he tries to use
looping. In looping he uses any one among three looping statements (e.g., while, do
while and for) and a printf statement is used inside the loop to print the name and
address 20 times.

8.2 CONCEPT OF LOOPING


The loop describes the process of executing a set of programming statements in the
act of following their order until the condition of the loop is not reached for stopping.
Alternatively, we can say that loop iterates the programming statements for a specific
number of times. If the loop does not execute properly then it makes the computer slow
and sometimes it may give infinite loop output. The looping of the program generally
consist of two parts, i.e., looping body part and control statement. The basic work of
control statement is to make a test for each condition at the beginning or at the end.
When that condition becomes true then the set of statements executes for fixed number
of times contained inside the curly braces. That set of statements enclosed with the curly
braces is called looping body part. The statements are examined before beginning or
starting the execution of loop (or before entering into the loop) is called entry controlled
Looping 161

loop. If the condition is true then body of the loop is executed otherwise it becomes
false and control goes out from the loop. But in exit controlled loop, the conditional
statements are examined at the end of the loop. When the condition becomes false then
body of the loop executes at least once.
The important things done by each programmer in looping are: first they initialize
the conditional variable, second make a test for each conditional variable, third to use
curly brace because those statements require executing number of times then they put
these inside curly braces, fourth is to increment and decrement the conditional variable.
There are three types of looping operations working in C programming. They
are: (a) while loop, (b) do while loop, (c) for loop.

8.2.1 Concepts of While Loop

The syntax of while loop is:


while(condition)
{
Statement block
}
Next statements

EXPLANATION:
A while loop is a control structure which is used to check the condition and the
condition is kept inside the parentheses preceded by using the keyword while at the
beginning of the loop. Generally, the conditions are numeric or alphanumeric. When
the condition becomes true then the statement block is executed inside the curly braces
repeatedly. When the condition is false, the while loop is stopped. After stopping the
loop, the program control moves to the next statements immediately after skipping
the body of the loop. This loop is also called an entry-controlled loop because at the
beginning condition is checked and if it is true, the statements inside the curly braces
are executed.

TIPS TO REMEMBER
• This is a good looping process with numeric applications.
• The programmer uses while loop when he does not know the number of iterations
required.
162 Concepts and Techniques of Programming in C

Input statement

Condition

Looping body part

Fig. 8.1 Flowchart of while loop

TIPS TO REMEMBER
• Do not give semicolon at the end of while statement but do not forget to give a
semicolon at the end of while in do while statement.
• When one statement is present inside the loop, then there is no requirement to
use the curly braces but good programmers can use it.
• Putting semicolon at the end of while and for statement is not a syntax error but
it is a logical error.

8.2.2 Some Useful Programming Examples of While Loop


Q1. C Program to Display Numbers from 1 To 15 using While Loop.
Solution:
/*************************************************************************
FILE NAME: while1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to display numbers from 1 to 15 using while
loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=1;
printf(“This is a program of displaying integer numbers from 1 to 15 using
while loop\n”);
while(x<=15)
{
Looping 163

printf(“ %d “,x);
x=x+1;
}
}

Output:
This is a program for displaying integer numbers from 1 to 15 using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

EXPLANATION:
Here x=1, while(1<=15) then print 1 and x increases to 2 and continue the loop until
x=15. When x=16 then the loop terminates. Therefore, the outputs are 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15
Q2. C Program of Conversion of Binary Number to Decimal Number.
Solution:
/*************************************************************************
FILE NAME: while2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: program of conversion of binary number to decimal number
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y=0,i=1,z;
printf(“This is a program of binary to decimal conversion\n”);
printf(“Input the binary Number:”);
scanf(“%d”,&x);
while(x!=0)
{
z=x%10;
y=y+z*i;
i=i*2;
x=x/10;
}
printf(“Decimal value of inputted binary number is:%d”, y);
}

Output:
This is a program of binary to decimal conversion
Input the binary Number:1111
Decimal value of input binary number is:15

EXPLANATION:
In the above program x = binary number, y = decimal number, z = remainder variable.
164 Concepts and Techniques of Programming in C

1st iteration
binary number=x=1111
while(1111!=0)
{
Remainder z=x%10=1111%10=1 e.g z=1
Decimal number =y=y+z*i=0+1*1=1
i=i*2=1*2=2
Binary number x=x/10=1111/10=111
}
2nd iteration
binary number=x=111
while(111!=0)
{
Remainder z=x%10=111%10=1 e.g z=1
Decimal number =y=1+1*2=3
i=2*2=4
Binary number x=x/10=111/10=11
}
3rd iteration
binary number=x=11
while(11!=0)
{
Remainder z=x%10=11%10=1 e.g z=1
Decimal number =y=y+z*i=3+1*4=7
i=i*2=4*2=8
Binary number x=x/10=11/10=1
}
4th iteration
binary number=x=1
while(1!=0)
{
Remainder z=x%10=1%10=0 e.g z=1
Decimal number =y=y+z*i=7+1*8=15
i=i*2=8*2=16
Binary number x=x/10=1/10=0
}
5th iteration
Loop terminates since binary number 0 is not equal to 0.
Q3. C Program to Convert Decimal to Binary using While Loop.
Solution:
/*************************************************************************
FILE NAME: while3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
Looping 165

DATE OF PROGRAM EXECUTION: 4/8/2015


NAME OF THE PROGRAM: c program to convert decimal to binary using while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
long int y,z=0,a=1;
int x,reminder;
printf(“This is a program of decimal to binary conversion\n”);
printf(“Input the decimal number:”);
scanf(“%d”,&x);
y=x;
while(x!=0)
{
reminder=x%2;
z=z+reminder*a;
x=x/2;
a=a*10;
}
printf(“The inputted value %ld in binary form is:%ld”,y,z);
}

Output:
This is a program of decimal to binary conversion
Enter the decimal number:12
The input value 12 in binary form is:1100

EXPLANATION:
The user enters the integer input as 12 then it assigns to y, i.e., y=12
1st iteration
while(12!=0)
{
reminder=12%2=0
z=0+0*1=0
x=12/2=6
a=1*10=10
}
2nd iteration
while(6!=0)
{
reminder=6%2=0
z=0+0*10=0
x=6/2=3
a=10*10=100
}
166 Concepts and Techniques of Programming in C

3rd iteration
while(3!=0)
{
reminder=3%2=1
z=0+1*100=100
x=3/2=1
a=100*10=1000
}
4th iteration
while(1!=0)
{
reminder=1%2=1
z=100+1*1000=1100
a=1000*10=10000
}
5th loop
Loop terminates.
Q4. C Program of Summation of Nth Term Natural Numbers E.G 1+2+3---N=N(N+1)/2
using While loop.
Solution:
/*************************************************************************
FILE NAME: while4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program of summation of nth term natural numbers
e.g 1+2+3---n=n(n+1)/2 suing while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,count=1,sum=0;
printf(“This is a program of summation of nth natural number\n”);
printf(“Input the nth term of natural number:”);
scanf(“%d”,&x);
while(count<=x)
{
sum=sum+count;
count++;
}
printf(“Summation of inputted nth term natural number is:%d”,sum);
}

Output:
This is a program of summation of nth natural number.
Looping 167

Input the nth term natural number:5


Summation of input nth term natural number is:15

EXPLANATION:
Suppose x=5
1st iteration
while(1<=5)
{
sum=0+1=1;
count=2;
}
2nd iteration
while(2<=5)
{
sum=1+2=3;
count=3;
}
3rd iteration
while(3<=5)
{
sum=3+3=6
count=4
}
4th iteration
while(4<=5)
{
sum=6+4=10;
count=5
}
5th iteration
while(5<=5)
{
sum=10+5=15
count=6
}
6th iteration
Loop terminates.

Q5. C Program of Count the Number of Digits of an Integer Number using While
Loops.
Solution:
/*************************************************************************
FILE NAME: while5.c
168 Concepts and Techniques of Programming in C

AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of count the number of digits of an integer
number using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,count=0;
printf(“This is a program of counting the number of digits of an integer
numbers\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x!=0)
{
x=x/10;
count++;
}
printf(“Number of digits of an inputted integer number is:%d”,count);
}

Output:
This is a program of counting the number of digits of integer numbers
Input the integer number: 123
Number of digits of an input integer number is: 3

EXPLANATION:
Suppose the input x=123
1st iteration
while(123!=0)
{
x=123/10=12;
count=1
}
2nd iteration
while(12!=0)
{
x=12/10=1
count=2
}
3rd iteration
while(1!=0)
{
x=1/10=0
count=3
}
Looping 169

4th iteration
Loop terminates.
Q6. C Program to Reverse a Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to reverse a number a using while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,rev=0;
printf(“This is a program of reverse an integer number\n”);
printf(“Input the integer number :”);
scanf(“%d”,&x);
while(x!=0)
{
reminder=x%10;
rev=rev*10+reminder;
x=x/10;
}
printf(“The reverse of inputted integer number is:%d”,rev);
}

Output:
This is a program of reverse an integer number
Input the integer number: 123
The reverse of input integer number is: 321

EXPLANATION:
Suppose the input x=123
1st iteration
while(123!=0)
{
reminder=123%10=3;
rev= rev*10+reminder =0*10+3=3
X=x/10=123/10=12
2nd iteration
while(12!=0)
{
reminder=12%10=2
rev= rev*10+reminder =3*10+2=32
170 Concepts and Techniques of Programming in C

X=x/10=12/10=1
}
3rd iteration
while(1!=0)
{
reminder=1%10=1
rev= rev*10+reminder =32*10+1=321
x=x/10=1/10=0
}

Q7. C Program to Check a Number is Palindrome using While Loop.


Solution:
/*************************************************************************
FILE NAME: while7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to check a number is palindrome using while
loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,rev=0,y;
printf(“This is a program of check a number is palindrome or not\n”);
printf(“Input the integer number :”);
scanf(“%d”,&x);
y=x;
while(x!=0)
{
reminder=x%10;
rev=rev*10+reminder;
x=x/10;
}
if(rev==y)
printf(“The inputted number %d is a palindrome”, y);
else
printf(“The inputted number %d is not a palindrome”, y);
}

Output:
This is a program to check a number is palindrome or not;
Input the integer number: 121
The input number 121 is a palindrome

EXPLANATION:
Looping 171

TIPS TO REMEMBER
A number is called palindrome when its digits are reversed and it remain the same.
Examples of palindrome number are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77,
88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191.

Before going to loop the user inputs number through scanf function and stored in
variable y and again that number is assigned to another variable rev. in reverse a
number logic, that number y is compared with another variable rev, if matched then
it is a palindrome number.
The logic of reverse a number is
1st iteration
while(121!=0)
{
reminder=121%10=1
rev=0*10+1;
x=121/10=12
}
2nd iteration
while(12!=0)
{
reminder=12%10=2
rev=1*10+2=12
x=12/10=1
}
3rd iteration
while(1!=0)
{
reminder=1%10=1
rev=12*10+1=121
x=1/10=0
}
4th iteration
In the 4th iteration the loop terminates.
After terminating the loop, the reversed number is compared with y which contains
the input number. If matches then that number is a palindrome number.
Q8. C Program to Check Number is Armstrong Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
172 Concepts and Techniques of Programming in C

DATE OF PROGRAM EXECUTION: 4/8/2015


NAME OF THE PROGRAM: c program to check number is Armstrong number using
while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,sum=0,y;
printf(“This is a program to check a number is Armstrong number or not\n”);
printf(“Input the integer number :”);
scanf(“%d”, &x);
y=x;
while(x!=0)
{
reminder=x%10;
sum=sum+(reminder*reminder*reminder);
x=x/10;
}
if(sum==y)
printf(“Inputted number %d is an Armstrong number”, y);
else
printf(“Inputted number %d is not an Armstrong number”, y);
}

Output:
This is a program to check a number is Armstrong number or not
Input the integer number: 153
Input number 153 is an Armstrong number

EXPLANATION:

TIPS TO REMEMBER
Those numbers whose sum of the cube of its digits is equal to that number are called
Armstrong numbers.
Example: 153=13+53+33=1+125+9=153
370=33+73+03=27+343=370
Others are 371,407

Before going to loop, enter the number through scanf function and assign it to another
variable y, then write the logic of program to find sum of the cube of digits of a number.
After that resultant number stored in sum and is compared with y variable, if matched
then it is an Armstrong number.
1st iteration
while(153!=0)
{
Looping 173

reminder=153%10=3
sum=0+(3*3*3)=27
x=153/10=15
}
2nd iteration
while(15!=0)
{
reminder=15%10=5
sum=27+(5*5*5)=152
x=15/10=1
}
3rd iteration
while(1!=0)
{
reminder=1%10=1
sum=152+(1*1*1)=153
x=1/10=0
}
4th iteration
The loop terminates.
After the loop terminates, sum is compared with y. If matches then that number is an
Armstrong number.
Q9. C Program to Display the Sum of Digits of an Integer Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to display the sum of digits of any integer
number using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,sum=0,r;
printf(“This is a program of sum of digits of an integer number\n”);
printf(“Input an integer number:”);
scanf(“%d”,&x);
while(x>0)
{
r=x%10;
sum=sum+r;
x=x/10;
}
printf(“Summation of digits of an inputted integer number is:%d”, sum);
}
174 Concepts and Techniques of Programming in C

Output:
This is a program of sum of digits of an integer number
Input an integer number: 123
Summation of digits of an inputted integer number is: 6
EXPLANATION:
Here the user enters the number through scanf function e.g. 123.
1st iteration
while(123>0)
{
r=123%10=3
sum=0+3=3
x=123/10=12
}
2nd iteration
while(12>0)
{
r=12%10=2
sum=3+2=5
x=12/10=1
}
3rd iteration
while(1>0)
{
r=1%10=1
sum=5+1=6
x=1/10==0
}
In the 4th iteration loop terminates.
Q10. C Program of Multiplication of Digits of an Integer Number using While
Loop.
Solution:
/*************************************************************************
FILE NAME: while10.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program of multiplication of digits of a integer
number using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
Looping 175

int x,multi=1,r;
printf(“This is a program of multiplication of digits of an integer
number\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x>0)
{
r=x%10;
multi=multi*r;
x=x/10;
}
printf(“Multiplication of digits of an inputted integer number is:%d”,multi);
}

Output:
This is a program of multiplication of digits of an integer number
Input the integer number: 123
Multiplication of digits of the input integer number is: 6

EXPLANATION:
Follow the above program, instead of addition use multiplication.
Q11. C Program to Find the Power of an Integer Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while11.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find the power of an integer number using
while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int power,x,i=1,total=1;
printf(“This is a program of finding the power of an integer number\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
printf(“Input the power of that number:”);
scanf(“%d”,&power);
while(i<=power)
{
total=total*x;
i++;
}
printf(“Power of inputted number %d is: %d “,x,total);
}
176 Concepts and Techniques of Programming in C

Output:
This is a program of finding the power of an integer number
Input the integer number: 2
Input the power of that number: 3
Power of input number 2 is: 8

EXPLANATION:
In the above program the user enters the number as 2 and power as 3.
1st iteration
while(1<=3)
{
total=total*x e.g 1*2=2
i++ e.g 2
}
2nd iteration
while(2<=3)
{
total=2*2=4
t++ e.g 3
}
3rd iteration
while(3<=3)
{
total=4*2=8
}
4th iteration
Loop terminates
Q12. C Program to Check the Number is a Perfect Number or not Using While Loop.
Solution:
/*************************************************************************
FILE NAME: while12.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to check the number is a perfect number or
not using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,j=1,sum=0;
printf(“This is a program to check a number is a perfect number or not\n”);
printf(“Input the integer number:”);
Looping 177

scanf(“%d”,&x);
while(j<x)
{
if(x%j==0)
sum=sum+j;
j++;
}
if(sum==x)
printf(“Inputted number %d is a perfect number”, x);
else
printf(“Inputted number %d is not a perfect number”, x);
}

Output:
This is a program to check a number is a perfect number or not
Input the integer number: 6
Input number 6 is a perfect number

EXPLANATION:
Because if the sum of the divisor of the number is equal to that number then we call
them perfect numbers. Examples of perfect number is 6 because divisor of 6 are 1, 2,
3. So sum of 1+2+3=6.
Q13. C Program to Find Gcd and Lcm of two Integer Numbers using While Loop.
Solution:
/*************************************************************************
FILE NAME: while13.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find GCD and LCM of two integer numbers
using while loop
*************************************************************************/
#include <stdio.h>
void main(void)
{
int m,n,x,y,t,gcd,lcm;
printf(“This is a program to find GCD and LCM of two integer numbers\n”);
printf(“Input two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=x;
n=y;
while(n!=0)
{
t=n;
n=m%n;
m=t;
}
178 Concepts and Techniques of Programming in C

gcd=m;
lcm=(x*y)/gcd;
printf(“Greatest common divisor of inputted %d and %d is:%d\n”,x,y,gcd);
printf(“Least common multiple of inputted %d and %d is:%d\n”,x,y,lcm);
}

Output:
This is a program to find GCD and LCM of two integer numbers
Input two integer numbers: 2 3
Greatest common divisor of input 2 and 3 is: 1
Least common multiple of input 2 and 3 is: 6
Q14. C Program to Find Gcd (Greatest Common Divisor) of two Numbers using
While Loop.
Solution:
/*************************************************************************
FILE NAME: while14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find GCD(greatest common divisor) of two
numbers using while loop.
*************************************************************************/
#include<stdio.h>
void main()
{
int x,y;
printf(“This is a program to find GCD two integer numbers\n”);
printf(“input two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“Gcd of two integer numbers[%d and %d] is:”,x,y);
while(x!=y)
{
if(x>y)
x=x-y;
else
y=y-x;
}
printf(“%d”,x);
}

Output:
This is a program to find GCD two integer numbers
Input two integer numbers: 4 2
GCD of two integer numbers [4 and 2]is:2
Looping 179

Q15. C Program to Find Lcm Between Two Integers using While Loop.
Solution:
/*************************************************************************
FILE NAME: while14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find LCM between two integer numbers
using while loop.
*************************************************************************/
#include<stdio.h>
void main()
{
int x,y,z,t1,t2;
printf(“This is a program to find LCM of two integer numbers\n”);
printf(“Input two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“LCM of two integer numbers[%d and %d] is:”,x,y);
t1=x;
t2=y;
while(t1!=t2)
{
if(t1>t2)
t1=t1-t2;
else
t2=t2-t1;
}
z=(x*y)/t1;
printf(“%d”,z);
}

Output:
This is a program to find LCM of two integer numbers
Input two integer numbers: 4 2
LCM of two integer numbers [4 and 2]is: 4
Q16. C Program to Find Sum of the First and the Last Digit of an Integer Number.
Solution:
/*************************************************************************
FILE NAME: while14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find sum of first and last digit of an
integer number.
*************************************************************************/
180 Concepts and Techniques of Programming in C

#include <stdio.h>
#include<conio.h>
void main(void)
{
int i,x,t=0;
clrscr();
printf(“This is a program to find sum of first and last digit of an integer
number\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
if(x>10)
{
t=t+x%10;
}
while(x>10)
{
x=x/10;
}
t=t+x;
printf(“Sum of first and last digit of that inputted number is:%d”,t);
getch();
}

Output:
This is a program to find the sum of the first and the last digits of an integer number
Input the integer number:123
Sum of first and last digits of that input number is: 4
Q17. Factorial of a Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: factorial of a number using while loop.
*************************************************************************/

#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,j,fact;
fact=j=1;
clrscr();
printf(“This is a program to calculate factorial of a number\n”);
printf(“Input the integer number to find factorial:”);
scanf(“%d”,&x);
Looping 181

while(j<=x)
{
fact*=j;
j++;
}
printf(“The Factorial of inputted %d is:%d”,x ,fact);
getch();
}

Output:
This is a program to find the sum of the first and the last digits of an integer number
Input the integer number to find factorial: 4
The factorial of input 4 is: 24
Q18. Fibonacci Series up to Nth Term using While Loop.
Solution:
/*************************************************************************
FILE NAME: while15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: Fibonacci series up to nth term using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=0,y=1,z=0,n;
printf(“This is a program to find Fibonacci series upto nth term\n”);
printf(“Input the number of terms:”);
scanf(“\n%d”,&n);
printf(“Fibonacci series are:%d %d”,x,y);
z=x+y;
while(z<n)
{
z=x+y;
x=y;
y=z;
printf(“ %d “,z);
}
}

Output:
This is a program to find Fibonacci series up to nth term
Input the number of terms: 5
Fibonacci series are: 0 1 1 2 3
182 Concepts and Techniques of Programming in C

8.2.3 Concepts of do While Loop


The do while loop is another control structure statement and is similar to the while loop.

The syntax of do while loop is


do
{
statement blocks
}
while(condition);
Next statements;

EXPLANATION:
In do while loop the condition is examined at the end of the loop instead of beginning,
whether it is true or false. If the condition becomes true then the program repeatedly
evaluates the statement blocks of the loop again and again. This evaluation process
continues until condition does not become false. When the condition is false then the
loop will stop immediately and control passes to the next statement after skipping the
while statements. This loop is also called exit-controlled loop therefore the body of the
loop is executed at least once.

Loop body part

False Exit while


Condition loop

True

Fig. 8.2 do while loop

8.2.4 Some Useful Programming Examples of do While Loop.


Q1. C Program to Display the Numbers from 1 to 15 using do While Loop
Solution:
/*************************************************************************
FILE NAME: dowhile1.c
Looping 183

AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to display the numbers from 1 to 15 using
do while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=1;
do
{
printf(“ %d “,x);
x=x+1;
}
while(x<=15);
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Explanation:
In the above example of do while loop first the value x=1 is printed inside the do
part and x value increments, i.e., x=2. And the last while condition is checked, i.e.,
while(2<=15); condition satisfied then control goes to the do part of the program again
and prints the value and continue the loop until it terminates.
Q2. C Program of Sum of Nth Natural Numbers using do While Loop.
Solution:
/*************************************************************************
FILE NAME: dowhile2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of sum of nth natural numbers using do
while loop
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,n,x=1;
printf(“Input the nth natural numbers:”);
scanf(“%d”,&n);
do
{
sum=sum+x;
x++;
184 Concepts and Techniques of Programming in C

}while(x<=n);
printf(“The summation of inputted nth natural number is:%d”,sum);
}

Output:
Input the nth natural number: 4
The sum of input nth natural number is: 10
Q3. C Program of Binary to Decimal Conversion using Do-While Loop.
Solution:
/*************************************************************************
FILE NAME: dowhile3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of binary to decimal conversion using do
while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y=0,i=1,z;
printf(“Input the binary Number:”);
scanf(“%d”,&x);
do
{
z=x%10;
y=y+z*i;
i=i*2;
x=x/10;
}
while(x!=0);
printf(“Decimal value of inputted binary number is:%d”,y);
}

Output:
Enter the binary number: 110
Decimal value of input binary number is: 6

EXPLANATION:
Here, user enters the input as 110
1st iteration
do
{
z=110%10=0
y=0+0*1=0
Looping 185

i=1*2=2
x=110/10=11
}while(110!=0);
2nd iteration
do
{
z=11%10=1
y=0+1*2=2
i=2*2=4
x=11/10=1
}while(11!=0);
3rd iteration
do
{
z=1%10=1
y=2+1*4=6(decimal form)
i=4*2=8
x=1/10=0
}while(1!=0);
4th iteration
Loop terminates.
Q4. C Program to Check the Armstrong Number using Do While Loop.
Solution:
/*************************************************************************
FILE NAME: dowhile4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to check the Armstrong number using do
while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,sum=0,y;
printf(“Input the integer number to check Armstrong number:”);
scanf(“%d”,&x);
y=x;
do
{
reminder=x%10;
sum=sum+(reminder*reminder*reminder);
x=x/10;
}
186 Concepts and Techniques of Programming in C

while(x!=0);
if(sum==y)
printf(“Inputted number %d is Armstrong number”,y);
else
printf(“Inputted number %d is not an Armstrong number”,y);
}

Output:
Input the integer number to check Armstrong number: 135
Input number 135 is not an Armstrong number

Assignment: Try to convert the above while loop programs into do while programs.

Comparison BETWEEN WHILE AND DO WHILE LOOP


In while loop it will first check the condition and then it enters into that loop. But in
do while loop it will enter the loop and then check for that condition. The do while
loop will run at least one time even if the test condition is false.

8.2.5 Concepts of for Loop


For loop is similar to the while and do while loop. For loops are generally used when
the set of statements which are to be executed a specific number of times, i.e., until
condition does not become false.

The syntax of for loop is:


for(initialization; condition; increment/decrement)
{
Statement block
}

EXPLANATION:
The above declaration consists of three parts, i.e., initialization, condition and increment/
decrement. In the initialization part, values are assigned to the variables and in the
condition part, if the condition is true then statement block of the loop will be executed
otherwise it will terminate. When the statement block of the loop is executed at first
iteration, at the that time program control moves to the increment part of the for loop.
In the second iteration, the variable’s value increases and again tests the condition, if it
again becomes true then statement block of the loop is executed and it continues until
the condition become true.
Looping 187

Variable initialization

Update statement

Condition Body part of for loop

Exit the for


loop

Jump to next
statements out the
for loop

Fig. 8.3 Flowchart of for loop

TIPS to REMEMBER ABOUT for LOOP


•  The for loop will be a good choice for a programmer, when the number of
repetition is known.

Advantages of for loop:


In for loop all the three parts, i.e., initialization, test condition and increment/
decrement is written in single statements.

TIPS TO REMEMBER ABOUT for LOOP


•  Do not give semicolon at the end of for loop expression.

Different styles of representing for loop are shown below Q1.

8.2.5.1 Multiple Initializations in for Loop


In for loop multiple variable initializations is possible by giving the symbol comma and
multiple incremental/decremented variables at the same time but only one statement
is allowed in the test expression.
for(int i=0,j=1;j<=10;j++)
188 Concepts and Techniques of Programming in C

8.2.5.2 Nested for Loop


Like nesting of if statement the while and for loop can be nested.

for(x=1;x<4;x++)
{

for(y=1;y<4;y++) /*inner loop*/


{
total=x+y; Outer loop
printf("x is: %d,y is: %d, total
is:%d\n", x, y, total);
}
} Inner loop

/*Simple Example of nested for Loop.*/


#include<stdio.h>
void main(void)
{
int x,y,n,total;
printf(“Input the number of loop:”);
scanf(“%d”,&n);
for(x=1;x<n;x++) /*outer loop*/
{
for(y=1;y<n;y++) /*inner loop*/
{
total=x+y;
printf(“x is:%d y is:%d total is:%d\n”,x,y,total);
}
}
}

Output:
Input the number of loop: 4
x is:1 y is:1 total is:2
x is:1 y is:2 total is:3
x is:1 y is:3 total is:4
x is:2 y is:1 total is:3
x is:2 y is:2 total is:4
x is:2 y is:3 total is:5
x is:3 y is:1 total is:4
x is:3 y is:2 total is:5
x is:3 y is:3 total is:6
Looping 189

EXPLANATION:
Here the outer loop is x and inner loop is y. The number of loop is 4. For each outer
loop of x, the inner loop y executes 3 times, i.e., for 3 outer loops, 3 inner loop executes,
i.e., 9 statements are executed.

8.2.6 Some Useful Programming Examples of for Loop


Q1. C Program to Display the Integer Numbers from 1 to 15 using for Loop.
Solution:
/*************************************************************************
FILE NAME: for1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to display the integer numbers from 1 to
15 using for loop
*************************************************************************/
1)#include<stdio.h>
void main(void)
{
int x;
for(x=1;x<=15;x++)
printf(“ %d “,x);
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2)#include<stdio.h>
void main()
{
int x;
for(x=1;x<=15;)
{
printf(“%d\t”,x);
x=x+1;
}
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
3)#include<stdio.h>
void main(void)
{
int x=1;
for(;x<=15;x=x+1)
printf(“%d\t”,x);
}
190 Concepts and Techniques of Programming in C

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
4)#include<stdio.h>
void main(void)
{
int x=1;
for(;x<=15;)
{
printf(“%d\t”,x);
x=x+1;
}
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
5)#include<stdio.h>
void main(void)
{
int x;
for(x=0;x++<15;)
printf(“%d\t”,x);
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Q2. C Program of Sum of Nth Natural Numbers using for Loop.
Solution:
/*************************************************************************
FILE NAME: for2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program of sum of nth natural numbers using for loop
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,n,x;
printf(“Input the nth natural numbers:”);
scanf(“%d”,&n);
for(x=1;x<=n;x++)
{
sum=sum+x;
}
Looping 191

printf(“The summation of nth natural number is:%d”,sum);


}

Output:
Input the nth natural numbers:4
The summation of nth natural number is:10
Q3. C Program to Find Prime Numbers between 1 to 100 using for Loop.
Solution:
/*************************************************************************
FILE NAME: for3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find prime numbers between 1 to 100 using
for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,j,count;
printf(“The prime numbers [1-100]are:\n”);
for(x=1;x<=100;x++)
{
count=0;
for(j=2;j<=x/2;j++)
{
if(x%j==0)
{
count++;
break;
}
}
if(count==0&&x!=1)
printf(“%d\t”,x);
}
}

Output:
The prime numbers [1-100] are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

EXPLANATION:
Logic of prime number:
A number which has two divisors, i.e., 1 and itself is called prime number. Example 3,
their divisor are 1 and 3. We will have two loops. The outer loop is the number from 1
192 Concepts and Techniques of Programming in C

to 100 and outer loop will divide the number taking from 2 to number/2. If the number
is not divisible by any of the number then we will print the prime numbers which are
displayed in the output.
Q4. C Program of Sum of Digits of an Integer Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of sum of digits of an integer number using
for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,sum=0,r;
printf(“Input the integer number:”);
scanf(“%d”,&x);
for(;x!=0;x=x/10)
{
r=x%10;
sum=sum+r;
}
printf(“Summation of digits of an inputted integer number is:%d”,sum);
}

Output:
Enter the number: 123
Summation of digits of an input integer number is: 6
Q5. C Programs of Reverse a Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of reverse a number using for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,rev=0;
printf(“Input the integer number:”);
scanf(“%d”,&x);
Looping 193

for(;x!=0;x=x/10)
{
reminder=x%10;
rev=rev*10+reminder;
}
printf(“Reverse of inputted integer number is:%d”,rev);
}

Output:
Input the integer number: 789
Reverse of input integer number is: 987
Q6. C Program to Count the Number of Digits of an Integer Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to count the number of digits of an integer
number using for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,count=0;
printf(“Input the integer number:”);
scanf(“%d”,&x);
for(;x!=0;x=x/10)
{
count++;
}
printf(“Number of digits of an inputted integer number is:%d”,count);
}

Output:
Input the integer number: 1234
Number of digits of an input integer number is: 4
Q7. C Program to Find the Factorial of an Integer Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find the factorial of a integer number
using for loop
*************************************************************************/
194 Concepts and Techniques of Programming in C

#include<stdio.h>
void main(void)
{
int x,i,fact=1;
printf(“Input the integer number to find the factorial:”);
scanf(“%d”,&x);
for(i=x;i>0;i--)
{
fact=fact*i;
}
printf(“Factorial of integer number %d is :%d\n”,x,fact);
}

Output:
Input the integer number to find the factorial: 5
Factorial of integer number 5 is: 120
Q8. C Program to Generate the Pyramid by Entering the Number of Lines by User.
Or
C Program to Print Floyd’s Triangle
1
11
111
1111
Solution:
/*************************************************************************
FILE NAME: for8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to generate the pyramid by entering the
number of lines by user.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,n;
printf(“Input the number of lines:”);
scanf(“%d”,&n);
printf(“The generated pyramid is:\n”);
for(x=1;x<=n;x++)
{
for(y=1;y<=x;y++)
{
printf(“1”);
}
Looping 195

printf(“\n”);
}
}

Output:
Input the number of lines:4
The generated pyramid is:
1
11
111
1111
Q9. C Program to Print Pyramid of 1.
Or
C Program to Print Patterns of Numbers and 1.
1
111
11111
Solution:
/*************************************************************************
FILE NAME: for9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to print pyramid of 1.
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x,y,n,z;
printf(“Input the number of rows in pyramid of one: “);
scanf(“%d”,&n);
printf(“The generated pyramid is:\n”);
z= n;
for(x=1;x<=n;x++ )
{
for(y =1;y<z;y++ )
printf(“ “);
z--;
for (y= 1;y<=2*x-1;y++ )
printf(“1”);
printf(“\n”);
}
}
196 Concepts and Techniques of Programming in C

Output:
Input the number of rows in pyramid of one:3
The generated pyramid is:
1
111
11111
Q10. C Program to Print Half Pyramid using Numbers.
1
12
123
1234
Solution:
/*************************************************************************
FILE NAME: for10.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to print half pyramid using numbers
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x,y,n;
printf(“Input the number of rows:”);
scanf(“%d”,&n);
printf(“The generated half pyramid is:\n”);
for(x=1;x<=n;++x)
{
for(y=1;y<=x;++y)
{
printf(“%d “,y);
}
printf(“\n”);
}
}

Output:
Input the number of rows: 4
The generated half pyramid is:
1
12
123
1234
Looping 197

Q11. C Program to Find Out the Sum of Series 1^2 + 2^2 + …. + N^2.
Solution:
/*************************************************************************
FILE NAME: for11.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find out the sum of series 1^2 + 2^2
+ .... + n^2
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,m,s=0;
clrscr();
printf(“Input the maximum number of series :”);
scanf(“%d”,&x);
s=(x*(x+1)*(2*x+1))/6;
printf(“Sum of the inputted series “);
for(m=1;m<=x;m++)
{
if (m!= x)
printf(“%d^2+”,m);
else
printf(“%d^2 is:%d”,m,s);
}
getch();
}

Output:
Input the maximum number of series: 4
Sum of the input series 1^2+2^2+3^2+4^2 is:30
Q12. C Program to Find Sum of Series 1 + 2 + 3 +......+ N=N*(N+1)/2.
Solution:
/*************************************************************************
FILE NAME: for12.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find sum of series 1 + 2 + 3 +......+
n=n*(n+1)/2.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
198 Concepts and Techniques of Programming in C

int i,x,s=0;
clrscr();
printf(“1+2+3+......+n”);
printf(“\nInput the value of n:”);
scanf(“%d”,&x);
for(i=1;i<=x;++i)
{
s=s+i;
}
printf(“Sum of values of %d is:%d”,x,s);
getch();
}

Output:
1+2+3……+n
Input the values of n: 4
Sum is: 10
Q13. C Program to Find Even Number between 1 to 100 using for Loop.
Solution:
/*************************************************************************
FILE NAME: for13.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find even number between 1 to 100 using
for loop.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x;
clrscr();
printf(“EVEN NUMBER BETWEEN [1 to 100]”);
printf(“\n”);
for(x=1;x<=100;x++)
{
if(x%2==0)
printf(“%d “,x);
}
getch();
}

Output:
EVEN NUMBER BETWEEN [1 to 100]
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Looping 199

Q14. C Program to Print the Sum of all Odd Numbers from 1 to N.


Solution:
/*************************************************************************
FILE NAME: for14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to print the sum of all odd numbers from
1 to n.
*************************************************************************/
#include <stdio.h>
void main(void)
{
int j,x,s=0;
printf(“Input the integer number: “);
scanf(“%d”,&x);
for(j=1;j<=x;j=j+2)
{
s=s+j;
}
printf(“Sum of odd numbers between[1 to %d]is:%d”,x,s);
}

Output:
Input the integer number: 3
Sum of odd numbers between [1 to 3] is: 4
Q15. C Program to Generate and Print Fibonacci Series.
Solution:
/*************************************************************************
FILE NAME: for15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to generate and print Fibonacci series
*************************************************************************/
#include<stdio.h>
void main(void)
{
int n,j,x=0,y=1,z=0;
printf(“Input the Nth term of Fibonacci series:”);
scanf(“%d”,&n);
printf(“%d %d”,x,y);
for(j=2;j<n;j++)
{
z=x+y;
x=y;
y=z;
200 Concepts and Techniques of Programming in C

printf(“ %d “,z);
}
printf(“\n”);
}

Output:
Input the nth term of Fibonacci series: 5
0 1 1 2 3

Summary

1. Loops are used when a part of the program is executed several times.
2. In while loop the condition is tested before entering the loop. When the condition
becomes false at the starting stage then the loop statements are not executed. It
is called entry-controlled loop.
3. In do while loop the condition is tested at the end of the loop. When the condition
becomes false the statements are executed at least once. It is called exit-controlled
loop.
4. The for loop consists of initialization, test condition and increment/decrement in
a single statement. So it is more preferable than while and do while loops.

Short Questions

1. What is looping in C? And what are the different types of the loop.
2. What is while loop?
3. What is do while loop?
4. What is for loop?
5. What is the difference between while, do while and for loops.

Long Questions

1. Program of conversion of binary number to decimal number.


2. Program to convert decimal to binary using while loop.
3. Program of summation of nth term natural numbers e.g. 1+2+3---n=n(n+1)/2
using whileloop.
4. Program of count the number of digits of an integer number using while loop.
5. Program to reverse a number using while loop.
6. Program to check a number is palindrome using while loop.
7. Program to check number is Armstrong number using while loop.
8. Program to calculate power of an integer number using while loop.
9. Program to display the sum of digits of any integer number using while loop.
Looping 201

10. Program of multiplication of digits of an integer number using while loop.


11. Program to find the power of an integer number using while loop.
12. Program to check the number is a perfect number or not using while loop.
13. Program to find GCD and LCM of two integer numbers using while loop.
14. Program of binary to decimal conversion using do while loop.
15. Program to check the Armstrong number using do while loop.
16. Program to find prime numbers between 1 to 100 using for loop.
17. Program of sum of digits of an integer number using for loop.
18. Program of reverse a number using for loop.
19. Program to count the number of digits of an integer number using for loop.
20. Program to find the factorial of a integer number using for loop.
21. Program to generate the pyramid by entering the number of lines by user.
22. Program to print pyramid of 1.
23. Program to print half pyramid using numbers.
24. Program to find out the sum of series 1^2 + 2^2 + …. + n^2.
25. Program to find sum of series 1 + 2 + 3 +......+ n=n*(n+1)/2.
26. Explain all the loop structures available in C.

OBJECTIVE Questions WITH Answers

1. What will be the output?


#include<stdio.h>
void main(void)
{
char x=1;
while(x<7)
{
printf(“%d “,x);
x =x+1;
}
printf(“\n”);
}
Output:
123456
2 What will be the output?
#include<stdio.h>
void main(void)
{
unsigned int x = 65535;
while(x++ != 0)
202 Concepts and Techniques of Programming in C

printf(“%d”,++x);
printf(“\n”);
}
Output:
Infinite loop
3. What will be the output?
#include<stdio.h>
void main(void)
{
unsigned int x = 65536;
while(x!= 0)
printf(“%d”,++x);
printf(“\n”);
}
Output:
No output
4. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
while(x<2)
{
x++;
}
printf(“INDIA\n”);
}
Output:
INDIA
5. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
while(++x)
{
printf(“INDIA”);
}
}
Output:
Infinite loop
Looping 203

6. What will be the output?


#include<stdio.h>
void main(void)
{
int x,y;
x=y=2, 3;
while(--x&&y++)
printf(“%d %d”,x,y);
}
Output:
13
7. What will be the output?
#include<stdio.h>
void main()
{
int x=5,y=5;
while(x<=7,y<=6)
printf(“%d %d “,++x,++y);
}
Output:
6677
8. What will be the output?
#include <stdio.h>
void main(void)
{
do
printf(“INDIA\n”);
while (0);
printf(“ODISHA”);
}
Output:
INDIA
ODISHA
9. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
do
{
x++;
printf(“I LOVE MY COUNTRY\n”);
}
while (x<4);
}
204 Concepts and Techniques of Programming in C

Output:
I LOVE MY COUNTRY
I LOVE MY COUNTRY
I LOVE MY COUNTRY
I LOVE MY COUNTRY
10. What will be the output?
#include <stdio.h>
void main(void)
{
int x=4;
do
{
printf(“JAI HIND”);
}
while(x<4);
}
Output:
JAI HIND
11. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
while(++x)
{
printf(“INDIA”);
}
}
Output:
INDIA will print infinite times
12. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
do
{
printf(“INDIA”);
}
while (x!=0);
}
Output:
INDIA
Looping 205

13. What will be the output?


#include <stdio.h>
void main(void)
{
double x;
for (x =0.0;x<5.0;x++);
printf(“%lf”,x);
}
Output:
5.00000
14. What will be the output?
#include <stdio.h>
void main(void)
{
int x;
for(x=-1;x<-6;x++)
printf(“INDIA”);
}
Output:
No output
15. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
for (; ; ;)
printf(“INDIA\n”);
printf(“ODISHA\n”);
}
Output:
Compilation error
16. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
for(x++;x==1;x=5)
{
printf(“INDIA\n”);
}
printf(“ODISHA”);
}
206 Concepts and Techniques of Programming in C

Output:
INDIA
ODISHA
17. What will be the output?
#include <stdio.h>
void main(void)
{
for(int x=0;x<2;x++)
printf(“INDIA\n”);
}
Output:
INDIA
INDIA
18. What will be the output?
#include<stdio.h>
void main(void)
{
int y=1,z=1;
for(;z;printf(“%d %d\n”,y,z))
{
z=y++<=6;
}
printf(“\n”);
}
Output:
21
31
41
51
61
71
80
19. What will be the output?
#include<stdio.h>
void main(void)
{
short int y=0;
for(y<=5&&y>=-1; ++y; y>0)
printf(“%u”,y);
}
Output:
Infinite loop
Looping 207

20. What will be the output?


#include<stdio.h>
void main(void)
{
for(int x=0;x<=5;x++);
printf(“%d”,x);
}
Output:
6
21. What will be the output?
#include<stdio.h>
void main(void)
{
for(int x=0;x<=6;x++)
printf(“ %d “,x);
}
Output:
0123456
22. What will be the output?
#include<stdio.h>
void main(void)
{
int x=0;
for(;x++;printf(“%d”,x));
printf(“%d”,x);
}
Output:
1
23. What will be the output?
#include<stdio.h>
void main(void)
{
int x=1;
for(;x<=4;x++)
{
printf(“%d “,x);
}
}
Output:
1234
9
Unconditional Statements

9.1 INTRODUCTION
Unconditional statements are the statements used only when the program flows into
another part of the program without checking the test condition. These statements
interrupt the sequential execution of program. The examples of unconditional statements
are: break, goto, continue, exit (0).

9.1.1 Break Statement


The break statement is used inside the while, do while, for loop or a switch statement.
When a break statement is identified inside the loop then it stops that loop immediately
and the program control continues with the next statement following that loop. A break
statement is usually associated with an if statement.

The syntax of break statement is:


break;

TIPS TO REMEMBER
Solution: The break is used with if statement only when the if statement is written
inside the loop.

EXAMPLES OF BREAK STATEMENT


Q1. C Program to Check the Number is Prime or not by using the Break Statement.
Solution:
/*************************************************************************
FILE NAME: unc1.c
Unconditional Statements 209

AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: c program to check the number is prime or not by
using the break statement.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,j;
printf(“Input the number:”);
scanf(“%d”,&x);
j=2;
while(j<=x-1)
{
if(x%j==0)
{
printf(“Inputted %d is not a prime”,x);
break;
}
j++;
}
if(j==x)
printf(“Inputted %d is a prime number”,x);
}

Output:
Input the number: 3
Input 3 is a prime number

EXPLANATION:
In the above program when break statement finds then it stops that loop or if statements.
If we remove the break statement then the above program will display both the
statements.
Example:
Input the number: 4
Input 4 is not a prime number
Input 4 is a prime number

9.1.2 goto Statement


The goto statement is used to branch unconditionally from one part of the program
into another part of the program. It may not be essential to use goto statement in high
level programming languages like C ,C++, Java .But in programming languages it
sometimes is useful.
210 Concepts and Techniques of Programming in C

The goto statements needs a label in order to search the location where the branching
is to be made. A label is a variable and it must be followed by a colon. The label can
be placed in any position in the program. Basically, it may be placed before the goto
label statement or after the goto label statements. When the label is placed before the
goto label statement then a loop will be generated and the set of statements will be
executed repeatedly. Such jump is called a backward jump. If the label is placed after
the goto label statement then some statements will be skipped and the jump is known
as forward jump.

Forward jump Backward jump


goto label; label:
block of statements; statement-1;
label: block of statements;
statement-1; goto label;

In case of forward jump, the cursor directly comes to statement-1 after goto label
statement and skips the block of statements. In case of backward jump, statement-1
and block of statements will be executed repeatedly.

TIPS TO REMEMBER
Do not use goto statement in programming. It can be used if any program is difficult
to debug.

Q.2 C Program to Display the Numbers from 1 to 15 using goto Statement.


Solution:
/*************************************************************************
FILE NAME: unc2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: c program to display the numbers from 1 to 15 using
goto statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=0;
y:
x++;
printf(“%d\t”,x);
if(x<=15)
goto y;
}
Unconditional Statements 211

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

EXPLANATION:
This program is a backward jump goto statement.

9.1.3 Continue Statement


While executing the loop, sometimes it is required to skip some of these statements
inside the body of the loop under some specific conditions. In that case continue
statement is very useful. Continue statement gives the information to the compiler
about the loop to be continued with next iteration after skipping the set of statements
in between the body part of the loop. Therefore, those statements which come after the
continue keyword will not be executed and those coming before the continue will be
executed. If continue statement is used in while and do while loop, then control moves
to the conditional part of the loop and then to continue that loop. If continue statement
is used in for loop, then control moves to the incremental part of the loop for execution
before the test condition.

The syntax of continue is:


continue;

The syntax of continue statement inside the loop is


1)
while(condition1)
{
if(condition2)
continue;
}
2)
do
{
if(condition1)
continue;
}
while(condition2);
3)
for(initialization; condition; increment/decrement)
{
if(condition1)
continue;
}
212 Concepts and Techniques of Programming in C

Q3. C Program to Find the Odd Number from 1 to 15 using Continue Statements.
Solution:
/*************************************************************************
File Name: Unc3.C
Author Details: Mr. X, 1St Sem, Comp.Sc& Engg., Abc College of Engg.
Date Of Program Execution: 5/8/2015
Name Of The Program: C Program To Find The Odd Number From 1 To 15 Using
continue statements
*************************************************************************/
#include<stdio.h>
void main(void)
{int x;
for(x=1;x<=15;x++)
{
if(x%2==0)
{
continue;
printf(“GCE,KEONJHAR”);
}
else
{
printf(“%d\t”,x);
}
}
}

Output:
1 3 5 7 9 11 13 15

EXPLANATION:
In the above program when 2%2==0 and condition is satisfied and the if condition
execution starts. Since there is no statement before the continue statement in that case
control goes to incremental part and test for next iteration. Here, the printf statement
will not print the message “GCE, KEONJHAR” because that statement is written below
the continue statement.
Q4. C Program of Continue Statement.
Solution:
/*************************************************************************
FILE NAME: unc4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: c program of continue statements
*************************************************************************/
Unconditional Statements 213

#include<stdio.h>
void main(void)
{int x;
for(x=1;x<=15;x++)
{
if(x%2==0)
{
printf(“GCE,KEONJHAR\t”);
continue;
}
else
{
printf(“%d\t”,x);
}
}
}

Output:
1 GCE,KEONJHAR 3 GCEKEONJHAR 5 GCEKEONJHAR 7 GCEKEONJHAR
9 GCEKEONJHAR 11 GCEKEONJHAR 13 GCEKEONJHAR 15

Explanation:
From the above program when 2%2==0 condition is satisfied then execution starts.
Since before the continue statement printf statement is used. So when the reminder of
condition matched with 0 then GCE,KEONJHAR will print then continue statement
continue the loop and control moves to incremental part for next iteration.

9.1.4 exit() Statement


To jump out of loop programmer use the statements break or goto statement. In a
similar way the programmer can jump out from a program by using the library function
exit();. The exit() function takes the integer value as its parameter. Generally, zero is
used for termination/quit the program. We can write the function as:

The general form of exit() function is:


exit(int);

Examples:
exit(0);
Q5. Examples of Exit Function.
Solution:
/*************************************************************************
FILE NAME: unc5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
214 Concepts and Techniques of Programming in C

DATE OF PROGRAM EXECUTION: 5/8/2015 NAME OF THE PROGRAM: .Examples of exit


function
*****************************************************************/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
printf(“I LOVE MY INDIA\n”);
printf(“I AM PROUD TO BE AN INDIAN\n”);
exit(0);
printf(“THANKS\n”);
return(0);
}

Output:
I LOVE MY INDIA
I AM PROUD TO BE AN INDIAN

EXPLANATION:
In the above examples exit(0) function stops the program execution when it is placed.
So the other message “thanks” is not printed.
Q6. Examples of Exit Function using Function.
Solution:
/*************************************************************************
FILE NAME: unc6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: examples of exit function using function.
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
void x()
{
printf(“I am user-defined function”);
exit(0);
}
void main(void)
{
x();
printf(“I am main function”);
}

Output:
I am user-defined function
Unconditional Statements 215

SUMMARY

1. The continue statement is used to continue the loop. Those statements which
come after the continue will not execute and those statements which come before
continue will execute.
2. The goto is an unconditional statement which transfers the flow of control to
another part of the program.
3. The break statement is used to terminate the switch statement or loop and
transfers the control to the next statements immediately following that loop or
switch statements.
4. The exit(0) function is used to quit the program.

SHORT QUESTIONS

1. What is role of unconditional statements?


2. What is break statement? Write its syntax.
3. What is continue statement? Give its syntax.
4. What is goto statement?
5. What is exit function?

LONG QUESTIONS

1. What is the difference between conditional statements and unconditional


statements? Give suitable examples.
2. Write short notes on
(a) continue statement,
(b) goto label statement
(c) break statement

OBJECTIVE Questions with Answers

1. What will be the output?


#include <stdio.h>
void main(void)
{
int x=5;
if(x==5)
{
printf(“INDIA”);
continue;
}
}
216 Concepts and Techniques of Programming in C

Output:
Compile time error
EXPLANATION:
Continue statement is applied in only loops. Therefore, compilation error
happened.
2. What will be the output?
#include <stdio.h>
void main(void)
{
int x=1;
do
{
x++;
if(x==4)
{
printf(“INDIA”);
continue;
}
}while (x<4);
}
Output:
India
3. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0,y=0;
for(;x<2;x++)
{
for(;y<3;y++)
{
printf(“*\n”);
break;
}
printf(“**\n”);
}
printf(“INDIA\n”);
}
Output:
*
**
*
**
INDIA
Unconditional Statements 217

4. What will be the output?


#include <stdio.h>
void main(void)
{
int x=1;
while(x<3)
{
if(x==1)
break;
x++;
if(x==1)
continue;
printf(“INDIA\n”);
}
printf(“ODISHA\n”);
}
Output:
ODISHA
5. What will be the output?
#include <stdio.h>
void main(void)
{
int i=1;
char a=’x’;
while(i<4)
{
i++;
switch(a)
{
case ‘x’:
printf(“%c “,a);
break;
}
}
printf(“INDIA\n”);
}
Output:
x x x India
6. What will be the output?
#include <stdio.h>
void main()
{
printf(“INDIA”);
continue;
printf(“ODISHA\n”);
}
218 Concepts and Techniques of Programming in C

Output:
Compile time error
7. What will be the output?
#include <stdio.h>
void main(void)
{
printf(“%d “,1);
goto x1;
printf(“%d “,2);
x1:goto x2;
printf(“%d “,3);
x2:printf(“%d “,4);
}
Output:
14
8. What will be the output?
#include<stdio.h>
void main()
{
printf(“%d “,1);
x1:x2:
printf(“%d “,2);
printf(“%d”,3);
}
Output:
123
9. What will be the output?
#include <stdio.h>
void main()
{
printf(“%d “,1);
goto x1;
printf(“%d “,2);
}
void fun()
{
x1 :printf(“3 “, 3);
}
Output:
Compile time error
10. What will be the output?
#include <stdio.h>
int main()
{
Unconditional Statements 219

int x=0,y=0;
while (x < 2)
{
m1 :x++;
while (y<3)
{
printf(“INDIA\n”);
goto m1;
}
}
}
Output:
Infinite loop
11. What will be the output?
#include <stdio.h>
void main()
{
int x=0,y=0;
while(m1:x<2)
{
x++;
while(y<3)
{
printf(“INDIA\n”);
goto m1;
}
}
}
Output:
Compilation error
12. What will be the output?
#include <stdio.h>
void main()
{
int x=1,y=1;
m1:while(x<3)
{
x++;
while(y<4)
{
printf(“INDIA\n”);
goto m1;
}
}
}
Output:
India
India
10
Function

10.1 INTRODUCTION
When a person faces a complex problem then to solve that problem is not an easy task
immediately. It takes some time to solve it. Then one of the easiest methods to solve
that problem is the divide and conquer principle. This principle divides the logic of
the problem into smaller problems and later solves the logic of the smaller problems
individually and then adds all these solutions of smaller problems to get the final
solution. Like that in programming concept, a complex program is divided into different
sub-programs and then each sub-programs is executed separate and sends the result to
the calling function. Such separate parts of sub-programs is called subroutine or function
or user-defined function or module. Thus, a function contains block of statements that
does a particular work/task. A function is also called black box because all the inner
operations inside the user-defined function are invisible to the rest of the program
and return the value to the calling function placed inside the main function. From the
above statements we can differentiate between monolithic programming with modular
programming.

10.1.1 Monolithic Program Vs. Modular Program


In monolithic programming instead of dividing a larger program into smaller programs,
a single function contains a larger program. It is difficult to maintain the programming
code when program code increases.
The disadvantages are:
1. It is difficult to detect the syntax error because program size is bigger.
2. It is difficult to maintain.
3. The programming code cannot be reused further.
In modular programming the larger program or software is divided into sub-parts called
modules. The programmer can change, modify or remove some of the programming
Function 221

codes without affecting the whole programming code. One module can communicate
with other module of a program in a well defined manner.
Advantages are:
1. It is easy to write a programming code and run.
2. The programming code can further be reused.
3. It reduces programming code.
4. Detecting error in each module is easy then searching error in whole program.
Let us write a C program to display the different laboratories in your college. Then
someone will take time to think. If he writes different laboratories of each dept separately
called module wise, then it will solve within a few seconds.
Suppose college name is: gcekjr and different depts. are: CSE, Electrical, Mechanical,
Civil, Mineral, Mett and Mining. The CSE dept has C programming lab, C++ lab, DBMS
lab, data structure lab, etc., Electrical dept has basic electrical lab, etc., Mechanical
dept has workshop lab, etc., Mineral has mineral processing lab, etc., Mett has metal
processing lab, Civil dept has survey lab then we can write the C program using above
data is
Test Program 1
/*Monolithic Program Execution of Displaying different Laboratories in each Dept
of a College*/
#include<stdio.h>
void main()
{
printf(“This is the example of displaying different labs in each dept of
a college without using function\n”);
printf(“CSE DEPT LABS\n”);
printf(“Data Structure lab\n”);
printf(“C++ programming lab\n”);
printf(“DBMS lab\n\n”);
printf(“MECHINACAL ENGG DEPT LABS\n”);
printf(“workshop lab\n\n”);
printf(“ELECTRICAL ENGG LABS\n”);
printf(“basic electrical lab\n\n”);
printf(“CIVIL ENGG LABS\n”);
printf(“survey lab\n\n”);
printf(“MINERAL ENGG LABS\n”);
printf(“mineral processing lab\n\n”);
printf(“coal preparation lab”);
printf(“particle technology”);
printf(“METT ENGG LABS\n”);
printf(“Metal processing lab\n”);
222 Concepts and Techniques of Programming in C

printf(“MINING ENGG LABS\n”);


printf(“mining survey lab\n\n”);
printf(“mine hazard lab”);
printf(“rock mechanics lab”);
printf(“mineral beneficiation lab”);
printf(“This is the end of the program”);
}

Test Program 2:
/*Example of C Program Execution of Displaying Different Laboratories in each Dept
of a College using User Defined Function (Module)*/
#include<stdio.h>
void cse(); /*CSE function declaration*/
void mechanical(); /*mechanical function declaration*/
void electrical(); /*electrical function declaration*/
void civil(); /*civil function declaration*/
void mineral(); /*mineral function declaration*/
void mett(); /*mett function declaration*/
void mining();   /*mining function declaration*/
void main() /*Entry point*/
{
printf(“This is the example of displaying different labs in each dept of
a college using function\n”);
cse(); /*calling function*/
mechanical(); /*calling function*/
electrical(); /*calling function*/
civil(); /*calling function*/
mineral(); /*calling function*/
mett(); /*calling function*/
mining(); /*calling function*/
printf(“This is the end of the function”);
}
void cse() /* CSE function definition*/
{
printf(“CSE DEPT LABS\n”);
printf(“c programming lab\n\n”);
printf(“Data Structure lab\n”);
printf(“C++ programming lab\n”);
printf(“DBMS lab\n\n”);
}
void mechanical() /* mechanical function definition*/
{
printf(“MECHINACAL ENGG DEPT LABS\n”);
printf(“workshop lab\n\n”);
}
void electrical() /* electrical function definition*/
{
Function 223

printf(“ELECTRICAL ENGG LABS\n”);


printf(“basic electrical lab\n\n”);
}
void civil() /* civil function definition*/
{
printf(“CIVIL ENGG LABS\n”);
printf(“survey lab\n\n”);
}
void mineral() /*mineral function definition*/
{
printf(“MINERAL ENGG LABS\n”);
printf(“mineral processing lab\n\n”);
printf(“coal preparation lab”);
printf(“particle technology”);
}
void mett() /*mett function definition*/
{
printf(“METT ENGG LABS\n”);
printf(“Metal processing lab”);
}
void mining() /*mining function definition*/
{
printf(“MINING ENGG LABS\n”);
printf(“mining survey lab\n\n”);
printf(“mine hazard lab”);
printf(“rock mechanics lab”);
printf(“mineral beneficiation lab”);
}

Output:
Different labs in each dept of a college using function
CSE DEPT LABS
C programming lab
Data structure lab
C++ programming lab
DBMS lab
MECHANICAL ENGG DEPT LABS
Workshop
ELECTRICAL ENGG LABS
Basic electrical lab
MINERAL ENGG LABS
Mineral processing lab
METT ENGG LABS
Metal processing lab
MINING ENGG LABS
224 Concepts and Techniques of Programming in C

Mining survey lab


This is the end of the program.

EXPLANATION:
In the above two program displays the different labs of different depts in a college. Then
if anyone asks why the second program is preferable? The answer is that we put the
different labs individually inside each dept function. And each dept function calculates
individually and sends the value to the main function. By using the user defined
function if any error is found while writing the program then it is easy to detect it
because instead of focusing each line of program the programmer focuses function-wise.
Diagrammatic representation of the above user defined function is:

main()

mining()

cse() mett()

electrical() mineral()

mechanical()
civil()

/*Another Example of User Defined Function (Modular Programming)*/


#include<stdio.h>
void x(); /*function prototype*/
void y(); /*function prototype*/
void z(); /*function prototype*/
void main()
{
x(); /*Calling function*/
printf(“\nThis is the end of the function”);
}
void x() /*function definition*/
{
printf(“I AM DHABAL PRASAD SETHI,\n”);
y(); /*calling function*/

}
void y() /*function definition*/
{
Function 225

printf(“I COMPLETED MY BTECH CSE FROM BIET,BHADRAK IN 2006\n”);


z(); /*calling function*/
}
void z() /*function definition*/
{
printf(“I COMPLETED MY MTECH CSE FROM UTKAL UNIVERSITY IN 2011”);
}

Output:
I AM DHABAL PRASAD SETHI
I COMPLETED MY BTECH CSE FROM BIET, BHADRAK IN 2006
I COMPLETED MY MTECH CSE FROM UTKAL UNIVERSITY IN 2011

10.2 FUNCTION TYPES


A function is generally categorised into two types: library function and the user-defined
function. In user-defined function any function can call any other function. It also call
itself. A function can be called more than once.

10.2.1 Library Functions


Library functions are inbuilt by the compiler. The programmer can use these functions
and they do not have permission to modify it. The examples of library functions are
printf(), scanf(), sqrt(), cos(), stcat(), pow() etc. If the beginner wrongly types the library
function then it gives error.
/* C Program Execution of Find Square Root of a Number using Library Function*/
#include <stdio.h>
#include <math.h>
void main(void)
{
double x,y;
printf(“ C program execution to find square root of a number using library
function\n”);
printf(“Input the number to find square root:”);
scanf(“%lf”,&x);
y=sqrt(x);
printf(“Square root of inputted %.2lf is:%.2lf”,x,y);
printf(“\nThis is the end of the program”);
}

Output:
Input the number to find square root: 16.00
226 Concepts and Techniques of Programming in C

Square root of inputted 16.00 is: 4.00.


This is the end of the program.

EXPLANATION:
Here sqrt() function is a library function used to measure the square root of the input
number.
/*C Program to Find Power of an Integer Number using Library Function*/
#include<stdio.h>
#include<math.h>
void main(void)
{
int x,y,z;
printf(“ C program execution to find power of an integer number using library
function\n”);
printf(“Input the base and exponent:”);
scanf(“%d%d”,&x,&y);
z=pow(x,y);
printf(“The power of integer(base) is:%d”,z);
printf(“\nThis is the end of the program”);
}

Output:
Input the base and exponent: 2 3
The power of integer (base) is: 8
This is the end of the program.

EXPLANATION:
Here pow() function is a library function which measures the power of an integer
number.

TIPS TO REMEMBER
C program has at least one function, which is main () function. There are three basic
functions required to write a simple c program: 1) main(),2) printf();,3) scanf();

10.2.2 User-Defined Functions


These are functions created by the programmer by giving them a name of
his/her own choice at that time of writing the program. Later that user-defined function
becomes library function, i.e., they become inbuilt functions. In order to write any
user defined function, the programmer should be familiar with three important terms
about user defined function, i.e., function declaration (function prototype), function
call (calling function) and function definition (user defined function). Therefore, these
Function 227

three are important to write when the programmer wants to write a modular program
(user-defined function).

TIPS TO REMEMBER
The main() function is called user-defined function because the prototype declaration
of main() function is predefined by compilers in C library and it is defined as the
entry point of the C program.

10.2.2.1 Function Prototyping (Declaration)


Generally, to initialize (to assign a value) a variable, it should be declared first. Like
that, to define the user defined function, it should be declared first in a proper place.
It is called function declaration or function prototyping and it sends the data about
function called information to the compiler, i.e., first return type, it means int or void,
second function name and third the number of values to be passed as an argument to
the user-defined function.

The syntax of function declaration (prototype declaration):


return_type function_name( data_type argument1,data_type argument2…….
data_type argument N);

EXPLANATION:
From the above syntax choose return_type as void or int then write the function name of
your choice then give parentheses and inside parentheses place the number of arguments
you want to use. Each argument consists of again first data type then argument name.
Always remember that the function declaration should end with semicolon and should
be placed above the void main function.
Let’s see an example:
int mul(int x,int y); /* valid function declaration*/

TIPS TO REMEMBER
In function declaration the names of the argument are optional, i.e., you may give
or may not.

Let’s see again the above declaration


int mul(int,int);/*valid function declaration*/
Here, in the above declaration variables are not mentioned inside parentheses but it is
also a valid declaration.
228 Concepts and Techniques of Programming in C

10.2.2.2 Function Call


In order to use the user defined function the programmer should place function inside
the main function, called function call.

The syntax of function call is:


function_name(argument1,arguemnt2-------argument-N);

EXPLANATION:
Here the above declaration consists of function_name and argument list. Do not write
the data type inside the parentheses of calling function. Write only arguments inside
calling function of the program. The function call should be placed inside the main
function. Therefore, the arguments used in calling function consist of only variables and
not the combination of data-type and variables. Let’s see the example:
void main (void)
{
int x,y,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer numbers is:%d”,m);
}

10.2.2.3 Function Definition /Called Function/User Defined Function


The function definition is the user defined function where the programmer writes the
programming code when he wants to display the output. Function definition also known
as function implementation or called function, i.e., the programmer has to implement/
convert the logic of program into a separate function created by him and the function
may be placed after or before the main function. It consists of a set of elements, e.g.,
return type, function name, argument list which consists of different arguments, local
variables, function statements and a return statement which returns the value to the
calling function. Again the above set of elements is broadly categorized into two parts,
i.e., function header and function body. The function header consists of return type,
function name and list of arguments (each argument consists of respective data-type).
The function body consists of local variables, function statements and return statement.

The syntax of function definition is:


return_type function_name(data_type argument1,data_type argument2…………….
data_type argumentN)
{
local variable declaration section;
functional statements section;
return statement section;
}
Function 229

Example:
/*User-defined Function mul()*/
int mul (int x,int y) ___________________Function Header
{ ___________________________function body starts
int z; ___________________local variable
z=x*y; __________________ functional statement
return z; _______________________ return statement
} _________________________________function body close

10.3 THE return STATEMENT


The user defined function may or may not return a value to the calling function. If the
user defined function returns the values to the calling function then return statement is
used at the end of the user defined function. If it does not return, it may not be used.
The syntax of return statement can be represented in different ways, e.g.,
1. return;
At the end of the user defined function, if return; is written then we will know
that the function does not return any value to the calling function. The function
return; is used as a closing braces of the function.
2. return(expression);
3. return expression;
If anyone uses the above syntax2 or syntax3 then we will ensure that the function
returns the value to the calling function.
Example of return statements
int mul(int x,int y)
{
int z;
z=x*y;
return(z); /*return statement*/
}

10.4 GENERAL STRUCTURE OF WRITING THE PROGRAM USING FUNCTION

Preprocessor directive part


Function prototyping/declaration part
main function()
{
calling function part
}
User-defined function part
{
Local variable declaration part;
Function statements part;
return statement part;
}
Fig. 10.1 General structure of a function
230 Concepts and Techniques of Programming in C

Let’s see a simple example of using function


/*simple program of multiplication two integer numbers using function*/
#include<stdio.h>
int mul(int x,int y); /*function prototype*/
void main (void)
{
int x,y,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer numbers is:%d”,m);
printf(“\nThis is the end of the program”);
}
/*user-defined function mul */
int mul(int x,int y)
{
int z;
z=x*y;
return z;
}

Output:
Input the two integer numbers: 2 3
The multiplication of input two integer numbers is: 6
This the end of the program
Let’s see the above program diagrammatically

void main (void)


{
int x,y,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer
numbers is:%d”,m);
}

/*user-defined function mul */


int mul (int x,int y)
{
int z;
z=x*y;
return z;
}

Fig. 10.2 Diagrammatic representation of a function


Function 231

EXPLANATION:
In the above diagram the integer values suppose 2,3 is passed through the calling
function mul(2,3); to the called function/user-defined function int mul(2,3)and after
operation done at called function the return function return the value 6 through variable
z to the calling function and that calling function stores that value in variable m. Then
printf function prints the value 6.

It is possible to write a C program without declaring the function prototype/


declaration. Let’s see the above example again.

/*Simple Program of Multiplication Two Integer Numbers without using Function


Prototyping*/
#include<stdio.h>
/*user-defined function mul */
int mul(int x,int y)
{
int z;
z=x*y;
return(z);
}
void main (void)
{
int x,y,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer numbers is:%d”,m);
printf(“\nThis is the end of the program”);
}

Output:
Input the two integer numbers: 10 10
The multiplication of input two integer numbers is: 1000
This is the end of the program

We can declare the function prototyping inside the main function.

/*Examples of Placing Function Prototyping Inside the Main Function*/


#include<stdio.h>
void main (void)
{
232 Concepts and Techniques of Programming in C

int x,y,m;
int mul(int x,int y); /*function prototype*/
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer numbers is:%d”,m);
printf(“\nThis is the end of the program”);
}
/*user-defined function mul */
int mul(int x,int y)
{
int z;
z=x*y;
return z;
}

Output:
Input the two integer numbers: 10 10
The multiplication of these two integer numbers is: 1000
This is the end of the program.

10.5 TYPES of USER DEFINED FUNCTIONS


Whenever a programmer wants to write any user defined function then he has to adopt
any one form among the list described below.

10.5.1 Function with no Arguments and no Return Values


Function with no arguments and no return values means user defined function/function
definition has no arguments inside the parenthesis and it does not accept any value from
any calling functions. Since calling function does not send any values to the function
definition/called function therefore the called function does not return any value to
calling function. Therefore, there is no data transfer happened between the calling
function vs. called function. Let’s see the programming example.
/*Example of Function with no Arguments with no Return Values*/
#include<stdio.h>
void z(); /*function declaration*/
void main(void)
{
printf(“This the example of function with no arguments and no return a
value to calling function\n”);
z(); /*function call*/
}
void z() /*function definition*/
{
Function 233

int x,y;
printf(“Input the two integer numbers:”);
scanf(“%d %d”,&x,&y);
x=x+50;
y=y+100;
printf(“After updating the inputted two integer number are:%d %d\n”,x,y);
printf(“This is the end of the program”);
}

Output:
This is the example of function with no argument and no return a value to the calling
function
Input the two integer numbers: 10 20
After updating the inputted two integer numbers are: 60 120
This is the end of the program

10.5.2 Function with Arguments and no Return Values


Function with arguments and no return values means the user defined function/
function definition received data/values from calling function through arguments but
does not return the value to the calling function. Since it does not return any value to
calling function therefore programmer uses the printf function to displays the result in
that function definition.
/*Example of Function with Arguments and no Return Values*/
#include<stdio.h>
void z(int x,int y); /*function declaration*/
void main(void)
{
int x,y;
printf(“This the example of function with arguments and no return a value
to calling function\n”);
printf(“Input the two integer numbers:”);
scanf(“%d %d”,&x,&y);
z(x,y); /*function call*/
}
void z(int x,int y) /*function definition*/
{
x=x+50;
y=y+100;
printf(“After updating the inputted two integer numbers are:%d %d\n”,x,y);
printf(“This is the end of the program”);
}

Output:
This is the example of function with arguments and no return a value to calling function
Input the two integer numbers: 5 10
234 Concepts and Techniques of Programming in C

After updating the input two integer numbers are: 55 110


This is the end of the program.

10.5.3 Function with Arguments and One Return Values


Function with arguments and one return values means a user-defined function/function
definition received data/value from calling function through arguments but as a result
the computed one value is returned back to the calling function.
/*Example of Function with Arguments and One Return Values*/
#include<stdio.h>
int diff(int b,int c); /*function declaration*/
void main(void)
{
int x,y,z;
printf(“This is the example of function with arguments and returns a
single value to calling function\n”);
printf(“Input the two numbers:”);
scanf(“%d%d”,&x,&y);
z=diff(x,y); /*function call*/
printf(“The subtraction of inputted two numbers is:%d”,z);
printf(“\nThis is the end of the program”);
}
int diff(int b,int c) /*function definition*/
{
int d;
d=b-c;
return(d);
}

Output:
This is an example of function with arguments and returns a single value to the calling
function.
Input the two numbers: 10 4
The subtraction of input two numbers is : 6
This is the end of the program.

10.5.4 Function with no Arguments and Return Values


Function with no arguments and return values means the user-defined function/
function definition may not accept the value as an argument from calling function but
return values to the calling function.
/*Example of Function with no Arguments and Return Values*/
#include<stdio.h>
int x(); /*function declaration*/
Function 235

int main(void)
{
int x1;
printf(“This the example of function with no arguments and return a value
to calling function\n”);
x1=x(); /*function call*/
printf(“Sum of two numbers is :%d\n”,x1);
printf(“This is the end of the program”);
return 0;
}
int x() /*function definition*/
{
int y,z,m;
printf(“Input two integer numbers:”);
scanf(“%d%d”,&y,&z);
m=y+z;
return(m);
}

Output:
This is an example of function with no argument and returns a value to the calling
function
Input two integer numbers:2 3
Sum of two numbers is: 5
This is the end of the program.

TIPS TO REMEMBER
When the programmer writes a program using user defined function, he should
ensure the number of parameters in the calling function/actual parameter should
match with formal parameters/called function. If the actual arguments are more
than formal parameter then extra arguments in actual arguments are removed.
If the actual arguments are less than formal arguments, then unmatched formal
arguments are initialized to garbage value. Any mismatch in data type may also
result in passing of garbage values.

10.6 Some Useful Programming Examples Using


Functions (User-Defiend Function)
The comment lines for each program are optional. The comment line presented in this
book clearly describes the program name, author information, program execution date,
program name. This gives the basic information about the program to the beginner/
programmer about the program name along with other information. We should write
file name, author details, date of program execution, program name inside it e.g. /* */.
236 Concepts and Techniques of Programming in C

Q1. C Program to Swap Two Numbers using the Third Variable by Function.
Solution:
/*************************************************************************
FILE NAME: swap.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to swap two numbers using the third variable
by function
*************************************************************************/
#include<stdio.h>
void swap_intnum(int x,int y); /*function prototype*/
void main(void)
{
int x,y,z;
printf(“This is the c program to swap two integer numbers using third
variable by function\n”);
printf(“Input the two numbers :”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping the inputted two numbers is:%d %d\n”,x,y);
swap_intnum(x,y); /*function call*/
printf(“\nThis is the end of the program”);
}
void swap_intnum(int x,int y) /*function definition*/
{
int z;
z=x;
x=y;
y=z;
printf(“After swapping the inputted two numbers is:%d %d”,x,y);
}

Output:
This is a C program to swap two integer numbers using third variable by function
Input the two numbers which is swapped: 2 3
Before swapping the input two numbers is: 2 3
After swapping the input two numbers is: 3 2
This is the end of the program

EXPLANATION:
In the above program the two integer numbers (2, 3) are input through the scanf
function. Then the two numbers are passed through the function swap_intnum
(2, 3).Then two numbers are passed to the called functions. In the called function declared
the third variable as z. First the x value( 2 )is assigned to the third variable z, i.e., memory
of x variable becomes blank then value of y (3) is assigned to x, i.e., x becomes 3 and
then y memory becomes blank. Then z values (2) is assigned to y variable e.g. y becomes
2. Finally x becomes 3 and y becomes 2.
Function 237

Q2. C Program to Swap Two Numbers without Third Variable by Function.


Solution:
/*************************************************************************
FILE NAME: swap1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to swap two numbers without third variable
by function
*************************************************************************/
#include<stdio.h>
void swap_intnum(int x,int y); /*function prototyping*/
void main(void)
{
int x,y;
printf(“This is the c program to swap two integer numbers without third
variable by function\n”);
printf(“Input the two integer numbers :”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping the inputted of two integer numbers is:%d %d\n”,x,y);
swap_intnum(x,y); /*function call*/
printf(“\nThis is the end of the program”);
}
void swap_intnum(int x,int y) /*function definition*/
{
x=x+y;
y=x-y;
x=x-y;
printf(“After swapping the inputted of two integer numbers is:%d %d”,x,y);
}

Output:
This is a C program to swap two integer numbers without third variable by function
Input the two integer numbers which are to swapped: 2 3
Before swapping the input two integer numbers is: 2 3
After swapping the input two integer numbers is: 3 2
This is the end of the program.

EXPLANATION:
In the above program two values 2 and 3 are input through scanf function and it passes
through the function swap, i.e., swap (2, 3).In the called function we did not use the
third variable. So the logic is x=2+3=5 and the value of y=5-3=2 and then x=5-2=3.so we
get after swapping without third variable x=3 and y=2.
238 Concepts and Techniques of Programming in C

Q3. C Program to Count the Number of Digits of a Number using Function.


Solution:
/*************************************************************************
FILE NAME: count.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to count the number of digits of a number
using function
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void countdigit(); /*function prototyping*/
void main(void)
{
clrscr();
printf(“This is the c program to count the number of digits of a integer
number using function\n”);
countdigit(); /*function call*/
printf(“\nThis is the end of the program”);
getch();
}
void countdigit() /*function definition*/
{
int x,count=0;
printf(“Input an integer number:”);
scanf(“%d”,&x);
while(x>0)
{
x=x/10;
count++;
}
printf(“Number of digits of inputted integer number is:%d”,count);
}

Output:
This is a C program to count the number of digits of an integer number using function
Input the integer number: 123
Number of digits of input integer number is: 3
This is the end of the program.

EXPLANATION:
In the above program of user defined function countdigit(), declare the variable x
and count with initialize it to zero (e.g. count=0). Enter the number 123 through
scanf function. Then apply the logic as while (123>0) then x=123/10=12 and counter
variable increments one, i.e., counter=1. Then in the second iteration while (12>0) then
x=12/10=1 and counter variable increments on e.g. counter =2. In the third iteration
Function 239

while (1>0) then x=1/10=0 and counter=3 then next iteration the while loop condition
does not satisfied and the loop terminates.
Q4. C Program of Sum of Digits of a Number using Function.
Solution:
/*************************************************************************
FILE NAME: sumdigit.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program of sum of digits of a number using function
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void sumdigit(); /*function prototyping*/
void main(void)
{
clrscr();
printf(“This is the c program of sum of digits of a number using function\n”);
sumdigit(); /*function call*/
printf(“\nThis is the end of the program”);
getch();
}
void sumdigit() /*function definition*/
{
int x,sum=0,reminder;
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x>0)
{
reminder=x%10;
sum=sum+reminder;
x=x/10;
}
printf(“Sum of digits of inputted integer number is:%d”,sum);
}

Output:
This is a C program of sum of digits of a number using function
Input the number: 123
Sum of digits of input integer number is: 6
This is the end of the program.

EXPLANATION:
In the above user-defined function is sumdigit() and inside body is supposed to read
the number 123.
240 Concepts and Techniques of Programming in C

1st Iteration
while(123>0)
Then it goes to the body part of the while loop. Reminder=123%10=3, then
sum=0+3=3, then x=123/10=12
2nd Iteration
while (12>0)
{
reminder=12%10=2
sum=3+2=5;
x=12/10=1
}
3rd Iteration
while(1>0)
{
reminder=1%10=1
sum=5+1=6;
x=1/10=0
}
4th Iteration
Loop terminates
Q5. C Program of Multiplication of Digits of a Number using Function.
Solution:
/*************************************************************************
FILE NAME: multdigit.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program of multiplication of digits of a number
using function
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void muldigit(); /*function prototyping*/
void main(void)
{
clrscr();
printf(“This is the c program of multiplication of digits of an integer
number using function\n”);
muldigit(); /*function call*/
printf(“\nThis is the end of the program”);
getch();
}
void muldigit() /*function definition*/
{
Function 241

int x,mul=1,reminder;
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x>0)
{
reminder=x%10;
mul=mul*reminder;
x=x/10;
}
printf(“Multiplication of digits of inputted integer number is:%d”, mul);
}

Output
This is a C program of multiplication of digits of an integer number using function
Input the integer number: 234
Multiplication of digits of input integer number is: 24
This is the end of the program.

EXPLANATION:
Follow the above program.
Q6. C Program to Check either Prime Number or Armstrong Number Depending on
the Data Entered by User.
Solution:
/*************************************************************************
FILE NAME: check.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check either prime number or Armstrong
number depending upon the data entered by user
*************************************************************************/
#include <stdio.h>
#include<conio.h>
int prime(int n); /*function declaration*/
int armstrong(int x); /*function declaration*/
void main(void)
{
char m;
clrscr();
int n,x=0;
printf(“This is the c program to check the number is either prime or
Armstrong \n”);
printf(“Input an integer number: “);
scanf(“%d”,&n);
printf(“[Input X(or x) to check prime]or[ Y(or y) to check Armstrong
number]:”);
242 Concepts and Techniques of Programming in C

m=getche();
if(m==’x’||m==’X’)
{
x=prime(n); /*calling function*/
if(x==1)
printf(“\n The inputted %d is a prime number.”, n);
else
printf(“\nThe inputted %d is not a prime number.”, n);
}
if(m==’Y’||m==’y’)
{
x=armstrong(n); /*calling function*/
if(x==1)
printf(“\nThe inputted %d is an Armstrong number”, n);
else
printf(“\nThe inputted %d is not an Armstrong number”, n);
printf(“\nThis is the end of the program”);
getch();
}
}
int prime(int n) /*prime user-defined function*/
{
int j,c=1;
for(j=2;j<=n/2;++j)
{
if(n%j==0)
{
c=0;
break;
}
}
return(c);
}
int armstrong(int x) /*Armstrong user-defined function*/
{
int s=0,t,r,c=0;
t=x;
while(x!=0)
{
r=x%10;
s=s+(r*r*r);
x=x/10;
}
if(s==t)
c=1;
return(c);
}
Function 243

Output:
This is a C program to check the number is either prime or Armstrong
Input a positive integer number: 2
Input X (or x) to check prime or Y (or y) to check Armstrong number: x
The input 2 is a prime number
This is the end of the program
Q7. C Program to Check Prime Number using Function.
Solution
/*************************************************************************
FILE NAME: checkprime.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check prime number using function
*************************************************************************/
#include<stdio.h>
int prime(int); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to check the number is prime or not\n”);
printf(“Input a positive integer number:”);
scanf(“%d”,&x);
y=prime(x); /*function call*/
if(y==1)
printf(“%d is a prime number”,x);
else
printf(“%d is not a prime number”,x);
printf(“\nThis is the end of the program”);
}
int prime(int x) /*function definition*/
{
int i=2;
while(i<=x/2)
{
if(x%i==0)
return 0;
else
i++;
}
return 1;
}

Output:
This is a C program to check the number is prime or not
Input an integer to check prime number: 2
244 Concepts and Techniques of Programming in C

2 is a prime number
This is the end of the program.
Q8. C Program to Check the Prime Number between the Ranges entered by User.
Solution
/*************************************************************************
FILE NAME: checkprime.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check the prime number between the ranges
entered by user
*************************************************************************/
#include<stdio.h>
int prime(int num); /*function prototype/declaration*/
void main(void)
{
int x,y,i,z;
printf(“This is the c program to check the prime number and the ranges is
entered by user\n”);
printf(“Input two integer numbers(suppose[1-100]): “);
scanf(“%d %d”,&x, &y);
printf(“Prime numbers between inputted [%d and %d] are: “,x,y);
for(i=x+1;i<y;++i)
{
z=prime(i); /*function call*/
if(z==0)
printf(“%d “,i);
}
printf(“\nThis is the end of the program”);
}
int prime(int num) /* User-defined function to check prime number*/
{
int i,z=0;
for(i=2;i<=num/2;++i)
{
if(num%i==0)
{
z=1;
break;
}
}
return(z);
}

Output:
This is a C program to check the prime number and the range is entered by user
Input two integer numbers (suppose [1-100]): 1 30
Function 245

Prime numbers between input [1 to 30] are: 2 3 5 7 11 13 17 19 23 29


This is the end of the program.
Q9. C Program to Find Hcf and Lcm using Function.
Solution
/*************************************************************************
FILE NAME: hcf.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find HCF and LCM using function
*************************************************************************/
#include <stdio.h>
long gcd(long, long); /*function declaration*/
void main(void)
{
long x,y,hcf,lcm;
printf(“This is the c program to find HCF and LCM using function\n”);
printf(“Input two integer numbers:”);
scanf(“%ld%ld”,&x,&y);
hcf=gcd(x,y); /*function call*/
lcm=(x*y)/hcf; /*function call*/
printf(“GCD of inputted %ld and %ld is: %ld\n”,x,y,hcf);
printf(“LCM of inputted %ld and %ld is: %ld\n”,x,y,lcm);
printf(“\nThis is the end of the program”);
}
long gcd(long m, long n) /*function definition*/
{
if (m==0)
{
return n;
}
while (n!=0)
{
if (m > n)
{
m=m-n;
}
else
{
n= n-m;
}
}
return m;
}

Output:
This is a C program to find HCF and LCM using function
Input two integer numbers: 3 4
246 Concepts and Techniques of Programming in C

GCD of input 3 and 4 is: 1


LCM of input 3 and 4 is: 12
This is the end of the program
Q10. C Program to Find Factoral of a Number using Function.
Solution
/*************************************************************************
FILE NAME: fact.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find factorial of a number using function
*************************************************************************/
#include <stdio.h>
#include<conio.h>
int fact(int x); /*function declaration*/
void main(void)
{
int x,y;
clrscr();
printf(“This is the c program to find factorial of a number using function\n”);
printf(“Input a number to calculate factorial:”);
scanf(“%d”,&x);
y=fact(x); /*function call*/
printf(“The factorial of inputted %d is:%d”,x,y);
printf(“\nThis is the end of the program”);
getch();
}
int fact(int x) /*function definition*/
{
int i,j=1;
for(i=x;i>0;i--)
{
j=j*i;
}
return(j);
}

Output:
This is a C program to find factorial of a number using function
Input the number to calculate factorial: 5
The factorial of input 5 is: 120
This is the end of the program

TIPS TO REMEMBER
If the programmer does not write the function prototyping then it will run successful
by placing function definition part before main function.
Function 247

10.7 FORMAL PARAMETERS VS. ACTUAL PARAMETERS


The variables declared in function definition/function header and function prototype
are called formal parameters (arguments).The variables used inside the function call
are called actual parameters. The actual parameter uses the constants, variables or
expressions. The formal parameter and actual parameter should match in data type,
order and number. Their names do not need to match. It is optional, e.g., name may
match or not.
/*Examples of Formal Parameter vs. Actual Parameter*/
#include<stdio.h>
void z(int a,int b);
void main(void)
{
int x,y;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
z(x,y); /*Here x and y variables are actual parameter*/
printf(“\nThis is the end of the program”);
}
/*user-defined function section*/
void z(int a,int b) /*Here a and b variables are formal parameter*/
{
a=a+30;
b=b+20;
printf(“After modification the inputted numbers a and b become:%d,%d”,a,b);
}

Output
Input the two integer numbers: 10 20
After modification the input numbers: a=40, b=40
This is the end of the program.

EXPLANATION:
In the above program, calling function takes variables x and y as arguments are called
actual parameter and in function header variable a and b are called formal parameter.
The actual parameter variable and formal parameter variable may be same or different
but their data type should be same. The input 10 and 20 are passed from calling function
alter(10,20) to called function void alter(10,20) function then 30 is added with 10 and 20
is added with 20 and then updated results are printed through printf function.

TIPS TO REMEMBER
The actual parameter and formal parameter names may be same or different.
The data type, order and number of actual and formal parameter list must be always
same.
248 Concepts and Techniques of Programming in C

10.8 PARAMETER PASSING TECHNIQUE


The technique which is used to pass data values from one function to another function
is called parameter passing technique. Or we can say that when a function is called and
if the function accepts some parameters then there are two different ways by which the
function receives the parameters. This is discussed below.

10.8.1 Pass by Value/Call by Value


In pass by value, the copied values of calling function/actual parameters are sent to the
variables in the parameter (argument) list of the called function (formal parameters).
The called function (formal parameter) does not work on the original values of actual
parameter rather it works only on the copied values of actual parameter which are
passed from the calling function. So any changes done at called function (formal
parameter) do not affect the actual parameter. Because the formal and actual parameter
values are stored in two different memory locations. There is no connection between
these parameters. This ensures that the original value in the calling function does not
change.
/*C Program of Pass by Value*/
#include<stdio.h>
void swap_intger(int x,int y); /*function declaration*/
void main(void)
{
int x,y,z;
printf(“This is the example of pass by value\n”);
printf(“Input the two integer numbers which is to swapped:”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping the inputted numbers are:%d %d\n”,x,y);
swap_intger(x,y); /*function call*/
printf(“After swapping the inputted numbers are:%d %d”,x,y);
printf(“\nThis is the end of the program”);
}
void swap_intger(int x,int y) /*function definition*/
{
int z;
z=x;
x=y;
y=z;
}

Output:
This is the example of pass by value
Input the two integer numbers which are to be swapped: 7 8
Before swapping the input numbers are: 7 8
After swapping the input numbers are: 7 8
This is the end of the program.
Function 249

EXPLANATION:
In the above program the two numbers are not swapped because this is an example of
pass by value. Because x, y are taken as parameters of the calling function swap(x,y);
and the called function parameter x, y, e.g., void swap(int x,int y) are stored in different
memory locations. So there is no connection. But this is possible only in pass by reference.

10.8.2 Pass by Pointer/Pass by Reference/Call by Reference /Call


by Pointer/Pass by Address
In pass by reference/pointer/address, instead of sending the values, the addresses of
the calling function variables (actual parameter) are sent to the called function variables
(formal parameter). The changes made at the formal parameter can alter/modify the
values of the actual parameter (calling function). This happens because of a single
memory location is created to store both actual argument and formal argument. First,
actual argument values stores in the memory location and then formal argument values
modify the same memory location as a result actual argument values are lost and the
modified value of formal argument is sent to the calling function.
/*C Program of Pass by Reference*/
#include<stdio.h>
void swap_integer(int *x,int *y); /*function declaration*/
void main(void)
{
int x,y,z;
printf(“This is the example of pass by reference\n”);
printf(“Enter the two integer numbers which is to swap:”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping the inputted two integer numbers are :%d %d\n”,x,y);
swap_integer(&x,&y); /*function call*/
printf(“After swapping the inputted two integer numbers are:%d %d”,x,y);
printf(“\nThis is the end of the program”);
}
void swap_integer(int *x,int *y) /*function definition*/
{
int z;
z=*x;
*x=*y;
*y=z;
}
Output:
This is an example of pass by reference
Input the two integer numbers which are to be swapped: 6 7
Before swapping the input two integer numbers are: 6 7
After swapping the input two integer numbers are: 7 6
This is the end of the program.
250 Concepts and Techniques of Programming in C

EXPLANATION:
In the above program we saw swap happened because in pass by reference (pointer) the
calling function parameter and called function parameter are stored in the same memory
location. First stored the value 6 7 and in two variables and after swapping the variables
value changes, i.e., 7 6. So pass by reference is the best for swapping two numbers.

TIPS TO REMEMBER
There are major differences between the pass by value and pass by reference value.
In pass by value, it takes more memory and more time to consume because values
are copied. In pass by reference, it takes less memory and less time because no values
are copied, instead address is passing.

10.9 SCOPE OF A VARIABLE


The scope of a variable determines over which region the program of a variable is
accessible. The variables are broadly categorized on the place of declaration: (a) local
variable and (b) global variable

10.9.1 Local Variable


Internal/local variables are those variables which are declared within a particular
function. Their scope is only within the function in which they are declared. If the
variable is declared within the main function then that variable is local to main function.
If the variable is declared with the particular user defined function created by the
programmer then that variable is local to that user defined function. The local variables
cannot be accessed outside the function. The local variables by default are initialized
to garbage value.
/*Example of Local Variable*/
#include<stdio.h>
void main(void)
{
int x,y,z; /*x,y,z are local variables*/
x=5;
y=10;
z=x+y;
printf(“This is the example of local variable\n”);
printf(“Sum of x:%d and y:%d is:%d\n”,x,y,z);
printf(“This is the end of the program”);
}

Output:
Sum of x=5 and y=10 are: 15
This is the end of the program.
Function 251

10.9.2 Global Variable


External/global variables are those variables which are declared outside the main()
function. The global variables can be accessed by any function anywhere in the program.
These are by default initialized to zero.
/*Example of Global Variable*/
#include<stdio.h>
int x=12,y=8,z; /*x, y, z are global variables*/
void main(void)
{
z=x+y;
printf(“This is the example of global variable\n”);
printf(“Sum of x:%d and y:%d are :%d\n”,x,y,z);
printf(“\nThis is the end of the program”);
}

Output:
This is an example of global variable
Sum of x: 12 and y: 8 are: 20
This is the end of the program.

TIPS TO REMEMBER
The benefit of global variable is once the variable is declared never again declared.
But local variable are local to each function.

10.10 RECURSION
Recursion is the process, where a function calls itself, that is, the same function statement
is within function, which calls itself until it terminates. To terminate the recursive
function there should be a base condition. If the base condition is wrong then recursive
function will never end and that function leads to stack overflow error. Therefore,
recursion works on the principle of stack. Stack is the collection of elements where
insertion and deletion are done at a single end. The top is the pointer variable through
which push and pop operations are done. The examples of recursion are evaluations of
factorial of a number, Fibonacci series, GCD of two numbers and many more.
The factorial of a number is calculated as
fact (n)=n*(n-1)*(n-2)-----------1
For example
Factorial of 5=5*4*3*2*1=120
From programming concept of recursion is
fact=n*factorial(n-1);
If n=5 e.g fact=5*factorial(4); will be evaluated.
252 Concepts and Techniques of Programming in C

int factorial(int x)
{
if(x==0)
return(1);
else
return(x*factorial(x-1));
}

EXPLANATION:
Form the above program if x=4
Then inside the function factorial (int x); there is a same function marked in bold letters
again which calls itself, i.e., factorial (3) calls itself until it terminates. As a result the
factorial of 4 is 4*3*2*1=24.The base condition is 0 for termination.

10.11 SOME USEFUL PROGRAMMING EXAMPLES USING RECURSION.


Q1. C Program to Find Factorial of a Number using Recursion.
Solution:
/*************************************************************************
FILE NAME: recursion.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find factorial of a number using recursion
*************************************************************************/
#include<stdio.h>
int factorial_integer(int y); /*function declaration*/
void main(void)
{
int x,f;
printf(“This is the c program to find factorial of a number using recursion\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
f=factorial_integer(x); /*function call*/
printf(“The factorial of an inputted integer number is:%d”,f);
printf(“\nThis is the end of the program”);
}
int factorial_integer(int y) /*function definition*/
{
if(y==0)
return(1);
else
return(y*factorial_integer(y-1));
}

Output:
Input the integer number: 5
Function 253

The factorial of an input integer number is: 120


This is the end of the program.

EXPLANATION:
Here in the program the user enters the number 5 then the value 5 goes to the parameter
of calling function, i.e., factorial (5).Then that value is passed to the function definition,
i.e., in the parameter of called function. In the called function, since 5 is not equal to 0
then it goes to the else part. In the else part the function calculated is as 5*factorial (4);
since this program is using recursion. Then next parameter value of function header is
4 and continue the next step until it reaches the termination condition, i.e., 0. Thus, the
result of factorial of 5 is 5*4*3*2*1=120.
Q2. C Program to Find the Fibonacci Series using Recursive Function.
Solution:
/*************************************************************************
FILE NAME: recursion.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTE: 7/8/2015
NAME OF THE PROGRAM: C program to find the Fibonacci series using recursive
function
*************************************************************************/
#include<stdio.h>
int fibonacci(int x); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to find the Fibonacci series using recursive
function\n”);
printf(“Input the number of terms:”);
scanf(“%d”,&x);
printf(“The Fibonacci series are:”);
for(int m=0;m<x;m++)
{
y=fibonacci(m); /*function call*/
printf(“%d\t”,y);
}
printf(“\nThis is the end of the program”);
}
int fibonacci(int x)/*function definition*/
{
if(x==0)
return(0);
if(x==1)
return(1);
else
return(fibonacci(x-1)+fibonacci(x-2));
}
254 Concepts and Techniques of Programming in C

Output:
Input the number of terms: 5
The Fibonacci series are: 0 1 1 2 3
This is the end of the program.
Q3. C Program to Find Gcd of Two Numbers using Recursive Function.
Solution:
/*************************************************************************
FILE NAME: gcd.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find GCD of two numbers using recursive
function
*************************************************************************/
#include<stdio.h>
int gcd_integer(int x,int y); /*function prototype*/
void main(void)
{
int x,y,z;
printf(“This is the c program to find GCD of two numbers using recursion\n”);
printf(“Input the two integer numbers whose GCD is to find:”);
scanf(“%d%d”,&x,&y);
z=gcd_integer(x,y);/*function call*/
printf(“The GCD of inputted two integer numbers is:%d”,z);
printf(“\nThis is the end of the program”);
}
int gcd_integer(int x,int y) /*function definition*/
{
int z;
if(x%y==0)
return(y);
else
z=gcd_integer(y,(x%y));
return(z);
}

Output:
Input the two integer numbers whose GCD is to find: 3 4
The GCD of input two integer numbers is: 1
This is the end of the program.

EXPLANATION:
Here this program finds the greatest common divisor of two integer numbers using
recursion. Here the user inputs the two integer number 3 and 5. Then it goes to the
parameter of the calling function, i.e., gcd(5,6); then that values goes to the parameter
of function header.
Function 255

i.e., int gcd(3,5);


Inside the user-defined function if (3%5==0) the result will display since in the modulo
operation the result is not zero.

TIPS TO REMEMBER
z=gcd(y,(x%y));
return z;
Instead of the above two lines we can write return(gcd(y,x%y));

Q4. Reverse a Sentence/String using Recursion without using String Function.


Solution:
/*************************************************************************
FILE NAME: rev.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program Reverse a sentence/string using recursion
without using string function
*************************************************************************/
#include<stdio.h>
void stringrev(); /*function declaration*/
void main(void)
{
printf(“This is the c program to reverse a sentence using recursion\n”);
printf(“Input a sentence/string:”);
stringrev();
printf(“\nThis is the end of the program”);
}
void stringrev() /*function definition*/
{
char x;
scanf(“%c”,&x);
if(x!=’\n’)
{
stringrev();
printf(“%c”,x);
}
}

Output:
Input a sentence/string: dhabal
labahd
This is the end of the program.
256 Concepts and Techniques of Programming in C

Q5. C Program to Find Sum of the First nth Natural Number E.G. 1+2+3----N=N(N+1)/2
using Recursion.

Solution:
/*************************************************************************
FILE NAME: rev.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find sum of first nth natural number e.g.
1+2+3----n=n(n+1)/2 using recursion
*************************************************************************/
#include<stdio.h>
int sum(int x); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to find sum of first nth natural number[1+2+3-
----n=n(n+1)/2]\n”);
printf(“Input the nth term:”);
scanf(“%d”,&x);
y=sum(x); /*function call*/
printf(“The sum of inputted 1 to nth term is:%d”,y);
printf(“\nThis is the end of the program”);
}
int sum(int x) /*function definition*/
{
if(x==0)
return x;
else
return x+sum(x-1);
}

Output:
Input the nth term: 5
The sum of input 1 to nth term is: 15
This is the end of the program.
Q6. C Program of Sum of Digits of a Integer Number using Recursion.
Solution:
/*************************************************************************
FILE NAME: sumdig.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program of sum of digits of a integer number using
recursion
*************************************************************************/
Function 257

#include<stdio.h>
int sum_integer_digit(int x); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program of sum of digits of an integer number using
recursion\n”);
printf(“Input an integer number:”);
scanf(“%d”,&x);
y=sum_integer_digit(x); /*function call*/
printf(“Sum of digits of inputted integer number is:%d”,y);
printf(“\nThis is the end of the program”);
}
int sum_integer_digit(int x) /*function definition*/
{
if(x==0)
return(0);
else
return(x%10)+sum_integer_digit(x/10);
}

Output:
This is a C program of sum of digits of an integer number using recursion
Input a number: 123
Sum of digits of input integer numbers is: 6
This is the end of the program.
Q7. C Program to Count the Total Number of Digits of an Integer Number using
Recursion.
Solution:
/*************************************************************************
FILE NAME: countdig.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM:C program to count the total number of digits of an
integer using recursion
*************************************************************************/
#include<stdio.h>
int countdigits_intnum(int x); /*function prototype*/
void main(void)
{
int n,m;
printf(“This is the c program to count the total number of digits of an
integer number using recursion\n”);
printf(“Input an integer number:”);
scanf(“%d”,&n);
m=countdigits_intnum(n); /*function call*/
258 Concepts and Techniques of Programming in C

printf(“Total number of digits of inputted integer number is:%d”,m);


printf(“\nThis is the end of the program”);
}
int countdigits_intnum(int x) /*function definition*/
{
static int counter=0;
if(x!=0)
{
counter++;
countdigits_intnum(x/10);
}
return(counter);
}

Output:
This is a C program to count the total number of digits of an integer number using
recursion.
Input an integer number: 123
Total number of digits of input integer number is: 3
This is the end of the program.
Q8. C Program to Find Factorial of two Integer Numbers Simultaneously using
Recursive Function.
Solution:
/*************************************************************************
FILE NAME: fact1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM:C program to find factorial of two integer numbers
simultaneously using recursive function.
*************************************************************************/
#include<stdio.h>
int factorial(int b); /*function prototype*/
void main(void)
{
int x,y,f1,f2;
printf(“This is the c program to find factorial of two integer numbers
simultaneously using recusion\n”);
printf(“Input two integer numbers:”);
scanf(“%d %d”,&x,&y);
f1=factorial(x); /*function call*/
f2=factorial(y); /*function call*/
printf(“The factorials of inputted two integer numbers simultaneously are:%d
%d”,f1,f2);
printf(“\nThis is the end of the program”);
}
Function 259

int factorial(int b) /*function definition*/


{
if(b==0)
return(1);
else
return(b*factorial(b-1));
}

Output:
Input the two integer numbers: 3 4
The factorials of input two integer numbers simultaneously are: 6 24
This is the end of the program.
Q9. C Program to Convert Decimal to Binary Equivalent using Recursion.
Solution:
/*************************************************************************
FILE NAME: bin.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to convert decimal to binary equivalent
using recursion
*************************************************************************/
#include<stdio.h>
long binary(int);/*prototype declaration*/
void main(void)
{
long m;
int x;
printf(“This is the c program to convert decimal to binary using recursion\n”);
printf(“Input the decimal number: “);
scanf(“%d”,&x);
m=binary(x); /*calling function*/
printf(“Binary representation of inputted decimal number is: %ld”,m);
printf(“\nThis is the end of the program”);
}
long binary(int y)/*function definition*/
{
static long m,remainder,f= 1;
if(y!= 0)
{
remainder =y% 2;
m= m+ remainder * f;
f= f*10;
binary(y/ 2);
}
return m;
}
260 Concepts and Techniques of Programming in C

Output:
Input the decimal number: 12
Binary representation of input decimal number is: 1100
This is the end of the program.
Q10. C Program to Check a Number is Prime Number or not by Recursion.
Solution:
/*************************************************************************
FILE NAME: prime.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check a number is prime number or not
by recursion
*************************************************************************/
#include<stdio.h>
int prime(int,int);/*prototype declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to check a number is prime or not using
recursion\n”);
printf(“Input a positive integer number: “);
scanf(“%d”,&x);
y= prime(x,x/2);/*function call*/
if(y==1)
printf(“The inputted %d is a prime number”,x);
else
printf(“The inputted %d is not a prime number”,x);
printf(“\nThis is the end of the program”);
}
int prime(int num,int i)/*function definition*/
{
if(i==1)
{
return 1;
}
else if(num%i==0)
return 0;
else
prime(num,i-1);
}

Output:
Input a positive integer number: 3
The input 3 is a prime number
This is the end of the program.
Function 261

TIPS TO REMEMBER
In a function, the return statement returns only one value to the calling function at
a time.

Q11. C Program to Find Hcf and Lcm using Recursion.


Solution:
/*************************************************************************
FILE NAME: lcm.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find HCF and LCM using recursion.
*************************************************************************/
#include <stdio.h>
long gcd(long,long); /*function prototype*/
void main(void)
{
long x,y,hcf,lcm;
printf(“This is the c program to find HCF and LCM using recursion\n”);
printf(“Input the two integer numbers:”);
scanf(“%ld%ld”,&x,&y);
hcf=gcd(x,y); /*function call*/
lcm=(x*y)/hcf;
printf(“GCD of inputted %ld and %ld is: %ld\n”,x,y,hcf);
printf(“LCM of inputted %ld and %ld:%ld\n”,x,y,lcm);
printf(“\nThis is the end of the program”);
}
long gcd(long m, long n) /*function definition*/
{
if (n==0)
{
return m;
}
else
{
return gcd(n,m%n);
}
}

Output:
Input the two integer numbers: 3 4
GCD of input 3 and 4 is: 1
LCM of input 3 and 4 is: 12
This is the end of the program.
262 Concepts and Techniques of Programming in C

Q12. C program for Tower of Hanoi using Recursion.


Solution:
/*************************************************************************
FILE NAME: tower.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program for Tower of Hanoi using Recursion.
*************************************************************************/
#include <stdio.h>
void tower1(int, char, char, char); /*function declaration*/
void main(void)
{
int x;
printf(“Input the number of disks : “);
scanf(“%d”, &x);
printf(“The sequence of disk moves in the Tower of Hanoi are \n”);
tower1(x, ‘S’, ‘T’, ‘D’); /*function call*/
printf(“\nThis is the end of the program”);
}
void tower1(int x, char S, char T, char D) /*function definition*/
{
if (x==1)
{
printf(“\nMove Disk %d From[%c to %c]”,x, S, D);
return;
}
tower1(x-1, S, D,T);
printf(“\nMove Disk %d From[%c to %c]”,x, S, D);
tower1(x-1, T, S,D);
}

Output:
Input the number of disks: 2
The sequence of disk moves in the Tower of Hanoi is:
Move disk1 from[ S to T]
Move disk2 from[ S to D]
Move disk1 from[ T to D]
This is the end of the program.

EXPLANATION:
Tower of Hanoi is a mathematical puzzle where there should have three rods and
n disks. The objective of the puzzle is to move the entire stack to another rod, by
following the simple rules:
1. Only one disk can be moved at a time.
Function 263

2. Each move consists of taking the upper disk from one of the stacks and placing it
onto the top of another stack, i.e., a disk can only be moved if it is the uppermost
disk on a stack.
3. No disk may be placed on top of a smaller disk.
In the above program num is the number of disks on source rod s. We can solve
it for n=1 and n=2.
So here we presented S is the source rod, T is the temporary rod and D is the destination
rod.

When n=1
The disk is place:
S------>D
When n=2
The disk is placed:
S----->T
S----->D
T----->D
When n=3
The disk is placed:
S--->D
S---->T
D----->T
S------>D
T------->S
T------->D
S------->D

10.12 STORAGE CLASS IN C


In chapter on variable we learnt that when a variable is declared it is stored in memory.
But we did not specified where it is stored. So there are two kinds of storage locations
in a computer, i.e., memory and register. These storage classes of variables determine
where the variables are stored. That means the variable either is stored in computer hard
disk or temporary memory register.
There are four types of storage classes in C. They are:

10.12.1 Automatic Variable


The automatic variables are local to the function. These variables are declared by using
the keyword auto inside the function. These variables start working when the function
is called and is destroyed automatically when the function is closed, hence, the name
automatic. The automatic variable is stored in memory and without initializing the
automatic variable, it takes garbage value. The variable declared inside any functions
264 Concepts and Techniques of Programming in C

without storage class is by default is an automatic variable.


/*Auto Variable Example*/
#include<stdio.h>
void z();
void main(void)
{
int x; /* x is local variable to function main()*/
printf(“This is the example of auto variable\n”);
printf(“The values of x are:”);
for(x=1;x<4;x++)
{
z();
}
printf(“\nThis is the end of the program”);
}
void z()
{
auto int x=0; /*here x is auto to function z() */
printf(“ %d “,x);
x=x+1;
}

Output:
This is an example of auto variable
The values of x are: 0 0 0
This is the end of the program.

EXPLANATION:
The input of the first, second and third iterations is 0 because auto variable is initialized
each time.

10.12.2 Static Variable


A static variable is declared by using the keyword static. The static variable exists until
the program closes. When the program is compiled, the static variable is initialized only
once and it does not require reinitialization again. The static variable stored in memory
and without initializing it contains the value zero. The scope of variable is local to the
function. The static variable is of two types: internal type and external type. Internal
static variable is declared inside the function. The external static variable is declared
outside the function and all other functions can access that program.
/*Example of Static Variable*/
#include<stdio.h>
void z();
Function 265

void main(void)
{
int x;
printf(“This is the example of static variable\n”);
printf(“The values of x are:”);
for(x=1;x<4;x++)
{
z();
}
printf(“\nThis is the end of the program”);
}
void z()
{
static int x=0;
printf(“ %d “,x);
x=x+1;
}

Output:
This is an example of static variable
The values of x are: 0 1 2
This is the end of the program.

EXPLANATION:
During the first call x=0, second call x=1, third call x=2. Because if once the static variable
is initialized it is never initialized again. The next will be incremented until termination.

10.12.3 Register Variable


A register variable is declared by using the keyword register. The register variable is
stored in CPU's register instead of computer memory. The access CPU register is faster
than memory in computer. Without initializing the register variable it takes garbage
value (unknown value). Their scope is within the function.
/*Examples of Register Variables using C Program*/
#include<stdio.h>
void main(void)
{
register int x;
printf(“This is the example of register variable\n”);
printf(“The values of x are:”);
for(x=1;x<=15;x++)
{
printf(“%d\t”,x);
}
printf(“\nThis is the end of the program”);
}
266 Concepts and Techniques of Programming in C

Output:
This is an example of register variable
The values of x are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
This is the end of the program.

10.12.4 External Variable


External variables are declared outside all the functions and all functions use that
variable. External variables are also called global variables. The external variables are
stored in memory and without initializing contain the value zero.
/*Examples of External Variables*/
#include<stdio.h>
int y=10;
void main(void)
{
extern int x;
printf(“This is the example of external variable”);
printf(“%d %d”,x,y);
printf(“\nThis is the end of the program”);
}
int x=20;

Output:
This is an example of external variable
20 10
This is the end of the program.
/*Another Examples of External Variables*/
#include <stdio.h>
extern int x,y;
extern int z;
extern float f;
void main (void)
{
int x,y;
int z;
float f;
x= 10;
y= 20;
z= x+ y;
printf(“value of z is: %d \n”,z);
f = 40/2.0;
printf(“value of f is : %f”,f);
printf(“\nThis is the end of the program”);
}
Function 267

Output:
Value of z is: 30
Value of f is: 20.00
This is the end of the program.
Comparison between four variables.

Auto variable Static variable Register variable External variable


It is stored in memory It is stored in memory It is stored in CPU It is stored in memory
register
Its scope is local Its scope is local Its scope is local Its scope is global
Without initializing Without initializing it Without initializing Without initializing it
it contains garbage contains zero value. it contains garbage contains zero value.
value. value.

SUMMARY

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


2. There are two types of function: library function and user-defined function.
3. Examples of library functions are sqrt, printf, scanf and example of user defined
functions are main and any function created by user.
4. There are three basic things a programmer should know before using the user-
defined function. These are function declaration, function call and function
definition.
5. Function declaration is also known as function prototyping.
6. Function prototyping gives the information to the C compiler about the function
name, return type and list of parameters.
7. In function call we pass the values.
8. In function definition we have to define our logic of the program and the value
should return to the calling function.
9. The variables used in function call are called actual parameters and the variables
used in function header of the user defined function are called formal parameter.
10. Local variables are declared inside the function, i.e., it may be placed in the main
function or any user defined functions. Any local variables declared inside the
function are not used by other functions. But once we declare the variable global
then any function can use the same variable in multiple functions.
11. In pass by value, values are passed from calling function to called function. Any
changes made at the called function do not affect the calling function.
12. In pass by reference instead of passing values address of that variables are passed
from calling function to called function. Any changes made at called function
affect the calling function.
268 Concepts and Techniques of Programming in C

13. The function which calls itself is called recursion.


14. To terminate the recursion, the function should have base condition to stop the
function unless it will run infinitely.
15. In storage class there are four types of variables present: auto, static, extern,
register.

SHORT QUESTIONS

1. What is function? Give its advantages.


2. Explain types of function.
3. To create user defined function the programmer should ensure three things, what
are they?
4. What is function prototyping/function declaration?
5. What is function call?
6. What is function definition?
7. How do we differentiate between formal parameter and actual parameter?
8. What is the difference between local variable and global variable?
9. What do you mean by parameter passing technique?
10. What is passing by value?
11. What is passing by reference?
12. What is recursion?
13. What is the difference between static variable and auto variable?
14. Register variables are stored in the main memory. State TRUE or FALSE.

Important QUESTIONS

1. Write short note on function prototype.


2. Explain the call by value and call by reference with example.
3. C program of sum of digits of a number using recursion.
4. C program to find factorial of two integer numbers simultaneously using recursive
function.
5. C program to convert decimal to binary equivalent using recursion.
6. Write a complete C program to check a given positive integer is a prime number
or not, by writing a recursive function.
7. What are storage classes? Discuss all storage classes using examples.
8. Explain with simple examples the use of storage classes.
9. Write a short note on storage classes.
Function 269

LONG Questions

1. Explain the formal parameters and actual parameters with suitable example.
2. Define different types of user-defined functions with suitable examples.
3. What is parameter passing technique? Explain pass by value and pass by reference
with suitable examples.
4. What is the scope of a variable? Explain local variable and global variable with
suitable examples.
5. What is recursion? Write a C program to find factorial of a number.
6. Write a C program to find GCD and LCM of two numbers using recursive
function.
7. Write a C program to find Fibonacci series using recursion.
8. Write a C program to swap two numbers using third variable by function.
9. Write a C program to swap two numbers without a third variable.
10. Write a C program to count the number of digits of a number using function.
11. Write a C program of sum of digits of a number by function.
12. Write a C program of multiplication of digits of a number by sung function.
13. Write a C program to check either Palindrome or Armstrong number depending
on the data entered by user.
14. Write a C program to check the prime number between the ranges entered by the
user.
15. Write a C program to find HCF and LCM by using function.
16. Write a C program to reverse a string using recursion.
17. Write a C program to find the sum of nth natural numbers using recursion.
18. Write a C program of sum of digits of a number using recursion.
19. Write a C program to count the total number of digits using recursion.
20. Write a C program to find factorial of two integer numbers simultaneously using
recursion.
21. Write a C program to convert decimal to binary using recursion.
22. Write a C program to check a number is prime or not using recursion.
23. Write a C program to find HCF and LCM using recursion.

OBJECTIVE QUESTIONS WITH Answers


1. Point out the error in the program
#include<stdio.h>
int z(int m)
{
m>20?return(10):return(15);
}
void main(void)
{
270 Concepts and Techniques of Programming in C

int x;
x=z(30);
printf(“%d”,x);
}
Output:
Compilation error
EXPLANATION:
The program gives compilation error because return statement is used in
conditional expression. Therefore, whenever writing a C program avoid return
statement in conditional expression.
2. Point out the error in the program
m(int x, int y)
{
int x;
x = 10;
return x;
}
Output:
Compilation error
3. What will be the output?
#include<stdio.h>
void z();
void main(void)
{
int x=10;
z();
}
void z()
{
printf(“INDIA”);
}
Output:
India
4. What will be the output?
#include<stdio.h>
void main(void)
{
int z();
int x;
x=z();
printf(“%d”,x);
}
Function 271

int z()
{
int m=2000;
return(m);
}
Output:
2000
5. What will be the output?
#include<stdio.h>
void fun(int*x, int*y);
void main(void)
{
int x=10,y=20;
fun(&x,&y);
printf(“%d,%d”,x,y);
}
void fun(int *x,int *y)
{
*x = *x**y;
*y = *y**y;
}
Output:
200, 400
6. What will be the output?
#include<stdio.h>
int rev(int y);
void main(void)
{
int x=20;
rev(x);
}
int rev(int y)
{
if(y == 0)
return 0;
else
printf(“%d,”,y);
rev(--y);
}
Output:
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
7. What will be the output?
#include<stdio.h>
int sumdig(int);
272 Concepts and Techniques of Programming in C

void main(void)
{
int a,b;
a=sumdig(123);
b=sumdig(120);
printf(“%d, %d\n”,a,b);
}
int sumdig(int x)
{
int s,d;
if(x!=0)
{
d=x%10;
x=x/10;
s=d+sumdig(x);
}
else
return 0;
return s;
}
Output:
6, 3
8. What will be the output?
#include<stdio.h>
void main(void)
{
int x=10,y=20,p,q;
p=add(x,y);
q=add(x,y);
printf(“%d %d”,p,q);
}
add(int a,int b)
{
a+=a;
b+=b;
return(a);
return(b);
}
Output:
Compilation error
9. What will be the output?
#include<stdio.h>
int fun(int n);
void main()
{
int x;
x=fun(5);
Function 273

printf(“%d”,x);
}
int fun(int n)
{
int x=1,k;
if(n==1)
return x;
for(k=1;k<n;++k)
x=x+fun(k)*fun(n-k);
return x;
}
Output:
51

MULTIPLE-Choice QUESTIONS

1. The keyword used to transfer control from an user defined function to the calling
function is
(a) switch (b) goto (c) go back (d) return
[Answer: d]
The keyword return is used in user-defined function to return back the values to
the calling function.
2. What is the notation for following functions?
1. int f(int a, float b)
{
}
2. int f(a, b)
int a; float b;
{
}
(a) KR Notation
ANSI Notation
(b) Pre ANSI C Notation
KR Notation
(c) ANSI Notation
KR Notation
(d) ANSI Notation
Pre ANSI Notation
[Answer: c]
KR Notation means Kernighan and Ritchie Notation.
274 Concepts and Techniques of Programming in C

3. How many number of times the program will print “India”?


#include<stdio.h>
void main()
{
printf(“India”);
main();
}
(a) infinite times
(b) 32767 times
(c) 65535 times
(d) Till the stack overflows
[Answer: d]
11
Array

11.1 INTRODUCTION
Using fundamental data types (int, char, float, double), a single variable of these types
can store only one value at a given time. When many times a single variable is assigned
the different values then what values the variable will hold? Let’s see the example
below and see the output.
#include<stdio.h>
void main(void)
{
int z;
z=10;
z=20;
z=30;
printf(“Value of z is:%d”,z);
}

Output:
Value of z is: 30

EXPLANATION:
From the above example the question arises how the value of z becomes 30? When
same variable is assigned many values, i.e., first 10 is assigned to variable z then 20 is
assigned to z and then 30 is assigned to z then one can get confused that what will be
the output? The solution of the above example is first 10 is assigned to variable z, so
10 is stored in variable z and then when 20 is assigned to the same variable z at that
time old value of z is lost and new value 20 is stored in variable z and last when 30
is assigned to variable z at that time again old value is lost. This is because a single
variable can store only one value at a time. Finally, 30 becomes value of variable z.
276 Concepts and Techniques of Programming in C

Then a if programmer wants to store the above three values and display them then
he can use three different variables.
Let’s see the example
#include<stdio.h>
void main(void)
{
int x,y,z;
x=10;
y=20;
z=30;
printf(“Value of x is:%d\n”,x);
printf(“Value of y is:%d\n”,y);
printf(“Value of z is:%d”,z);
}

Output:
Value of x is:10
Value of y is:20
Value of z is: 30

EXPLANATION:
In the above example three values are assigned to individual variables and then print
its values by using printf() function. By following the above concepts and techniques,
if a programmer wants to store 1000 values and display them he will create 1000
variables to store the values. So it creates problem for the programmer. To solve the
problem array can be used.
In arrays, instead of creating 1000 variables of same type to store 1000 values, the
programmer will create only one variable and it will store 1000 or more values. How
can it be possible for a beginner? To get the solution follow the Q1 in some useful
programming examples of one-dimensional array. Thus, array is the fixed-size series
of variables of same data type.

TIPS TO REMEMBER
• The derived data type array can also be called subscripted variables.
• The definition of array is: it is the fixed series of variables of same data type and
size by giving a name.
• Another definition, an array is the collection of elements of same type and size
and by using it we can create a common variable and that variable holds many
values called array.
• The array elements are generally stored in contiguous memory location.
Array 277

What are the Major Areas Arrays that can be Implemented?


Solution:
Arrays can be implemented when large number of data of same type are required to
store. Suppose examples: 1) The customer name and their account details e.g. account
no, account type and contact mobile phone numbers stored in a bank. 2) The list of
employees working in an particular organization. 3) Internal exam marks obtained by
each student in a particular branch. 4) The temperature recorded in different place of
India and abroad in daily, monthly and yearly. 5) The rain fall recorded data in different
centers in India or abroad daily, monthly, yearly by metrological dept.
Instead of storing series of values in array we can also stores tables of data in two,
three and more dimensions. So the array can be different types. They are
(a) One-dimensional array
(b) Two-dimensional array
(c) Three-dimensional arrays (3-D Array)

11.2 ONE-DIMENSIONAL ARRAY


11.2.1 Declaration of One-Dimensional Array

The syntax of one-dimensional array is:


datatype variable_name[size];

Explanation:
In the above syntax data type determines the type of elements/values that the array
will store. It may be integer type, float type, char type or double type. The variable_
name is the name of the array and last size specifies the maximum number of elements
that the array can store.
Example 1:
int marks[50];

EXPLANATION:
This declaration specifies that marks variable stores 50 student’s marks of a particular
subject. The individual element/value of marks is called array elements, e.g., marks[0]
will store one values and marks[1] stores another values till marks[49].
Here int specifies data type of the array, marks is the name of the array, [50] represents
the size of the array is 50. The symbol square bracket [] used in array is called array
indices or subscript.
278 Concepts and Techniques of Programming in C

TIPS TO REMEMBER
When the array is declared the elements of the array contain garbage values at that
time.
Size used in array may be a numeric constant or a symbolic constant.

11.2.2 One-Dimensional Array Initialization


The programmer can assign values to an array and it is called array initialization.
Array initialization can be done in two ways: at compile time initialization and runtime
initialization.
Compile time initialization is simple, like initialization of values to normal variables.
But in runtime initialization the programmer forcefully initializes the array.

The syntax of one-dimensional array initialization/compile time initialization


array is:
datatype array_name[size]={value1,value2-----valueN};

Example 2:
int marks[4]={40,45,50,55};

EXPLANATION:
This declaration tells that the variable marks as an array of size 4 and thus the values 40,
45, 50, 55 are stored in each variable or an array element. Let’s see how the initialized
values are stored in consecutive memory location of array marks. Suppose the base
address of array is100 then each location will take 2 bytes of memory. Because array
name marks is int type whose size is 2 bytes. So the memory addresses are 100, 102,
104, 106.

marks[0] marks[1] marks[2] marks[3]


40 45 50 55
100       102 104 106

Example 3:
int marks[4]={40,45};

EXPLANATION:
In the above example marks variable creates 4 memory locations. But two values
are initialized. So the first elements are stored in the first memory locations and the
second element is stored in the second memory locations and the remaining values
are stored in other memory locations. Third memory and fourth memory locations
will automatically store the value zero. Let us see the above example in tabular form.
Array 279

marks[0] marks[1] marks[2] marks[3]


40 45 0 0
200 202 204 206
The character array is initialized as
char name[]={‘r’,’a’,’m’};
In compile time initialization the number of initialization may be less than the array
size. In that case remaining elements are initialized to zero.

TIPS TO REMEMBER
Sets of values are stored in a single variable name given by the programmer using a
single data type from fundamental data types is called as an array. Thus, array can
store large number of elements by same type.
The individual value in the array is called array element.
The position of each array element in the array is called the array index/subscript.
In one-dimensional array, the array index starts with the value zero and last maximum
size minus one.

TIPS TO REMEMBER
When an array is declared without initialization the total array contains the garbage
value. But suppose when the array size is 4 but one element is initialized then rest
of memory locations default assigned to zero.

11.2.3 Useful Programming Examples of One-Dimensional Array


Q1. C Program of Initialization of One-Dimensional Array.
Solution:
/*************************************************************************
FILE NAME: array1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: C program of initialization of one-dimensional array.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x;
int marks[4]={30,35,40,45};
for(x=0;x<4;x++)
printf(“The marks of student[%d] is:%d\n”,x,marks[x]);
}
280 Concepts and Techniques of Programming in C

Output:
The marks of student [0] is: 30
The marks of student [1] is: 35
The marks of student [2] is: 40
The marks of student [3] is: 45

EXPLANATION:
The above program is initialization of one-dimensional array. Here 30, 35, 40, 45
are assigned to array named marks, e.g., marks[0]=30,marks[1]=35,marks[2]=40,
marks[3]=45. The for loop is used to display each initialized value.

TIPS TO REMEMBER
A good programmer should try to define symbolic constant as the size of the array.

Q2. C Program to Insert the Elements into the Array and Display It.
Solution:
/*************************************************************************
FILE NAME: array2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to insert the elements into the array and
display it
*************************************************************************/
#include<stdio.h>
#define M 3
void main(void)
{
int x[M],y;
for(y=0;y<M;y++)
{
printf(“Input the elements of the array x[%d]:”,y);
scanf(“%d”,&x[y]);
}
for(y=0;y<M;y++)
{
printf(“The inputted elements of the array x[%d] is:%d\n”,y,x[y]);
}
}

Output:
Input the elements of the array x[0]:5
Input the elements of the array x[1]:6
Input the elements of the array x[2]:7
Array 281

The input elements of the array x[0] is:5


The input elements of the array x[1] is:6
The input elements of the array x[2] is:7

EXPLANATION:
Here in the above program, instead of fixing the size of the array we have used symbolic
constant, M, i.e., size of the array is 3. We cannot store more than 3 elements in the above
array. Then we have input the elements through scanf() function by using for loop.
Then using for loop and printf() function we have displayed the elements of the array.
Instead of using the symbolic constant we can alternatively write the same program.
Let’s see the same program.
#include<stdio.h>
void main(void)
{
int x[100],y,n;
printf(“Input the size of the array:”);
scanf(“%d”,&n);
for(y=0;y<n;y++)
{
printf(“Input the elements of the array x[%d]:”,y);
scanf(“%d”,&x[y]);
}
for(y=0;y<n;y++)
{
printf(“The inputted elements of the array x[%d] is:%d\n”,y,x[y]);
}
}

Q3. C Program to Find Sum and Average of N Numbers using Array/One-Dimensional


Array.
Solution:
/*************************************************************************
FILE NAME: array3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program of find the sum and average of n numbers
using one dimensional array
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x[50],n,sum=0,j;
float avg;
printf(“Input the size of the array:”);
scanf(“%d”,&n);
282 Concepts and Techniques of Programming in C

printf(“Input the elements of the array:”);


for(j=0;j<n;j++)
{
scanf(“%d”,&x[j]);
}
for(j=0;j<n;j++)
{
sum=sum+x[j];
}
printf(“The sum of elements of the array is:%d\n”,sum);
avg=sum/n;
printf(“The Average of inputted array elements is:%f”,avg);
}

Output:
Input the size of the array: 3
Input the elements of the array: 3 4 5
The sum of elements of the array is:12
The average of input array elements is: 4.000000

EXPLANATION:
Here, suppose the user input the size of the array, i.e., 3. Then the user input the
elements of the array by using scanf function and for loop. Then using the for loop
we have stored each individual element into the variable sum till j<3. When j value
becomes 3 the loop terminates and then divide the sum with the size of the array and
store the results in the variable avg and the printf statement prints that average value.
Q4. C Program to Find the Largest Number Among N Numbers.

Solution:
/*************************************************************************
FILE NAME:array4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: C program to find largest number among N numbers
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x[10],j,y,n;
printf(“Input the size of the array:”);
scanf(“%d”,&n);
printf(“Input the elements of the array:\n”);
for (j=0;j<n;j++)
{
scanf(“%d”,&x[j]);
}
Array 283

y=x[0];
for(j=1;j<n;j++)
{
if (x[j]>y)
y=x[j];
}
printf(“\The largest element among inputted array elements is:%d”,y);
}

Output:
Input the size of the array: 4
Input the elements of the array
2 7 1 14
The largest element among input array elements is: 14

EXPLANATION:
Here the objective of the program is to find the largest element among the array. Here,
the user enters the size of the array, suppose 4 then he will input the elements of the
array through scanf() function and for loop. Then suppose x[0] value is assigned to the
larger variable. To find the largest among the array elements, the next step is to initialize
the variable j= 1 in for loop and check the condition 1<4. Since it satisfies execute the
loop and inside the for loop we have used the if condition to measure between x[1]
and larger, if(x[1]>larger) e.g. 7>1 then larger=7. Next loop increments to 2 and inside
the loop again test the condition as if(x[3]>larger) e.g. 14>7 yes condition satisfied,
therefore larger=14 and next loop increments to 4. As the maximum size of loop is 4,
therefore loop terminates.
Q5. C Program to Find Smallest Elements in One-Dimensional Array.
Solution:
/*************************************************************************
FILE NAME: array5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to find smallest elements in one dimensional
array.
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void)
{
int x[100],y,n,i,loc=1;
clrscr();
284 Concepts and Techniques of Programming in C

printf(“Input the size of the array:”);


scanf(“%d”,&n);
printf(“Input %d elements of the array:”,n);
for(i=0;i<n;i++ )
{
scanf(“%d”,&x[i]);
}
y=x[0];
for(i=1;i<n;i++)
{
if(x[i]<y)
{
y=x[i];
loc=i+1;
}
}
printf(“Smallest element is present at location[%d] and the value is:
%d”,loc,y);
getch();
}

Output:
Input the size of the array: 3
Input 3 elements of the array: 3 8 1
Smallest elements is present at location [3] and the value is: 1

EXPLANATION:
Adopt the largest number among three using array explanation.
Q6. C Program to Generate the Fibonacci Series of N Numbers using Array.
Solution:
/*************************************************************************
FILE NAME: array6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to generate the Fibonacci series of n
numbers using array
*************************************************************************/
#include<stdio.h>
#define M 5
void main(void)
{
int fib[M];
int x;
fib[0]=0;
fib[1]=1;
for(x=2;x<M;x++)
{
Array 285

fib[x]=fib[x-1]+fib[x-2];
}
printf(“The Fibonacci series are:”);
for(x=0;x<M;x++)
{
printf(“%d\t”,fib[x]);
}
}

Output:
The Fibonacci series are: 0 1 1 2 3

EXPLANATION:
Here we have mentioned the symbolic constant #define M 5. It means instead of 5 we
have given named it M. So M is the substitute name of 5. In that program first two
values are initialized as 0 and 1 and are stored in two array elements. The size of fib
array is 5. Then for loop starts with index 2 and it increments till 4 because it is less
than 5. When x=2 and 2<5 the fib[2]=fib[2-1]+fib[2-2], i.e., fib[2]=fib[1]+fib[0] and the
for loop works till condition is satisfied. When the loop terminates for loop is again
used to display the Fibonacci series.
Q7. C Programs of Reverse the Array.
Solution:
/*************************************************************************
FILE NAME: array7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: C program of reverse the array
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void)
{
int x[100],y[100],n,i,j;
clrscr();
printf(“Input the size of the array:”);
scanf(“%d”,&n);
printf(“Input the elements of the array:”);
for (i=0;i<n;i++)
scanf(“%d”,&x[i]);
for (i=n-1,j=0;i>=0;i--,j++)
{
y[j]=x[i];
}
for(i=0;i<n;i++)
{
286 Concepts and Techniques of Programming in C

x[i]=y[i];
}
printf(“The Reverse of inputted array elements are:”);
for(i=0;i<n;i++)
{
printf(“ %d “,x[i]);
}
getch();
}

Output:
Input the size of the array: 4
Input the elements of the array: 2 3 4 5
The reverse of input array elements are: 5 4 3 2

11.2.4 Passing One-Dimensional Array Elements as an Argument in Function


Generally, till now we passed one variable or multiple variables as an argument in
function. Now we can pass the array elements as an argument in function. It may be
individual array elements or the entire array. Passing one-dimensional array elements
as an argument to function in different forms. They are: passing individual array
elements by using pass by value method, passing individual array elements using pass
by reference, Passing the entire array as an argument in function by pass by value,
passing the entire array as an argument in function by pass by reference.

11.2.4.1 Passing Individual Array Elements by Using Pass by Value


Here in this method the user can pass the individual array element instead of all the
elements as an argument to function.
Q8. /*C Program to Pass One-Dimensional Array Elements as an Argument in
Function using Pass by Value.*/
#include <stdio.h>
void display(int a,int b,int c);
void main(void)
{
int x[]={20,31,42};
display(x[0],x[1],x[2]); /*Passing array elements x[0,x[1]],x[2].*/
}
void display(int a,int b,int c)
{
printf(“The array elements are:%d %d %d”,a,b,c);
}

Output:
The array elements are: 20, 31, 42
Array 287

Explanation:
Here in the above program the individual element x[0],x[1],x[2] are passed from the
calling function display(); to the called function void display(int a,int b,intc){ }.

11.2.4.2 Passing Individual Array Elements Using Pass by Reference/Address


Operator
Here in this method the user can pass the individual array element by using address
operator of the each element in the calling function and in the called function the
pointer variable holds the address of array element.
Q9. /*Example of Passing Individual Array Elements using Pass by Reference*/
#include <stdio.h>
void display(int *a,int *b,int *c);
void main(void)
{
int x[3]={20,31,42};
display(&x[0],&x[1],&x[2]); /*Passing array elements x[0,x[1]],x[2].*/
}
void display(int *a,int *b,int *c)
{
printf(“The array elements are:%d %d %d”,*a,*b,*c);
}

Output:
The array elements are: 20,31,42

Explanation:
Here three elements x[0],x[1] and x[2] are passed from the calling function by using the
address operator with each element to the called function and in the called function
three pointer variables are declared which hold the address of each element and in the
end last using dereferencing operator we can print the each individual element.

11.2.4.3 Passing the Entire Array Elements as an Argument in Function by Pass


by Value
Passing the entire array as an argument means name of the array is passed (the
base address is passed) from the calling function to the called function. Let’s see the
programming examples.
Q10. C Program to Sum all the Elements of an Array Using Function.
Solution:
/*************************************************************************
FILE NAME: hcf.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
288 Concepts and Techniques of Programming in C

NAME OF THE PROGRAM: C program to sum all of the elements of an array


using function
*************************************************************************/
#include <stdio.h>
int s(int m[], int n);/*function declaration*/
void main(void)
{
int m[10]= {10,20,30,40,50,60,70,80,90,100};
int x;
x = s(m, 10);/*function call*/
printf(“The sum of the array elements are: %d\n”,x);
}
int s(int m[], int n) /*function definition*/
{
int i,sum=0;
for(i=0;i<n;i++)
{
sum=sum+m[i];
}
return(sum);
}

Output:
The sum of the array elements is 550

Explanation:
Here in the above program the array name is passed for the entire array instead of
individual array element.
Q11. C Program to Find the Greatest Number Among Array Elements using Function.

Solution:
/*************************************************************************
FILE NAME: hcf.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: c program to find greatest number among array elements
using function.
*************************************************************************/
#include <stdio.h>
int max_num(int z[],int n); /* function prototype */
void main()
{
int z[100],i,x,m;
printf(“Input the size of the array:”);
scanf(“%d”,&m);
printf(“Input the elements of the array:”);
for(i=0;i<m;++i )
Array 289

scanf(“%d”,&z[i]);
x=max_num(z,m); /*function call*/
printf(“Greatest number among the array is:%d\n”,x);
}
int max_num(int z[],int m) /*function definition*/
{
int big,i;
big=z[0];
for(i=1;i<m;++i )
if(z[i]>big)
big=z[i];
return(big);
}

Output:
Input the size of the array: 3
Input the elements of the array: 3 2 10
Greatest number among the array is: 10

Explanation:
Here in the above program all the array elements are passed by using pass by value
method so array name z and size m is passed inside the calling function max_num(); to
called function then inside called function we declare the variable big which holds the
first element by assigning z[0] to big variable and using for loop we compare the second
element of the array to size-1 element with first element. and if the array element is
greater than big variable value then find the greater number else big variable assigning
first element is the greatest.

11.2.4.4 Passing the Entire Array Elements as an Argument in Function by Pass


by Reference or Address Operator
While passing the entire array using pass by reference then address of variable is passed
to called function. Since name of the array is called constant pointer, e.g., base address
or address of starting element in the array, therefore do not require to put address in
front of array name.
/*Example of Passing the Entire Elements in Function using Pass by Reference*/
#include <stdio.h>
void z(int *value,int num);/*function prototyping*/
void main()
{
int x[5]={10,20,30,40,50};
z(x,5);/*function call*/
}
void z(int *value, int num) /*function definition*/
{
290 Concepts and Techniques of Programming in C

for(int j=0; j<num; j++)


{
printf(“Value of x[%d] is: %d \n”, j, *value);
value++; /*increment operator used in pointer for displaying next element*/
}
}

Output:
Value of x[0] is:10
Value of x[1] is:20
Value of x[2] is:30
Value of x[3] is:40
Value of x[4] is:50

11.3 TWO-DIMENSIONAL ARRAYS


Two-dimensional arrays are represented in the form of matrix and tables. The arrays
have two subscripts: one represents the row and other represents the columns.

11.3.1 Declaration of Two-Dimensional Arrays

The syntax of a two-dimensional array is:


data_type array_name[rowsize][columnsize];

Example:
int marks[3][3];

EXPLANATION:
In the above example the first index stores the row and the second index stores the
column, i.e., marks variable holds 3 rows and 3 columns.
Let us first see the two-dimensional representation of marks variables.

Table 10.1 Shows the marks [3][4]

marks[0][0] marks[0][1] Marks[0][2]


marks[1][0] marks[1][1] marks[1][2]
marks[2][0] marks[2][1] marks[2][2]

11.3.2 Two-Dimensional Array Initialization


Like a one-dimensional array, two-dimensional arrays can be initialized by declaration
with list of values enclosed in braces.
Array 291

The syntax is:


data_type array_name[rowsize][columnsize]={value1,value2------valueN};

Example:
int marks[3][3]={30,35,40,45,50,55,60,65,70};
Or
int marks[3][3]={{30,35,40},{45,50,55},{60,65,70}};
Or
int marks[3][3]={
{30,35,40}
{45,50,55}
   {60,65,70}
  };

Table 10.2 Two-dimensional array representations

30 35 40
45 50 55
60 65 70

11.3.3 Passing Two-Dimensional Array as an Argument in Function


Passing two-dimensional arrays is the same as one-dimensional array, i.e., in three
different ways we can pass the array as an argument in function. They are: passing
individual array elements, second passing a row, third passing entire 2D array.

11.3.3.1 Passing Individual Array Elements as an Argument in Function


Passing individual array elements as an argument in 2D array means it is the same as
passing one-dimensional array.

11.3.3.2 Passing a Row as an Argument


Passing a row in two-dimensional array means instead of passing both row and column
as an argument in the 2D array we can pass the one-dimensional array as row in the
calling function as an argument to called function.
/*Example of Passing a Row as an Argument*/
#include <stdio.h>
void pass(int x[]);
void main()
{
int x[3][3]={{1,2,3},{4,5,6},{7,8,9}};
292 Concepts and Techniques of Programming in C

pass(x[0]);
}
void pass(int x[])
{
int m;
for(m=0;m<3;m++)
printf(“%d “,x[m]*15);
}

Output:
15 30 45

11.3.3.3 Passing Entire 2D Array as Argument in Function


Passing the entire 2D array as an argument in function means instead of passing one-
dimensional array we can pass the entire 2D array. Let us the example below.
/*Example of Passing Entire 2D Array*/
#include <stdio.h>
void display(int x[3][3],int z);
void main()
{
int x[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
display(x, 3);
}
void display(int x[3][3], int z)
{
int m,n;
for (m=0;m<z;m++)
for (n=0;n<3;n++)
{
printf(“%d “,x[m][n]);
}
}

Output:
123456789

11.3.4 Some Useful Programming Examples of Two-Dimensional Arrays


Q1. C Program of Addition of Two Matrices.
Solution:
/*************************************************************************
FILE NAME: twoarray1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program of addition of two dimensional arrays
*************************************************************************/
Array 293

#include<stdio.h>
void main(void)
{
int x[20][20],y[20][20],z[20][20],i,j,k,l;
printf(“Input the number of rows and columns of the two matrices:”);
scanf(“%d%d”,&k,&l);
printf(“Input the elements of the first matrix:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
scanf(“%d”,&x[i][j]);
}
}
printf(“Input the elements of the second matrix:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
scanf(“%d”,&y[i][j]);
}
}
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
z[i][j]=x[i][j]+y[i][j];
}
}
printf(“The addition of inputted two matrices is:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
printf(“%d\t”,z[i][j]);
}
printf(“\n”);
}
}

Output:
Input the number of rows and columns of the two matrices: 2 2
Input the elements of the first matrix:
3 4
2 3
Input the elements of the second matrix:
5 6
1 2
294 Concepts and Techniques of Programming in C

The addition of inputted two matrices is:


8 10
3 5
Q2. C Program of Subtraction of Two Matrices.
Solution:
/*************************************************************************
FILE NAME: twoarray2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program of Subtraction of two matrices
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x[10][10],y[10][10],z[10][10],m,n,i,j;
printf(“Input the number of rows and columns of the two matrices:”);
scanf(“%d%d”,&m,&n);
printf(“Input the elements of first matrix\n”);
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
scanf(“%d”,&x[i][j]);
}
}
printf(“Input the elements of second matrix\n”);
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
scanf(“%d”,&y[i][j]);
}
}
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
z[i][j]=x[i][j]-y[i][j];
}
}
printf(“Subtraction of two inputted matrices is:\n”);
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
printf(“%d\t”,z[i][j]);
}
Array 295

printf(“\n”);
}
}

Output:
Input the number of rows and columns of the two matrices: 2 2
Input the elements of the first matrix:
23
23
Input the elements of the second matrix:
23
23
Subtraction of two input matrices is:
0 0
0 0
Q3. C Program of Multiplication of Two Matrices.
Solution:
/*************************************************************************
FILE NAME: twoarray3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program of multiplication of two matrices
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x[10][10],y[10][10],z[10][10],i,j,k,row1,row2,col1,col2;
printf(“Ensure that number of columns of the first matrix should match number
of rows in the second matrix\n”);
printf(“Input the number of rows and columns of the first matrix:”);
scanf(“%d%d”,&row1,&col1);
printf(“Input the number of rows and columns of the second matrix:”);
scanf(“%d%d”,&row2,&col2);
if(col1!=row2)
printf(“Multiplication is not possible”);
printf(“Input the elements of the first matrix:\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&x[i][j]);
}
}
printf(“Input the elements of the second matrix:”);
for(i=0;i<row2;i++)
296 Concepts and Techniques of Programming in C

{
for(j=0;j<col2;j++)
{
scanf(“%d”,&y[i][j]);
}
}
/*multiplication done*/
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
z[i][j]=0;
for(k=0;k<row2;k++)
{
z[i][j]=z[i][j]+x[i][k]*y[k][j];
}
}
}
printf(“The multiplication of two inputted matrices is:\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf(“\t%d”,z[i][j]);
}
printf(“\n\n”);
}
}

Output:
Ensure the number of columns of the first matrix should match the number of rows of
the second matrix.
Input the number of rows and columns of the first matrix: 2 2
Input the number of rows and columns of the second matrix: 2 2
Input the elements of the first matrix:
23
24
Input the elements of the second matrix:
25
37
The multiplication of two input matrices is:
13 31
16 38
Array 297

Q4. C Program to Find Transpose of the Matrix.


Solution
/*************************************************************************
FILE NAME: twoarray3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to find transpose of the matrix
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x[20][20],y[20][20],i,j,k,l;
printf(“Input the number of rows and columns of the matrix:”);
scanf(“%d%d”,&k,&l);
printf(“Input the elements of the matrix:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
scanf(“%d”,&x[i][j]);
}
}
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
y[j][i]=x[i][j];
}
}
printf(“The transpose of the inputted matrix is:\n”);
for(i=0;i<l;i++)
{
for(j=0;j<k;j++)
{
printf(“%d\t”,y[i][j]);
}
printf(“\n”);
}
}

Output:
Input the number of rows and columns of the matrx: 2 3
Input the elements of the matrix:
1 3 4
4 5 6
298 Concepts and Techniques of Programming in C

The transpose of the input matrix is:


2 4
3 5
4 6

TIPS TO REMEMBER
1. The transpose of the matrix is defined as the matrix that is obtained by
interchanging the rows of a matrix to columns. If the matrix is of the order m*n
then transpose of the matrix will be n*m.
2. In matrix multiplication, the number of columns in the first matrix should be
equal to the number of rows in the second matrix. Each row of the first matrix is
multiplied with the columns of the second matrix then added to get the element
of the result.

Q5. C Program to Find the Sum of Diagonal Elements of a Matrix.


Solution
/*************************************************************************
FILE NAME: twoarray4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: C Program to Find the Sum of Diagonal Elements of a
Matrix
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x[20][20],row,col,i,j,sum=0;
printf(“\nInput the number of rows and columns of a matrix: “);
scanf(“%d%d”,&row,&col);
printf(“\nInput elements of the matrix:\n”);
for (i=0;i<row;i++)
{
for (j=0;j<col;j++)
{
scanf(“%d”,&x[i][j]);
}
}
for (i=0;i<row;i++)
{
for (j=0;j<col;j++)
{
if (i == j)
{
Array 299

sum=sum+x[i][j];
}
}
}
printf(“Sum of diagonal of inputted matrix is:%d”,sum);
}

Output:
Input the number of rows and columns of a matrix: 2 2
Input the elements of the matrix:
2 3
2 3
Sum of diagonal of input matrix is: 5
Q6. C Program to Find Determinants of the N*N Matrix.
Solution
/*************************************************************************
FILE NAME: twoarray5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to find determinants of the n*n matrix
*************************************************************************/
#include <stdio.h>
void main(void)
{
int m[3][3],x,y=0,i,j;
printf(“Input the order of the matrix(2*2/3*3):”);
scanf(“%d”,&x);
if (x<2||x>3)
{
printf(“You have inputted invalid value\n”);
}
printf(“Input the elements of the matrix\n”);
for (i=0;i<x;i++)
for (j=0;j<x;j++)
scanf(“%d”,&m[i][j]);
if (x==2)
{
y=(m[0][0]*m[1][1])-(m[0][1]*m[1][0]); /* calculatation of determinant of
the 2 x 2 matrix */
}
else if(x==3)
{
/* calculation of determinant of the 3 x 3 array */
y=(m[0][0]*m[1][1]*m[2][2])-(m[0][0]*m[2][1]*m[1][2])-(m[0][1]*m[1]
[0]*m[2][2])+
300 Concepts and Techniques of Programming in C

(m[0][1]*m[2][0]*m[1][2])+(m[0][2]*m[1][0]*m[2][1]) -(m[0][2]*m[1][1]*m[2]
[0]);
}
printf(“The Determinant of the inputted matrix is:%d”,y);
}

Output:
Input the order of the two-dimensional array (2*2/3*3):2
Input the elements of two-dimensional array
3 4
2 8
The determinant of the input matrix is: 16

11.4 THREE-DIMENSIONAL ARRAYS (3D-ARRAY)


We studied in the previous section that a two-dimensional array is an array of array.
A three-dimensional array is nothing but a collection of two-dimensional arrays. We
can alternatively say that a three-dimensional array is an array of array. The 3-D array
consists of three subscripts, first subscript specifies the number of matrix and second
for row and third for column.

11.4.1 Declaration of Three-Dimensional Arrays

The syntax of three dimensional arrays is


Data_type array_name[table_number][row][column];

This syntax described that the first subscript of the array contains number of tables
and second number of rows and third number of column.
Example:
int a[3][2][2];

EXPLANATION:
Here int specified that it is the data type, a is the name of the array, inside the first
subscript 3 is the number of tables, second 2 is the number of rows, third 2 is the number
of columns. This array contains 12 elements and the number of elements is calculated
by multiplying size inside each subscript. Therefore, size of array a is: 3*2*2=12.

11.4.2 Initialization of Three-Dimensional Array


Assigning values to a three-dimensional array is called initialization of the three-
dimension array.
Array 301

The syntax is:


Data_type array_name[table][row][column]={ {{value1,value2----},{}};
Example 1:
   int a[3][2][2]={
{
{5,10},
{15,20}
},
{
{25,30},
{35,40}
},
{
{45,50},
{55,60}
}
};

EXPLANATION:
This is explained that a is the name of the 3-D array where 3 specifies the number of
array which is a 2*2 array.
Example 2:
int b[3][3][2]={
{
{1,2},
{3,4},
{5,6}
},
{
{7,8},
{9,10},
{11,12},
},
{
{13,14};
{15,16},
{17,18},
}
};

EXPLANATION:
This is explained that b is the 3-D array name where 3 is the number of tables each of
three rows and two columns each.
302 Concepts and Techniques of Programming in C

TIPS TO REMEMBER
2D array is the array of 1D array where 3D array is the array of array of array.

SUMMARY

1. An array is a collection of elements of same data types and size.


2. There are three types of array: a) one-dimensional, b) two-dimensional, c) three-
dimensional.
3. The position of each array elements is called as array index /subscript.
4. The array index starts with the value zero.
5. Without initializing the array, the whole array contains garbage value. So better
when array is declared then initialized them first.

SHORT Questions

1. What is an array?
2. Write the syntax of array declaration?
3. Write the syntax of array initialization?
4. What is a subscript?
5. If we do not initialize the array then the arrays contain what values?
6. If the array size is 10 then the array index start with what?
7. Assume”s” as an integer array with the following initialization values:
int s[3][3]={5,10,15,20,25,30,35,40,45,50};
Write a single c statement to print 35 from the list.
Solution:
#include<stdio.h>
void main()
{
int s[3][3]={5,10,15,20,25,30,35,40,45};
printf(“%d”,s[2][0]);
}
Output:
35

LONG Questions

1. Write a program to insert an element into the array.


2. Write a C program to find the largest element in the array.
Array 303

3. Write a C program to find smallest elements into the array.


4. Write a C program to find the Fibonacci series using array.
5. Write a C program of addition of two matrices.
6. Write a C program of subtraction of two matrices.
7. Write a C program of multiplication of two matrices.
8. Write a C program to find transpose of the matrix.
9. Write a C program to find the determinant of the matrix.
10. Write a C program of sum of diagonal of the matrix.

Objective Questions with answers

1. What will be the output of the program if the array begins at 65472 and each
integer occupies 2 bytes? [internet]
#include<stdio.h>
void main()
{
int a[3][4] = {10,20,30,40,40,30,20,10,70,80,90, 0};
printf(“%u, %u\n”, a+1, &a+1);
}
Output:
65480, 65496
2. What will be the output of the following program?
#include<stdio.h>
void main()
{
int x[5],i=0;
while(i<5)
x[i]=++i;
for(i=0;i<5;i++)
printf(“%d “, x[i]);
}
Output:
garbase value,1,2,3,4
3. What will be the output of the program?
#include<stdio.h>
void main()
{
int a[2]={100};
printf(“%d\n”,0[a]);
}
Output:
100
304 Concepts and Techniques of Programming in C

4. What will be the output if the array begins at address 65486?


#include<stdio.h>
void main()
{
int arr[] = {10,15,20,25,30};
printf(“%u %u\n”, arr,&arr);
}
Output:
65486, 65486
5. What will be the output of the program?
#include<stdio.h>
void main()
{
float arr[]={12.0,2.0,4.0,6.0};
printf(“%d\n”, sizeof(arr)/sizeof(arr[0]));
}
Output:
4
6. What will be the output of the program if the array begins 1400 in memory?
#include<stdio.h>
void main()
{
int arr[]={20,30,40,10,60};
printf(“%u, %u, %u\n”,arr,&arr[0],&arr);
}
Output:
1400,1400,1400
Output:
A

Multiple-Choice questions

1. Choose the correct syntax of sending a 3-dimensional array as an argument


to function? (Assuming declaration int x[2][3][2];)
(a) func(x); (b) func(&x);
(c) func(*x); (d) func(**x);
[Answer: a]
2. Applications of multidimensional array are_______________
(a) Matrix-Multiplication (b) Minimum Spanning Tree
(c) Finding connectivity between nodes (d) All of the mentioned
[Answer: d]
Array 305

3. Find out the correct one of initialize an array of 3 integers?


(a) int[] a = {78, 9, 54};
(b) int[] a;
a = new int[3];
a[1] = 78;
a[2] = 9;
a[3] = 54;
(c) int[] a;
a = new int{78, 9, 54};
(d) int[] a;
a = new int[3]{78, 9, 54};
[Answer: a, d]
4. The memory address of the first element of an array is called _____________
(a) floor address (b) foundation address
(c) first address (d) base address
[Answer: d]
5. Two-dimensional arrays are also called __________
(a) tables arrays (b) matrix arrays
(c) both of above (d) none of above
[Answer: c]
12
String

12.1 INTRODUCTION
The process of storing set of integer values in an integer array. Similarly, set of characters
can also be stored in a character array. Therefore, character arrays are called strings.
Thus, the definition of a string is, it a finite sequence of characters that is treated as a
single data item.

12.1.1 Declaration of String Variable

The syntax of string variable declaration is


char string_name[size];

Example:
char x[20];

12.1.2 Initialization of String


char x[5]=”BBSR”;
char x[5]={‘B’,’B’,’S’,’R’,’\0’};

If the declaration of string size is large but less numbers are initialized then rest of
the memory locations are assigned NULL values. Example
char x[10]={‘C’,’U’,’T’,’T’,’A,’C’,’K’,’\0’};

The memory representation is

C U T T A C K \0 \0 \0

Fig. 12.1 Initialization of string


String 307

/*C Program to Print your Name*/


#include <stdio.h>
void main()
{
char s[] = “DHABAL PRASAD SETHI”;
printf(“%s\n”,s);
}

Output:
DHABAL PRASAD SETHI
Q1. /*Program to Display Printing of a String named BBSR*/
#include<stdio.h>
void main(void)
{
char x[]=”BBSR”;
int j=0;
while(j<=4)
{
printf(“%c”,x[j]);
j++;
}
}

Output:
BBSR
Or
#include<stdio.h>
void main(void)
{
char x[]=”BBSR”;
int j=0;
while(x[j]!=’\0’)
{
printf(“%c”,x[j]);
j++;
}
}

Output:
BBSR
Or
#include<stdio.h>
void main(void)
{
308 Concepts and Techniques of Programming in C

char x[]=”BBSR”;
char *p;
p=x;
while(*p!=’\0’)
{
printf(“%c”,*p);
p++;
}
}

Output:
BBSR

12.2 READING A STRING


To read the string we can use the input function scanf() with the format specifier, e.g.,
%s.
Example:
char x[20];
scanf(“%s”,x);

TIPS TO REMEMBER
To read the character array do not use address operator (&) with the variable of scanf
function. The example is shown in above.

12.2.1 getchar() Function


The getchar() function is used to read a single character from the keyboard.
Example:
char x;
x=getchar();

12.2.2 gets() Function


The gets() function is used to read a string of text containing white space.
Example:
#include<stdio.h>
void main(void)
{
char x[20];
printf(“Input the string:”);
gets(x);
printf(“%s”,x);
}
String 309

Output:
Input the string: DHABAL
DHABAL

12.3 WRITING A STRING/DISPLAYING A STRING


In printf function the conversion specification %s is used for printing the group of
characters on the computer screen. So %s is used to display array of character that is
terminated by’\0’.
Example:
#include<stdio.h>
void main(void)
{
char x[7]=”DHABAL”;
printf(“%s”,x);
}

Output:
DHABAL

TIPS TO REMEMBER
If the length of the string is six then declare the array whose size is seven because the
string should end with’\0’ e.g. ‘\0’ occupy one extra memory location in addition
to string size.

12.3.1 putchar() Function


The putchar() function is used to display a single character.
Example:
char x=’A’;
putchar(x);
Or
printf(“%c”,x);

12.3.2 puts() Function


The puts() function is used to display a string.
Example:
puts(x);
310 Concepts and Techniques of Programming in C

Q2. /* Program to Input/Output Strings using printf() and scanf() */


#include <stdio.h>
void main(void)
{
char x[20];
printf(“Input your name:”);
scanf(“%s”,x);
printf(“My name is: %s”,x);
}

Output:
Input your name: DHABAL
My name is: DHABAL
Q3. /* Program to Input/Output Strings using gets() and puts() */
#include <stdio.h>
void main(void)
{
char x[20];
puts(“Input your name: “);
gets(x);
puts(“My name is: “);
puts(x);
}

Output:
Input your name: JUGAL
My name is: JUGAL

12.4 STRING HANDLING LIBRARY FUNCTIONS


12.4.1 strlen() Function
The strlen() is a library function which is used to count the number of characters
present in a string or measure the length of the string.
Q4. /*C Program to Find Length of a String using strlen() Function*/
#include<stdio.h>
#include<string.h>
void main(void)
{
char x[30];
int y;
printf(“Input the string:”);
scanf(“%s”, x);
y=strlen(x);
printf(“The number of character in the inputted string is:%d\n”, y);
}
String 311

Output:
Input the string: DHABAL
The number of characters in the input string is 6

TIPS TO REMEMBER
If the character array/string size is 10 then you have to initialize the 9 character
because ‘\0’ (null character) occupies one memory location.

12.4.2 strcpy() Function


The strcpy() is a library function which is used to copy from one string into another
string. If str2 is the source sting and str1 is the destination string. If str2=”DHABAL”
then strcpy function copies “DHABAL” into str1. Let us see the example.
Q5. /*C program to Copy Source String to Destination String using strcpy() Function*/
#include<stdio.h>
#include<string.h>
void main(void)
{
char x[30],y[30];
printf(“Input the source string:”);
scanf(“%s”, y);
strcpy(x, y);
printf(“The destination string is:%s”, x);
}

Output:
Input the source string: NUTAN
The destination string is: NUTAN

EXPLANATION:
Here y is the source string and x is the destination string.

12.4.3 strcmp() Function


The strcmp() is a library function which is used to compare the two strings. The strings
are compared character by character till the end of the string or there is a mismatch.
If the two characters are matched, the strcmp() function returns a value 0. If not, it
returns the numeric difference between the ASCII values of the first non-matching pair
of characters.
Q6. /*C Program to Compare the Two Strings using strcmp() Function*/
#include<stdio.h>
#include<string.h>
312 Concepts and Techniques of Programming in C

void main(void)
{
char x[30],y[30];
printf(“Input the first name:”);
scanf(“%s”,x);
printf(“Input the second name:”);
scanf(“%s”,y);
if(strcmp(x,y)==0)
printf(“The two names are same”);
else
printf(“The two names are not same”);
}

Output:
Input the first name: DHABAL
Input the second name: DHABAL
The two names are same.
Q7. /* Program to Compare Two Strings without using strcmp() */
#include<stdio.h>
void main(void)
{
char x[30],y[30];
int j,c=0;
printf(“Input the first name:”);
gets(x);
printf(“Input the second name:”);
gets(y);
for(j=0;x[j]!=’\0’;j++)
{
if(x[j]==y[j])
c=1;
else
c=0;
}
if(c==1)
printf(“Both names are same.”);
else
printf(“Both names are not same.”);
}

Output:
Input the first name: DHABAL
Input the second name: DHABAL
Both names are same.
Q8. /* Program to Find whether a String is Palindrome or Not */
#include <stdio.h>
#include <string.h>
String 313

void main(void)
{
char x[20],y[20];
int z;
printf(“Input the string: “);
gets(x);
strcpy(y,x);
strrev(y);
z=strcmp(x,y);
if(z==0)
printf(“The inputted string is a palindrome string”);
else
printf(“The inputted string is not a palindrome string”);
}

Output:
1st run
Input the string: DHABAL
The input string is not a palindrome
2nd run
Input the string: EEE
The input string is a palindrome string

12.4.4 strcat() Function


The strcat() is a library function which is used for concatenation/appending one
sting with another string. The function concatenate source string with target string by
overwriting the null character (‘\0’). Example: If the first string is ”LORD” and second
string is “JAGATNATH”, then after concatenation the function the first string becomes
”LORDJAGATNATH”.
Q9. /*C Program to Add Two Strings (e.g., First Name and Last Name) using strcat()
Function*/
#include<stdio.h>
#include<string.h>
void main(void)
{
char x[30],y[30];
printf(“Input the first name:”);
scanf(“%s”,x);
printf(“Input the last name:”);
scanf(“%s”,y);
strcat(x,y);
printf(“The first name becomes:%s”,x);
}
314 Concepts and Techniques of Programming in C

Output:
Input the first name: DHABAL
Input the last name: SETHI
The first name becomes: DHABALSETHI
Q10. /* Program to Concatenate Two Strings without using strcat() */
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main(void)
{
char x[30],y[30];
int j,c=0,t;
printf(“Input the first name:”);
gets(x);
printf(“Input the last name:”);
gets(y);
for(j=0;x[j]!=’\0’;j++)
c++;
t=c;
for(j=0;y[j]!=’\0’;j++)
{
x[t]=y[j];
t++;
}
x[t] = ‘\0’;
printf(“After concatenation the first name is:”);
puts(x);
}

Output:
Input the first name: DHABAL
Input the last name: SETHI
After concatenation the first name is: DHABALSETHI

12.4.5 strrev() Function


This function is used to reverse the string.
Q11. /*Program to Reverse a String using strrev() */
#include <stdio.h>
#include <string.h>
void main(void)
{
char x[20];
printf(“Input the string: “);
gets(x);
strrev(x);
String 315

printf(“Reverse of inputted string is: %s”,x);


}

Output:
Input the string: dhabal
Reverse of input string is: labahd

TIPS TO REMEMBER
If the scanf() function reads the string as input then do not give “&” (address
operator)in that address variable.

Q12. /*Program to Reverse a String without using strrev() */


#include<stdio.h>
#include<string.h>
void main(void)
{
char x[30],revx[30];
int i=0,j=0;
printf(“Input the string to be reversed:”);
scanf(“%s”,x);
for(i=strlen(x)-1;i>=0;i--)
{
revx[j]=x[i];
j++;
}
revx[j]=’\0’;
printf(“The reversed string is:%s”,revx);
}

Output:
Input the string to be reversed: UTKAL
The reversed string is: LAKTU

TIPS TO REMEMBER
The last character is always’\0’ and that ‘\0’is called null character.
The ASCII value of ‘\0’ is 0.
The ASCII value of ‘0’is 48
The printf() function does not print the ‘\0’
In c, the end of a string is marked by a null character.
The ‘\0’ is not two characters but it is actually one character. The\ indicates what
follows, it is something special.
The elements of the character array are stored in contiguous memory locations.
The ‘\0’ is not a string, but a collection of characters.
The %s used in printf() function is a format specifier for printing a string.
316 Concepts and Techniques of Programming in C

Q13. /* Program to Find Length of a String without using strlen() */


#include <stdio.h>
void main(void)
{
char x[20];
int j=0;
printf(“Input the string:”);
gets(x);
while(x[j]!=’\0’)
j++;
printf(“Length of string is: %d”,j);
}

Output:
Input the string: DHABAL
Length of string is: 6
Q14. /* Program to Find whether a String is Palindrome or Not without using String
Functions */
#include <stdio.h>
#include <string.h>
void main(void)
{
char x[20];
int i,j,l=0,c=0;
printf(“Input the string to check palindrome:”);
gets(x);
for (i=0;x[i]!=’\0’;i++)
l++;
i=0;
j=l-1;
while(i<l)
{
if(x[i]!=x[j])
{
c=1;
break;
}
i++;
j--;
}
if(c==0)
printf(“The string is a palindrome”);
else
printf(“The string is not palindrome”);
}
String 317

Output:
Input the string to check palindrome: AAA
The string is a palindrome
Q15. /*C program to Find the Number of Vowels, Consonants, Digits and White
Spaces Character in a Sentence*/
#include<stdio.h>
void main(void)
{
char x[150];
int j,count1,count2,count3,count4;
count1=count2=count3=count4=0;
printf(“Input an English sentence:”);
gets(x);
for(j=0;x[j]!=’\0’;++j)
{
if(x[j]==’a’||x[j]==’e’||x[j]==’i’||x[j]==’o’||x[j]==’u’||x[j]==’A’||x[j]=
=’E’||x[j]==’I’||x[j]==’O’||x[j]==’U’)
count1++;
else if((x[j]>=’a’&&x[j]<=’z’)||(x[j]>=’A’&&x[j]<=’Z’))
count2++;
else if(x[j]>=’0’&&count2<=’9’)
count3++;
else if (x[j]==’ ‘)
count4++;
}
printf(“Vowels in the sentence:%d\n”,count1);
printf(“Consonants in the sentence:%d\n”,count2);
printf(“Digits in the sentence:%d\n”,count3);
printf(“White spaces in the sentence:%d\n”,count4);
}

Output:
Input an English sentence: I AM DHABAL
Vowels in the sentence: 4
Consonants in the sentence: 5
Digits in the sentence: 0
White spaces in the sentence: 2

SUMMARY

1. String is the sequence of characters and is treated as a single data item.


2. %s is the conversion specification character used to input and display the string.
3. The strlen() function is used to count the number of characters present in that
string.
318 Concepts and Techniques of Programming in C

4. The strcpy() function is used to copy one string into another.


5. The strcmp() function is used to compare the two strings.
6. The strcat() function is used to concatenate one string with another string.
7. The strrev() function is used to reverse the input string.
8. The last character of string is the ‘\0’.

SHORT QUESTIONS

1. What is string? Explain with suitable examples.


2. Which conversion specification character is used to read the string?
3. Write the difference between getchar() and gets() function.
4. Write the difference between putchar() and puts() function.
5. What are the string handling libraries functions?
6. What is the function of strcmp()?

LONG QUESTIONS

1. Write a C program to check whether a given string is a palindrome or not.


2. Write a program to check whether a given sentence is a palindrome sentence or
not. Do not use any standard string handling library functions.
3. Write a C program to count the number of vowels in a given string.

OBJECTIVE Questions WITH Answers

1. What will be the output?


#include<stdio.h>
#include<string.h>
void main()
{
char x[20]=”LORD”,y[20]=”JAGATNATH”;
printf(“%s\n”,strcpy(y,strcat(x,y)));
}
Output:
LORDJAGATNATH
2. What will be the output?
#include<stdio.h>
void main()
{
char x[]=”%d\n”;
x[1]=’c’;
printf(x,65);
}
String 319

Output:
A
3. What will be the output?
#include<stdio.h>
#include<string.h>
void main(void)
{
printf(“%d\n”,strlen(“123”));
}
Output:
3
4. What will be the output?
#include<stdio.h>
void main(void)
{
printf(2+”I LOVE MY COUNTRY”);
}
Output:
LOVE MY COUNTRY
5. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
char x[]=”INDIA\0\ODISHA\0”;
printf(“%s\n”,x);
}
Output:
INDIA
6. What will be the output?
#include<stdio.h>
void x();
void main()
{
printf(“Input the character:”);
x();
printf(“\n”);
}
void x()
{
char d;
if((d=getchar())!=’\n’)
x();
printf(“%c”,d);
}
320 Concepts and Techniques of Programming in C

Output:
Input the character: a
a
7. What will be the output?
#include<stdio.h>
void main()
{
printf(“INDIA”,”ODISHA\n”);
}
Output:
INDIA
8. What will be the output?
#include<stdio.h>
void main()
{
char x[8]=”INDIAODISHA”;
printf(“%s\n”,x);
}
Output:
Compilation error
9. What will be the output?
#include<stdio.h>
void main()
{
char *x[]={“DHABAL”,”JUGAL”,”GUDU”,”NUTAN”,”RAKESH”};
int i;
char *t;
t=x[3];
x[3]=x[4];
x[4]=t;
for(i=0;i<=4;i++)
printf(“%s,”,x[i]);
}
Output:
DHABAL,JUGAL,GUDU,RAKESH,NUTAN,
10. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
char x[]=”ODISHA\0\INDIA\0”;
printf(“%d\n”,strlen(x));
}
String 321

Output:
6
11. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
static char x[]=”sethi”;
static char y[20];
static char z[]=”dhabal”;
int i;
i=strcmp(strcat(z,strcpy(y,x)),”dhabalsethi”);
printf(“%d\n”, i);
}
Output:
1
12. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
static char x[]=”INDIA!”;
printf(“%d\n”,*(x+strlen(x)));
}
Output:
0
13. What will be the output?
#include<stdio.h>
void main(void)
{
static char x[25]=”MY INDIA”;
int i=0;
char d;
d=x[++i];
printf(“%c”,d);
d=x[i++];
printf(“%c”,d);
d=i++[x];
printf(“%c”,d);
d=++i[x];
printf(“%c”,d);
}
Output:
YY J
322 Concepts and Techniques of Programming in C

14. What will be the output in 32-bit platform?


#include<stdio.h>
void main()
{
printf(“%d,%d,%d”,sizeof(4.0f),sizeof(‘4’),sizeof(4.0));
}
Output:
4,1,8
15. What will be the output?
#include<stdio.h>
void main()
{
char x[]=”\0”;
if(printf(“%s”,x))
printf(“The string is empty”);
else
printf(“The string is not empty”);
}
Output:
The string is not empty
16. If char=1 and float=4 bytes size, what will be the output?
#include<stdio.h>
void main()
{
char x=’A’;
printf(“%d,%d,%d”,sizeof(x),sizeof(‘A’),sizeof(3.14f));
}
Output:
1 1 4
17. If the size of pointer is 32 bits, what will be the output?
#include<stdio.h>
void main()
{
char x[]=”c programming”;
char *y=”c++ programming”;
printf(“%d,%d\n”,sizeof(x),sizeof(y));
printf(“%d,%d”,sizeof(*x),sizeof(*y));
}
Output:
14,4
1,1
String 323

18. What will be the output?


#include<stdio.h>
void main(void)
{
char x[]=”MY INDIA”;
char y[20];
char *t,*s;
s=x;
t=y;
while(*t=*s)
*t++=*s++;
printf(“%s\n”,y);
}
Output:
MY INDIA
19. What will be the output?
#include<stdio.h>
void main(void)
{
char x[]=”INDIA\0ODISHA\0”;
printf(“%d\n”,sizeof(x));
}
Output:
14
20. What will be the output?
#include<stdio.h>
void main()
{
char x[25] = “INDIAODISHA”;
printf(“%s\n”,& x+2);
}
Output:
Compilation error
21. What will be the output?
#include<stdio.h>
void main()
{
char x=”ODISHA”;
printf(“%s”,x);
}
Output:
Compilation error
324 Concepts and Techniques of Programming in C

22. What will be the output?


#include<stdio.h>
void main()
{
char x[]=”Bhubaneswar”;
x[0]=’C’;
printf(“%s,”,x);
x=”Cuttack”;
printf(“%s”,x+1);
}
Output:
Compilation error
23. What will be the output?
#include<stdio.h>
void main(void)
{
printf(12+”BHUBANESWAR-ODISHA”);
}
Output:
ODISHA
24. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
char x[80];
int i;
printf(“Input the string:”);
gets(x);
printf(“The reversed string is:”);
for(i=strlen(x)-1; i >=0; i--)
putchar(x[i]);
}
Output:
Input the string: dhabal
labahd
13
Pointer

13.1 INTRODUCTION
In chapter 4 we studied that a variable is a memory location which is used to store
a value. To access that memory address of a variable we can use the & (ampersand)
operator.
Let’s see the programming example
#include <stdio.h>
void main(void)
{
int x;
printf(“Address of variable x is:%u”, &x);
}

Output:
Address of variable x: 1000

EXPLANaTION:
From the above discussion we learned about the memory address. Let’s see the concept
of a pointer. The definition: it is a derived data type which is built from one of the
fundamental data types, e.g., int, char, float, double. It holds memory addresses as their
values. It can be used to access and manipulate data stored in the computer memory.
Therefore, pointer is the most powerful and exciting features of C language.

The main advantages of using pointers are:


1. The function cannot return more than one value to the calling function at a time.
But pointers can return more than one values in function to calling function.
2. In arrays, we can decide the size of the array at runtime by allocating the
necessary space.
3. It supports dynamic memory allocation.
326 Concepts and Techniques of Programming in C

The disadvantage of pointers is:


1. If sufficient memory is not available during runtime for the storage of pointers,
the program may crash (least possible).

13.1.1 What is Pointer Variable?


A pointer variable is a variable which holds an address of another variable stored in
computer memory.

13.1.2 Pointer Variable Declaration


The syntax of pointer variable declaration is
datatype *variable_name;

EXPLANATION:
In the above declaration data type determines what type of data value of the pointer
variable will hold by using fundamental data type (e.g., int, char, float, double) and
then *in front of variable_name identified that variable_name is a pointer variable.

TIPS TO REMEMBER
The pointer variable declaration works when it gives the information/report to
the C compiler about three basic things about pointer variable. First thing is that,
asterisk (*) placed in front of variable identify that it is a pointer variable. Second
thing pointer variable requires is a memory location where it will contain address
of another variable and the third thing pointer variable should point to a variable
of same data type.

Let’s see the examples of pointer variable declarations with their respective data
types.

Examples of Pointer Variable Declaration by using Fundamental Data Types


1. int *x;
2. float *x;
3. char *x;
4. double *x;

EXPLANATION OF EXAMPLE 1 TO 4
1. int *x;
Pointer 327

This statement declares that the variable x is a pointer variable that points to an
integer type value, e.g., pointer variable x may hold the value which may be a
garbage value because in that above syntax initialization of values is not done or
if initialized it holds the initialized value.
2. float *x;
This statement declares that the variable x is a pointer variable that points to a
float type value. It may hold garbage value or initialized value.
3. char *x;
This statement declares that the variable x is a pointer variable that points to char
type value. It may hold garbage value or initialized value.
4. double *x;
This statement declares that the variable x is a pointer variable that points to
double type value. It may hold garbage value or initialized value.

TIPS TO REMEMBER
Pointer is used to access and input data which is stored in computer memory.

Q. When we declare the pointer variable, e.g., int *x; or pointer variable x with
other data types (char, float, double), then what value x will contain?
The answer is that when we declare the pointer variable x .Then it will point to the
unknown locations because it searches some data values to store. These data values
are called garbage values and are automatically generated by the system.

x pointer variable

? points to unknown memory locations, e.g., it


may contain garbage value

1000 address of pointer variable x

Fig. 13.1 Diagrammatical representation of declaration of pointer variable

TIPS TO REMEMBER
int *x;
In the above declaration x is a pointer variable but *x is not called a pointer
variable. But *in front of x identifies that x is a pointer variable.
328 Concepts and Techniques of Programming in C

TIPS TO REMEMBER
A pointer is a variable and it contains only address, e.g., it contains address of
another variable.
There are two important operators used in pointer concept. They are:
(a) * and (b) &
(a) * is called as indirection operator or value at address operator or dereferencing
operator.
(b) & is called address operator and is used to find the address of a variable.

13.2 DIFFERENT WAYS OF POINTER VARIABLE DECLARATION

1. int *x; /*preferable one*/


2. int * x;
3. int* x;

All three pointer variable declarations are correct declarations but the first one
marked as bold is preferred by programmers to the other two.

13.3 POINTER VARIABLE INITIALIZATION


Initialization of pointer variable means assigning the address of a variable to a pointer
variable. We know that without initialization the pointer variable takes the value
garbage from previous diagram. Therefore, it is important to initialize the pointer
variable whenever declared.

The syntax of pointer variable initialization is:


int x;
int *y; /*pointer variable y declaration*/
y=&x; /*pointer variable y initialization*/

SOME WRONG POINTER VARIABLE INITIALIZATIONS


(a) When int pointer variable is pointing to float type values.
#include<stdio.h>
void main()
{
float x=10.0;
int *p;
Pointer 329

p=&x;
printf(“address of variable x stored in p is:%u”,p);
}
Output:
Compilation error
(b) When int pointer variable is pointing to char type values.
#include<stdio.h>
void main()
{
char x=’a’;
int *p;
p=&x;
printf(“address of variable x stored in p is:%u”,p);
}
Output:
Compilation error
(c) When int pointer variable is pointing to double type value.
#include<stdio.h>
void main()
{
double x=20.0;
int *p;
p=&x;
printf(“address of variable x stored in p is:%u”,p);
}
Output:
Compilation error

TIPS TO REMEMBER
The pointer variable of data type int can point to int data type values only but not
to float, double, char data type value.

Q1. Example of Correct Pointer Variable Initialization which Hold an Address of


another Variable of Same Data Type.

Solution:
/*************************************************************************
FILE NAME: pointer1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of correct pointer variable initialization
which hold an address of another variable of same data type.
*************************************************************************/
330 Concepts and Techniques of Programming in C

#include <stdio.h>
void main (void)
{
int x=10; /* variable declaration */
int *y; /* pointer variable declaration */
y= &x; /* address of x is stored in pointer variable p*/
printf(“Address of variable x is: %x\n”,&x ); /*printing address of variable
x by using address operator*/
printf(“Address stored in pointer variable y is:%x\n”,y); /*printing
address of variable x by using pointer variable */
}

Output:
Address of variable x is: 2226
Address stored in pointer variable y is: 2226

x=10

1000 ‐‐‐‐‐ address of variable x

y=1000

2000 ‐‐‐‐‐‐ address of pointer variable p

Fig. 13.2 Diagrammatical representation of pointer variable initialization

In the above diagram let’s see how the pointer variable y holds the address 1000 of
another variable x.

13.4 NULL POINTER


A pointer that is assigned NULL is called a null pointer. If the pointer variable is not
assigned any value then it is always assigned a NULL to that pointer variable. The
NULL pointer is a constant with a value zero is defined in libraries.
Q2. Example of Null Pointer Variable.
Solution:
/*************************************************************************
FILE NAME: pointer2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of NULL pointer variable.
*************************************************************************/
#include<stdio.h>
void main(void)
Pointer 331

{
int *y=NULL;
printf(“value of pointer variable y is:%u”,y);
}

Output:
Value of pointer variable y is:0

13.5 ACCESSING A VARIABLE BY USING THE POINTER CONCEPT


To access the variable’s value through pointer concept then the programmer should use
the operator asterisk (*).The asterisk is usually known as indirection operator. Another
name of the indirection operator is dereferencing operator.
Q3. Example of Dereferencing Pointer.
Solution:
/*************************************************************************
FILE NAME: pointer3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of dereferencing pointer.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=5;
int *y;
y=&x;
printf(“value of x is:%d\n”, x);
printf(“value of x is:%d\n”,*&x);
printf(“value of x is:%d\n”,*(&x));
printf(“value of x is:%d”,*y);
}

Output:
Value of x is: 5
Value of x is: 5
Value of x is: 5
Value of x is: 5

EXPLANATION:
From the above four printf statements in the program that prints the value of x in
different ways. First is printing the value of variable x then second, third, fourth printf
statements are the same for printing the value of x through pointer concept.
332 Concepts and Techniques of Programming in C

13.6 GENERIC POINTER


The alternative name of generic pointer is called a void pointer. The generic pointer
is a pointer variable that can point to any data type. When we declare it, its syntax is
same as general pointer variable instead of fundamental data type we can use void.
Q4. Example of Generic Pointer Variable.
Solution:
/*************************************************************************
FILE NAME: pointer2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of Generic pointer variable.
*************************************************************************/
#include<stdio.h>
void main()
{
int x=4;
char c=’D’;
float m=10.7;
void *y;
y=&x;
printf(“%d\n”,*(int*)y);
y=&c;
printf(“%c\n”,*(char*)y);
y=&m;
printf(“%f”,*(float*)y);
}

Output:
4
D
10.7000000

Explanation:
In the above program the first printf function prints the output 4 and in the printf
statement *(int *)y is used because y is void type and our objective is to print the value
of x which is int type therefore we type caste void data type to int data type by the
syntax (int *) and other printf statements are followed by the first syntax.

13.7 POINTER TO POINTER


In pointer-to-pointer declaration, two pointer variables are declared where one holds
single asterisk and second holds double asterisk (**).Pointer-to-pointer means one
pointer variable (contains double asterisk) holds the address of another pointer variable
Pointer 333

(contains one asterisk). Again that another pointer variable (containing one asterisk)
holds the address of a variable. The whole process is called multiple indirections.

The syntax of pointer-to-pointer variable declaration is


int **x;

Double asterisks are used to declare the pointer-to-pointer variable. The above
declaration tells that x is a pointer to a pointer of int data type.

TIPS TO REMEMBER
int **x;
In the above line x is not a pointer to an integer type but a pointer to an integer
pointer.

We can access the variable’s value indirectly through the concept pointer to pointer,
e.g., using the indirection operator (*) two times. Let’s see the example.
Q5. Example of Pointer to Pointer.
Solution:
/*************************************************************************
FILE NAME: pointer4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of dereferencing pointer.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=20,*y,**z;
y=&x;
z=&y;
printf(“value of pointer variable z is:%d”,**z);
}

Output:
Value of pointer variable z is: 20

Explanation:
From the above program we saw that z is displaying the value of x by using the
operator** called pointer to pointer, e.g., z holds the value of y which again holds the
value of x.
334 Concepts and Techniques of Programming in C

z=2000

Address=3000

y=1000

Address=2000

x=20

Address=1000
Fig. 13.3 Pointer-to-pointer mechanism

Here in the figure pointer variable z holds the address of another pointer variable y
and again that pointer variable y holds the address of variable x.
Q6. /*Example of Size of Character Pointer Variable*/
#include<stdio.h>
void main(void)
{
char *x;
printf(“Size of character pointer variable is:%d”,sizeof(x));
}

Output:
Size of character pointer variable is:4
Q7. /*Example of Size of Indirection Character Pointer Variable*/
#include<stdio.h>
void main(void)
{
char *x;
printf(“Size of indirection character pointer variable is:%d”,sizeof(*x));
}

Output:
Size of indirection character pointer variable is:1
Q8. /*Example of Size of Integer Pointer Variable*/
#include<stdio.h>
void main(void)
{
Pointer 335

int *x;
printf(“Size of character pointer variable is:%d”,sizeof(x));
}

Output:
Size of integer pointer variable is: 4
Q9. /*Example of Size of Indirection Integer Pointer Variable*/
#include<stdio.h>
void main(void)
{
int *x;
printf(“Size of indirection integer pointer variable is:%d”,sizeof(*x));
}

Output:
Size of indirection integer pointer variable is: 2
Q10. /*Example of Size of Floating Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
float *x;
printf(“Size of floating type pointer variable is:%d”,sizeof(x));
}

Output:
Size of floating type pointer variable is: 4
Q11. /*Example of Size of Indirection Floating Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
float *x;
printf(“Size of indirection float type pointer variable is:%d”,sizeof(*x));
}

Output:
Size of indirection float type pointer variable is: 4
Q12. /*Example of Size of Double Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
double *x;
printf(“Size of double type pointer variable is:%d”,sizeof(x));
}
336 Concepts and Techniques of Programming in C

Output:
Size of double type pointer variable is: 4
Q13. /*Example of Size of Indirection Double Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
double *x;
printf(“Size of double type indirection pointer variable is:%d”,sizeof(*x));
}

Output:
Size of double type indirection pointer variable is: 8

TIPS TO REMEMBER
In the above program we find that the size of pointer variable of types, e.g., int,
char, float, double type is 4. This program tested in 32-bit compiler and editor
Turbo C 4.5. If you run the above program in 16-bit compiler and Turbo C then
its output will be 2. So it is compiler dependent. But if we measure the size of
fundamental data types and indirection pointer variable, e.g., int, char, float,
double then its size is different. Generally, size of fundamental data types are: int
is 2,char=1,float=4 and double=8.

Q14. C Program of Addition of Two Integer Numbers using Pointer Concepts.


Solution:
/*************************************************************************
FILE NAME: pointer14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: c program of addition of two integer numbers using
pointer concept.
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x,y,*a,*b,c;
printf(“Input two integer numbers :”);
scanf(“%d%d”,&x,&y);
a=&x;
b=&y;
c=*a +*b;
printf(“Sum of inputted two integer numbers is: %d\n”,c);
}
Pointer 337

Output:
Input the two integer numbers: 2 3
Sum of input two integer numbers is: 5

Explanation:
Here in the above program pointer variable a and b hold the address of input variable
x and y. Then using dereferencing operator add these pointer variables and the result
is stored in another variable c and last prints that values.
Q15. Swap Two Integer Numbers using Pointer Concept.
Solution:
/*************************************************************************
FILE NAME: pointer15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: swap two integer numbers using pointer concept.
**************************************************************************
*******/
#include <stdio.h>
void main(void)
{
int x,y,*m,*n,t;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“Before Swapping the inputted values are:\nx:%d\ny=%d\n”,x,y);
m=&x;
n=&y;
t=*m;
*m=*n;
*n=t;
printf(“After Swapping the inputted values are:\nx:%d\ny:%d\n”,x,y);
}

Output:
Input the two integer numbers: 3 4
Before swapping the input values are:
x:3
y:4
After swapping the input values are:
x:4
y:3

13.8 POINTER AS FUNCTION ARGUMENTS


In the previous we studied call by reference which is called pointer function arguments.
When address of a variable is passed to a user defined function, the parameters
338 Concepts and Techniques of Programming in C

receiving the addresses should be pointers. The process of passing the address of a
variable from the calling function to called function is called call by reference. In call by
reference the values of variable used in function call are changed. The example shown
below is passing by reference.
Q16. Examples of Pointer as Function Arguments.
Solution:
/*************************************************************************
FILE NAME: pointer16.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: examples of pointer as function arguments.
*************************************************************************/
#include<stdio.h>
void num_update(int *m,int *n); /*function declaration*/
void main(void)
{
int x,y;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
num_update(&x,&y); /*calling function*/
printf(“After updating the two inputted numbers are:%d %d”,x,y);
}
void num_update(int *m,int *n)
{
*m=*m*10;
*n=*n*5;
}

Output:
Input the two integer numbers: 10 20
After updating the two input numbers are: 100 100
See the program of swapping the two integer numbers using call by reference in the
chapter function is another examples of pointer as function arguments.

TIPS TO REMEMBER
The parameter used in user-defined functions/function header is declared as
pointers.
The dereferencing pointers are used in body section of user-defined function.
When the function is called from calling function, the addresses of parameter are
passed in function call.
Pointer 339

13.9 ADDRESS (POINTER) ARITHMETIC


Pointer arithmetic means the arithmetic operations done on pointer variable, e.g.,
addition, subtraction, multiplication or division. But there are certain rules of pointer
arithmetic.

Some valid pointer arithmetic operations are:


1. Addition of integer numbers with pointer variable
2. Subtraction of integer numbers from pointer variable
3. Subtract one pointer variable from other pointer variable
4. Comparison of pointer variable using relational operator.

The invalid pointer arithmetic operations are:


1. Addition of one pointer variable with another pointer variable
2. Division of one pointer variable with another pointer variable
3. Multiplication of one pointer variable with another pointer variable

Pointer arithmetic is different from general arithmetic. In pointer arithmetic all the
operations are done on the base address of the corresponding data type.
Suppose p is an integer data type which holds the address 100 then if we write p++
;or p=p+1; then it will display the value 102 instead of 101. Because its corresponding
data type size is 2bytes when one increment is done then the result becomes 100+2=102 .
Q17. C Program of Addition of Two Dereferencing Pointer Variable.
Solution:
/*************************************************************************
FILE NAME: pointer17.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: c program of addition of two dereferencing pointer
variable.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=10,y=20,z;
int *p1,*p2;
p1=&x;
p2=&y;
z=*p1+*p2;
printf(“%d”,z);
}
340 Concepts and Techniques of Programming in C

Output:
30

TIPS TO REMEMBER
In pointer concept the dereferencing pointer variable addition, subtraction,
multiplication and division is possible but except subtraction of one pointer variable
from other pointer variable others pointer operation, e.g., addition, division,
multiplication is not possible.

Valid pointer arithmetic programming examples are given below.


Q18. /*C Program of Subtraction of Two Pointer Variable */
#include<stdio.h>
void main(void)
{
int x=10,y=20,z;
int *y1,*y2;
y1=&x;
y2=&y;
z=y1-y2;
printf(“%d”,z);
}

Output:
1

Explanation:
Suppose the pointer variable y1 holding address of x is 1000 and another pointer
variable y2 holding the address of variable y is 999 and after difference the variable z
holds the value 1.
Q19. /*C Program of Add an Integer Number with Pointer Variable*/
#include<stdio.h>
void main(void)
{
int x=10,y;
int *p1;
p1=&x;
p1=p1+4;
printf(“%d”,p1);
}

Output:
8680
Pointer 341

EXPLANATION:
Because if the pointer variable p1 will hold the address 8672 then with the addition of
integer number 4 it will have 8680, e.g., 8672+4*size of int data type=8672+4*2=8680.
Q20. /*C Program of Subtraction of a Integer Number from Pointer Variable*/
#include<stdio.h>
void main(void)
{
int x=10,y;
int *p1;
p1=&x;
p1=p1-4;
printf(“%d”,p1);
}

Output:
8664

EXPLANATION:
Because if pointer variable p1 holds the address 8672 then on subtracting the number
4 it will have 8664.The formula is base address-integer number*size of data type,
e.g., 8672-4*2=8664.

13.10 POINTER AND ONE-DIMENSIONAL ARRAY


When an array is declared it creates memory locations to contain all the elements of
the whole array. The base address is the memory address of first element of array. The
array name is called a constant pointer.
Suppose the programmer wants to declare the array y then it is
int y[4]={10,12,14,16};

The name of the array y is called constant pointer that points to the first elements
y[0]. Therefore, the first element 10 stored in memory y[0] whose base address is 2000.
If we declare a pointer variable p and it points to the array y then it can be represented
as
p=y;

We can alternatively declare it as


p=&y[0];

We can access the address of each elements of the array by using pointer concept is
p+0=&y[0]=2000
p+1=&y[1]=2002
p+2=&y[2]=2004
p+3=&y[3]=2006
342 Concepts and Techniques of Programming in C

TIPS TO REMEMBER
From the above discussion we find the formula to access the address of array
elements using pointer concept in one-dimensional array is: p+i or y+i or
&y[i]

We can access the array elements using pointer concept in one-dimensional array is
*(p+0)=y[0]=10
*(p+1)=y[1]=12
*(p+2)=y[2]=14
*(P+3)=y[3]=16

TIPS TO REMEMBER
So the formula of accessing array elements using pointer concept is:
*(p+i) or *(y+i) or y[i]

TIPS TO REMEMBER
The name of the array is called constant pointer that points to the first element of
the array.

Q21. Examples of Accessing the Array Elements and its Address using Pointer
Concept.
Solution:
/*************************************************************************
FILE NAME: pointer20.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTE: 10/8/2015
NAME OF THE PROGRAM: Examples of accessing the array elements and its
address using pointer concept.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int y[4]={10,12,14,16};
int *p;
p=&y[0];
for(int j=0;j<4;j++)
{
printf(“Value of y[%d] is:%d”,j,y[j]);
printf(“Address of y[%d] is:%u\n”,j,&y[j]);
printf(“Value of y[%d] is:%d”,j,*(y+j));
printf(“Address of y[%d] is:%u\n”,j,y+j);
Pointer 343

printf(“Value of y[%d] is:%u”,j,*(p+j));


printf(“Address of y[%d] is:%u\n”,j,p+j);
}
}

Output:
Value of y[0] is:10 Address of y[0] is:8806
Value of y[0] is:10 Address of y[0] is:8806
Value of y[0] is:10 Address of y[0] is:8806
Value of y[1] is:12 Address of y[1] is:8808
Value of y[1] is:12 Address of y[1] is:8808
Value of y[1] is:12 Address of y[1] is:8808
Value of y[2] is:14 Address of y[2] is:8810
Value of y[2] is:14 Address of y[2] is:8810
Value of y[2] is:14 Address of y[2] is:8810
Value of y[3] is:16 Address of y[3] is:8812
Value of y[3] is:16 Address of y[3] is:8812
Value of y[3] is:16 Address of y[3] is:8812

Q22. C Program to Find Smallest Elements in the Array using Pointer.


Solution:
/*************************************************************************
FILE NAME: pointer21.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: C program to find smallest elements in the array using
pointer.
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void)
{
int a[100],*min,n,i,l=1;
clrscr();
printf(“Input the size of the array:”);
scanf(“%d”,&n);
printf(“Input the [%d] integer elements:”,n);
for(i=0;i<n;i++ )
scanf(“%d”,&a[i]);
min=a;
*min=*a;
for(i=1;i<n;i++)
{
if(*(a+i)<*min)
{
*min=*(a+i);
l=i+1;
}
}
344 Concepts and Techniques of Programming in C

printf(“smallest element found at location[%d]and its value is:%d”,l,*min);


getch();
}

Output:
Input the size of the array: 4
Input [4] integer elements: 3 1 6 8
Smallest element found at location [2] and its value is 1

13.11 POINTERS AND MULTIDIMENSIONAL ARRAYS


The multidimensional arrays are represented in the form of y[i][j].The name of the
array is called constant pointer which gives the base address. In y[i][j], the array name
y gives the base address, e.g., the address of y[0][0] element. So the two-dimensional
array can be represented by pointer expression is:
*(*(p+i)+j) or *(*(y+i)+j) is same as y[i][j].

13.12 POINTER TO ARRAY


Pointer to array means we can declare a pointer variable that can point to the whole
array instead of one element of the array.

The syntax of declaring pointer to two-dimensional array is


data_type (*variable_name)[size];

Example:
int (*x)[20];

EXPLANATION:
This declares that x is a pointer to an array of twenty integers and size represents the
number of columns. The pointer to the array must be dereferences to access the value of
each element. If we do not mention the parenthesis in the above declaration of pointer
variable named x then we would call them it array of pointer. Therefore, we should
use the parenthesis when declaring pointer variable.
Q23. Example of Pointer to One-Dimensional Array.
Solution:
/*************************************************************************
FILE NAME: pointer22.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
Pointer 345

DATE OF PROGRAM EXECUTION: 10/8/2015


NAME OF THE PROGRAM: examples of pointer to one dimensional array.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x;
int m[5]={10,20,30,40,50};
int *p=m; /*or int *p=&m[0] */
for(x=0;x<5;x++)
{
printf(“%d\t”,*p);
p++;
}
}

Output:
10 20 30 40 50
Q24. Example of Pointer to Two-Dimensional Arrays.
Solution:
/*************************************************************************
FILE NAME: pointer23.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: examples of pointer to two dimensional arrays.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y;
int m[2][2]={{10,20},{30,40}};
int (*p)[2]=m;
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
printf(“%d\t”,(*(p+x))[y]);
}
}

Output:
10 20 30 40
Q25. Write a Function using Pointers to Add Two Matrices and Return the Resultant
Matrix to the Calling Function.
346 Concepts and Techniques of Programming in C

Solution:
/*************************************************************************
FILE NAME: pointer24.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: write a function using pointers to add two matrices
and return the resultant matrix to the calling function.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
int x[5][5],y[5][5],row,col;
void add(int(*)[5]);
void main(void)
{
int z[5][5],m,n;
clrscr();
printf(“Input the row : “);
scanf(“%d”,&row);
printf(“Input the column : “);
scanf(“%d”,&col);
printf(“Input the matrix X :\n”);
for(m=0;m<row;m++)
{
for(n=0;n<col;n++)
{
scanf(“%d”,&x[m][n]);
}
}
printf(“Input the matrix Y :\n”);
for(m=0;m<row;m++)
{
for(n=0;n<col;n++)
{
scanf(“%d”,&y[m][n]);
}
}
add(z);
printf(“Addition of two matrices:\n”);
for(m=0;m<row;m++)
{
for(n=0;n<col;n++)
{
printf(“%d\t”,z[m][n]);
}
printf(“\n”);
}
getch();
}
Pointer 347

void add(int z[5][5])


{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
z[i][j]=x[i][j]+y[i][j];
}
}
}

Output:
Input the row: 2
Input the column: 2
Input the matrix X:
2 3
2 4
Input the matrix Y:
2 4
4 5
Addition of two matrices:
4 7
6 11

13.13 ARRAY OF POINTER


Before going to array of pointer first we recall that how the array can be declared. If
we write: int x[10]; then this declaration tells that it is an array of integer type. Similar
to it, the array of pointer means we can declare an array which holds pointers as its
elements, e.g., each element of the array is the pointer variable which holds address
of any other variable.

The syntax of the array of pointer is


data-type *array_name[size];

Example:
int *x[20];

This declares and allocates an array of pointers to int type. Each element must be
dereferences individually.
348 Concepts and Techniques of Programming in C

Q26. Examples of Array of Pointers.


Solution:
/*************************************************************************
FILE NAME: pointer25.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: examples of array of pointers.
*************************************************************************/
#include<stdio.h>
const int M=4;
void main(void)
{
int x[]={1,2,3,4};
int j,*p[M];
for(j=0;j<M;j++)
{
p[j]=&x[j];
}
for(j=0;j<M;j++)
{
printf(“Value of x[%d] are:%d\n”,j,*p[j]);
}
}

Output:
Value of x[0]are:1
Value of x[0]are:2
Value of x[0]are:3
Value of x[0]are:4

Q. Distinguish between the following two pointer declarations:


(i) int(*x)[10];
(ii) int *x[10];

13.14 DYNAMIC MEMORY MANAGEMENT


Dynamic memory management is a technique to managing the memory of the computer
dynamically. Dynamic memory management techniques permit us to allocate additional
memory space or remove unnecessary memory space when program execution is
done (called runtime programming). So when it removes unnecessary memory space
as a result size of memory increases. Alternatively, we can say dynamic memory
management optimizes the storage space of computer. There are four memory allocation
functions are used in dynamic memory allocation. These are: 1) malloc() function, 2)
calloc() function, 3) realloc() function, 4) free() function.
Pointer 349

The C programming language consists of set of local variable, global variable and
program instruction. Among the three generally local variables are stored in stack
region. Program instruction and global variable are stored in computers permanent
storage region. Heap region is the dynamic memory allocation. The size of the heap
changing when program is executed due to creation and deleted.

Variable Name Memory Name


Local Variable Stack Memory
Program Instruction, Global Variable Permanent Memory
Dynamic Memory Allocation Heap Memory

13.14.1 malloc() Function


This is a function which allocates a single block of memory dynamically.
The general form is
p=(data_type*)malloc(size specified);

Here size specified means the number of bytes to be allocated, p is a pointer of type
data-type, malloc returns a pointer of data type to an area of memory with specified
size.
Example:
int *p;
p=(int *)malloc(20);

This function creates 20 bytes of memory whose base address is stored in pointer
variable p. Since p is integer pointer it creates 10 memory location whose size is 2 bytes.
Another form of declaration is
p=(data_ type*)malloc(number of space*sizeof(data _type));

Example:
int *p;
p=(int *)malloc(10*sizeof(int));

Here it creates 10 memory locations to store integer values.


The malloc function allocates a continuous block of bytes. If the heap memory is not
sufficient then the allocation process fails. If fails, it returns a NULL.

13.14.2 calloc() Function


This function is the another memory allocation function which is used to allocate
multiple blocks of memory each of same size and then sets all bytes to zero. This
function is used for allocating memory space dynamically for storing derived data
types such as structure and arrays.
350 Concepts and Techniques of Programming in C

The general form is


p=(data_type*)calloc(n,sizeof(data_type));
This declaration allocates contagious n memory blocks/space each of size of
respective data type.
Example:
int *p;
p=(int*)calloc(5,sizeof(int));

This declaration allocates 5 memory blocks each of size 2 bytes and starting address/
base address is stored in pointer variable p which is int type.

13.14.3 realloc() Function


This function is another memory allocation function which is used to modify the
existing memory size without losing the previous data. If the memory allocated is larger
than the required memory then we want to reduce it. If the previous allocated memory
is not sufficient then we can increase. This process is called the reallocation of memory.
The general form is
p=(int *)realloc(p,modified_size);
In this declaration two arguments are there, first one p is a pointer to the previously
allocated block of memory by the function malloc() or calloc(). The second one is
the modified_size which allocates new memory location to the pointer variable p. p
argument stores the base (starting) address of memory. If modified_size is larger, then
old data is not lost.

13.14.4 free() Function


In dynamic memory allocation, the programmer’s responsibility is to remove the
memory when it is not required. When we do not want to store the data in a block
of memory then we intend to remove that block of memory which we will not use in
future. Then we use the function free.
The general form/syntax is
free(p);
p is a pointer to a block of memory which has been created by malloc or calloc function.

TIPS TO REMEMBER
malloc() function allocates the size of bytes and returns a pointer to the first bytes
of the allocated memory.
calloc() function allocates the memory for array elements, initializes them to zero
and returns a pointer to the memory.
realloc() function modifies the existing memory.
free() function removes the allocated memory.
Pointer 351

Different Types of Important Long Questions about Dymamic Memory Allocation


Q. What are the uses of malloc() and calloc() function in C? In which header file
these two functions are defined? What is the full syntax of these functions?
Q. Explain with simple examples the use of dynamic memory management
functions.
Q. Write short notes on dynamic memory allocation.

13.15 COMMAND-LINE ARGUMENTS


Like user-defined function takes arguments, the main function also takes the arguments
by default. But we do not mention the arguments in writing the program. The main
is also a user defined function which takes two arguments called argument counter
abbreviated as argc and other is argument vector abbreviated as argv.
The variable argument counters (argc) count the number of arguments on the
command line. The argv represents an array of character pointer that points to the
command line arguments. The argc is the size of the array.
In order to access the command line arguments, we must declare the main function
and its parameters are
void main(int argc, char *argv[])
{
}

In the above declaration argv[0] hold the name of the program and argv[1] is pointer
to the first command line argument supplied and *argv[n] is the last argument. If no
arguments are supplied, argc will be one, otherwise and if you pass one argument then
argc is set at 2.

LONG TYPE QUESTIONS ABOUT COMMAND-LINE ARGUMENTS


Q. What is a command line argument? Explain with an example.
Q. Explain the use of command line arguments in C programming with suitable
examples.
Q. Write any two uses of command line argument.

Summary

1. A pointer is a derived data type which is built from fundamental data type, e.g.,
int, char, float, double.
352 Concepts and Techniques of Programming in C

2. The pointer variable holds the memory address of another variable.


3. In pointer variable two important operators are used, e.g.: 1)*(asterisk) and 2) &
(address operator).
4. To print the address of a variable using pointer variable p then write printf(“%u”,p);
5. To print the value of a variable using pointer variable p then write printf(“%d”,*p);
6. Uninitialized pointer may take garbage value therefore after declaration that
variable it should be initialized first.
7. A pointer that is initialized NULL is called null pointer.
8. Pointer-to-pointer means one pointer holds the address of another pointer.
9. Size of all types of pointer variables is same according to the compiler but size
of all types of variable is not same.
10. In pointer arithmetic one pointer can be subtracted from another pointer but
addition, multiplication, division and module operation of two-pointer variable
is not possible but in dereferencing addition, multiplication, subtraction, division,
module operations are possible.
11. To access the address of array elements using pointer in one-dimensional array
we can select any one of the following: a)p+I, b)y+I, c)&y[i]
12. We can access array elements using array. Select any one of the following:
(a) *(p+i), b)*p(y+i), c)y[i]
13. int (*m)[10]; is a pointer to array.
14. int *m[10]; is a array of pointer. [
15. Dynamic memory management is used to manage memory dynamically.
16. Different types memory management functions are:
(a) malloc, (b) calloc() (c) alloc (d) free

SHORT QUESTIONS

1. What is a pointer?
2. What value the pointer variable will hold without initialization?
3. What do you mean by NULL pointer?
4. What do you mean by pointer to pointer?
5. What do you mean by dereferencing pointer?
6. Give examples of pointer as function arguments?
7. Can we add two-pointer variables?
8. Write the formula to access array elements using pointer?
9. Write the formula to access array address using pointer?
10. What do you understand by pointer to array?
Pointer 353

11. What do you understand by array of pointer?


12. What is dynamic memory allocation?
13. What is malloc(), alloc(), calloc() and free function?
14. What is a command line argument?
15. What is the size of pointer variable?
16. What is generic pointer?
17. In C, malloc() initializes the allocated memory garbage? State true or false.

LONG QUESTIONS

1. Write a C program to add two integer numbers using pointer.


2. Write a C program to exchange two integer numbers using pointer.
3. Describe pointer as function arguments with suitable examples.
4. Explain the difference between pointer to array and array of pointer with suitable
examples?

OBJECTIVE QUESTIONs WITH ANSWERs

1. What will be the output?


#include<stdio.h>
void main()
{
int x=3,*y, z;
y=&x;
printf(“%d\n”, x**y*x+*y);
}
Output:
30
2. What will be the output, if address of x is 500 and integer is 4 byte size?
#include<stdio.h>
void main()
{
int x=30,*y,*z;
y=&x;
z=y;
*y++=*z++;
x++;
printf(“x=%d, y=%d, z=%d\n”, x, y, z);
}
Output:
31,504,504
354 Concepts and Techniques of Programming in C

3. What will be the output?


#include<stdio.h>
void main()
{
char s[20] =”CNDIA”;
char *const p=s;
*p=’I’;
printf(“%s\n”,s);
}
Output:
INDIA
4. What will be the output, if the integer is 4bytes long?
#include<stdio.h>
void main()
{
int ***o, **n, *m,x=5;
m= &x;
n= &m;
o= &n;
printf(“%d, %d, %d\n”,*m,**n,***o);
}
Output:
8,8,8
5. What will be the output, assuming that the array begins at the location 1002
and size of an integer is 4 bytes?
#include<stdio.h>
void main()
{
int x[3][4]={10,20,30,40,50,60,70,80,90,100,110,120};
printf(“%u, %u, %u\n”,x[0]+1,*(x[0]+1),*(*(x+0)+1));
}
Output:
1006, 20, 20
6. What will be the output?
#include<stdio.h>
void main()
{
char *s;
s=”%d\n”;
s++;
s++;
printf(s-2,200);
}
Pointer 355

Output:
200
7. What will be the output?
#include<stdio.h>
void main()
{
printf(“%c\n”,6[“INDIA-ODISHA”]);
}
Output:
O
8. What will be the output?
#include<stdio.h>
void main()
{
char s[] = “INDIA”;
char *s1 =s;
printf(“%s\n”, s1++ +2);
}
Output:
DIA
9. What will be the output?
#include<stdio.h>
void main()
{
char *x;
x=”INDIA”;
printf(“%s\n”, *&*&x);
}
Output:
INDIA
10. What will be the output, assuming that the array begins at location 1002?
#include<stdio.h>
void main()
{
int x[2][3][4] = { {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 100,
200},
{20, 10, 40, 70, 60, 70, 80, 90, 0, 0, 0, 0} };
printf(“%u, %u, %u, %d\n”,x,*x,**x,***x);
}
11. What will be the output, if address of ‘a’ is 1000?
#include<stdio.h>
int power(int**);
356 Concepts and Techniques of Programming in C

void main()
{
int x=5,*y;
y= &x;
x= power(&y);
printf(“%d\n”,x);
}
int power(int **m)
{
int n;
n=**m***m;
return(n);
}
Output:
25
12. What will be the output?
#include <stdio.h>
void main(void)
{
int x=30;
int *p =&x;
printf(“%d\n”,*p++);
}
Output:
30
13. What will be the output?
#include <stdio.h>
void main(void)
{
int x=10;
int *p=&x;
int *m=p++;
int n=p-m;
printf(“%d”,n);
}
Output:
1
14. What will be the output?
#include<stdio.h>
void main(void)
{
int x[]={1,2,3,4,5,6};
int *p=x+2;
printf(“%d”,*--p);
}
Pointer 357

Output:
2
15. What will be the output?
#include<stdio.h>
void main()
{
char *x;
x=”DHABAL”;
printf(“%s”,x);
}
Output:
DHABAL
16. What will be the output?
#include<stdio.h>
void main()
{
double a[2],*p,*q;
p=a;
q=p+1;
printf(“%d\n”,q-p);
}
Output:
1

MULTIPLE-Choice QUESTIONS

1. Pointer is a variable which is used to store ________of another variables.


(a) Data type (b) Address
(c) Value (d) Variable name
[Answer: b]
2. Pointer variable is declared using proceeding ______________symbol.
(a) & (b) *
(c) ^ (d) %
[Answer: b]
3. Address stored in pointer variable is of type____________
a) Integer (b) Array
(c) Float (d) Character
[Answer: a]
4. Consider a 32-bit compiler. We need to store address of integer variable to integer
pointer. What will be the size of the integer pointer?
358 Concepts and Techniques of Programming in C

(a) 2 bytes (b) 4 bytes


(c) 10 bytes (d) 6 bytes
[Answer: b]
5. In order to access address of an integer variable we write the preceding_____
symbol.
(a) Ampersand (b) Percent
(c) Comma (d) Asterisk
[Answer: a]
6. A variable X is called pointer if____________
(a) X contains the address of an element in DATA.
(b) X points to the address of first element in DATA
(c) X can store only memory addresses
(d) X contains the DATA and the address of DATA
[Answer: a]
7. Choose the correct options on the following statement:
int (*x)[10];
(a) It is an array “x” of pointers. (b) It is a pointer “x” to an array.
(c) A ragged array. (d) None of the mentioned
[Answer: b]
8. Choose the correct options on the two arrays regarding X and Y.
     int *a1[8];
     int *(a3[8]);
     X. Array of pointers
Y. Pointer to an array
(a) a1 is X, a2 is Y
(b) a1 is X, a2 is Y
(c) a1 is Y, a2 is X
(d) a1 is Y, a2 is Y
[Answer: b]
14
Structure, Union, Type
Definition, Bit Field

14.1 INTRODUCTION
In chapter 4 we saw that a variable can store only one value at a time. Then we
learnt in chapter 14 that an array is a substitute for storing multiple values by using
a single variable of same type. Now we are going to learn a new topic “structure and
it is another substitute how different types of variables called members are store in a
single package” called structure. The structure is the mechanism for storing members of
different data types into one package. Example, suppose the entity named as student
has the following characteristics or properties, e.g., name, regdno, branch, etc. If one
can ask write a C program to display the information of two students using structure
then the program is written as:
/* C Program to Display 2 Students Information, e.g., name, regdno, branch using
Structure */
#include<stdio.h>
void main()
{
struct student
{
char name[20];
int regdno;
char branch[20];
};
struct student s1,s2;
printf(“Input the name,regdno and branch\n”);
scanf(“%s%d%s”,s1.name,&s1.regdno,s1.branch);
scanf(“%s%d%s”,s2.name,&s2.regdno,s2.branch);
printf(“The inputted data are\n”);
printf(“%s\t%d\t%s\n”,s1.name,s1.regdno,s1.branch);
printf(“%s\t%d\t%s”,s2.name,s2.regdno,s2.branch);
}
360 Concepts and Techniques of Programming in C

Output:
Input the name, regdno and branch
Dhabal 15 Comp.sc
Jugal 09 ETC
The input data are
Dhabal 15 comp.sc
Jugal 09 ETC

Explanation:
Here in this program the structure is defined inside the main function along with
structure variables s1 and s2. Each structure variable can have access permission of each
member. Always note that whenever the user writes code of taking the input of group
of characters then the access specifier %s is used. You may or may not place address
operator before the character member and when input is int type then the place address
operator before int type member.

14.2 DEFINING/DECLARING A STRUCTURE


The syntax of defining or declaring the structure is
struct struct_name
{
datatype variable1;
datatype variable2;
-----------------------
-----------------------
};

EXPLANATION:
From the above definition we know that struct is a data type which holds the different
variables of different types than struct_name is the name of the structure and it also
called structure tag. The variables declared inside the curly braces are called structure
elements or structure members. These are not called structure variables. Each member
belongs to different data type. At the end of the structure definition semicolon is given
to terminate it. Let’s see the example:
struct student
{
char name[30];
int regdno;
char branch[30];
};
Structure, Union, Type Definition, Bit Field 361

EXPLANATION:
Here the keyword struct is the structure data type which holds three data fields of
different types, e.g., name, regdno, branch. The student is called name of structure or
structure tag. The three different fields (name, regdno and branch) are called structure
elements or structure members and last semicolon is used to terminate the structure.

TIPS TO REMEMBER
While writing a program using structure, the declaration of structure may be done
above the main()function or inside the main()function.

14.3 DECLARATION OF STRUCTURE VARIABLES


The declaration of structure variable is similar to the declaration of variable of
fundamental data type, e.g., int, char, float, double. It consists of the keyword struct,
the structure tag name, if series of variables present then to separate it by giving comma
in each variable and at the end of the statement semicolon is used for termination.

The syntax of declaring structure variable is:


struct struct_name variable1,varibale2--------varible_N;

Example:
struct student s1,s2,s3; /*s1,s2,s3 are structure variables*/
Then the complete declaration of structure and variable is
struct student
{
char name[10];
int regdno;
char branch[10];
};
struct student s1,s2; /*s1 and s2 are structure variables*/

TIPS TO REMEMBER
The members of structure are not structure variables. They are structure members.
They do not occupy any memory until they are associated with the structure
variables such are s1, s2.

14.4 ACCESSING STRUCTURE MEMBER


In array concept the individual/each element of the array is accessed using subscript.
But in structure concept it does not follow the subscript notation. To access the members
362 Concepts and Techniques of Programming in C

of a structure the dot (.) is used which is called dot operator or period operator or
member operator. This operator makes or establishes a connection between members
of the structure with the structure variables. Let’s see the example below as:
s1.name;

Here s1 is the structure variable and name is the structure member. So the dot
operator maintains the relationship between s1 and name to access the name which is
initialized.
/*Example of Accessing Structure Members*/
#include<stdio.h>
void main()
{
struct student
{
char name[30];
int regdno;
char branch[30];
};
struct student s1;
printf(“INPUT THE NAME,REGD,BRANCH:”);
scanf(“%s %d %s”,s1.name,&s1.regdno,s1.branch);
printf(“THE INPUTTED NAME,REGD AND BRANCH IS:%s %d %s”,s1.name,s1.regdno,s1.
branch);
}

Output:
INPUT THE NAME, REGD, BRANCH: DHABAL 15 CSE
THE INPUTTED NAME, REGD AND BRANCH IS: DHABAL 15 CSE

14.5 STRUCTURE VARIABLE INITIALIZATION


Whenever a programmer assigns the values to structure variable it is called structure
variable initialization.
The different forms of structure variable initialization are:
1. One structure variable initialization inside the main function
#include<stdio.h>
void main()
{
struct
{
char name[30];
int regdno;
char branch[30];
}
Structure, Union, Type Definition, Bit Field 363

s1={“Ram”,100,”Civil”}; /*structure variable s1 initialization*/


printf(“NAME\t REGDNO\tBRANCH\n”);
printf(“%s\t%d\t%s”,s1.name,s1.regdno,s1.branch);
}

Output:
NAME REGDNO BRANCH
Ram 100 Civil

Explanation:
Here name ‘ram’ assign to s1.name,100 assign to s1.regdno,’civil’ assign to
s1.branch.There is a one-to-one mapping between the members and their
initializing values.
2. Multiple structure variable initializations inside the main function
#include<stdio.h>
void main()
{
struct student
{
char name[30];
int regdno;
char branch[30];
}
s1={“Ram”,100,”Civil”}; /*structure variable s1 initialization*/
struct student s2={“Hari”,101,”Elect”}; /*structure variable s2
initialization*/
printf(“NAME\t REGDNO\tBRANCH\n”);
printf(“%s\t%d\t%s\n”,s1.name,s1.regdno,s1.branch);
printf(“%s\t%d\t%s”,s2.name,s2.regdno,s2.branch);
}

Output:
NAME REGDNO BRANCH
Ram 100 Civil
Hari 101 Elect

Explanation:
Here structure named student consists of three members name, regdno, branch
is declared along with two structure variable s1 and s2 are initialized.
3. One structure variable initialization outside the main function and another one
initialization inside the main function
#include<stdio.h>
struct student
{
364 Concepts and Techniques of Programming in C

char name[30];
int regdno;
char branch[30];
}s1={“Ram”,100,”Civil”};/*structure variable s1 initialization*/
void main()
{
struct student s2={“Hari”,101,”Elect”};/*structure variable s2
initialization*/
printf(“NAME\t REGDNO\tBRANCH\n”);
printf(“%s\t%d\t%s\n”,s1.name,s1.regdno,s1.branch);
printf(“%s\t%d\t%s”,s2.name,s2.regdno,s2.branch);
}

Output:
NAME REGDNO BRANCH
Ram 100 Civil
Hari 101 Elect

Explanation:
Here structure student is declared outside the main function, i.e., it is placed
above the main function and the structure variable is declared and initialized
inside the main function.

TIPS TO REMEMBER
1. The structure members inside the curly braces are not initialized individually.
2. When initializing the structure variables, the order of values should match the
order of the structure members. The uninitialized members are assigned to zero
for integer and floating numbers and ‘\0’ for character and strings.

/*Addition of Two Complex Numbers using Structure*/


#include <stdio.h>
struct complex
{
int real;
int img;
};
void main()
{
struct complex x,y,z;
printf(“Input x and y[where x + iy is the first complex number]:”);
scanf(“%d%d”,&x.real,&x.img);
printf(“Input m and n[ where m + in is the second complex number]:”);
scanf(“%d%d”, &y.real,&y.img);
z.real = x.real + y.real;
z.img = x.img + y.img;
Structure, Union, Type Definition, Bit Field 365

if(z.img>=0)
printf(“Addition of two complex numbers is:%d + %di\n”, z.real, z.img);
else
printf(“Addition of two complex numbers is:%d %di\n”, z.real, z.img);
}

Output:
Input x and y [where x+iy is the first complex number]:2 3
Input m and n [where m+in is the second complex number]:4 5
Addition of two complex numbers is:6+8i

14.6 NESTED STRUCTURE


Structure within structure is called nested structure, i.e., one structure can be declared/
defined inside other structure.
/*Examples of Structure within Structure */
#include <stdio.h>
#include <string.h>
struct college
{
int colle_id;
char colle_name[30];
};
struct student
{
int id;
char name[30];
float percentage;
struct college c; /*structure variable c of college is within another
structure named student*/
} s; /*s is the structure variable of student*/
void main()
{
struct student s ={100,”Rajiv sharma”,80.00,104,”GCE,KEONJHAR”};
printf(“Student Id is: %d \n”,s.id);
printf(“ Student Name is: %s \n”,s.name);
printf(“ Percentage of marks is: %f \n\n”,s.percentage);
printf(“ College Id is: %d \n”,s.c.colle_id);
printf(“ College Name is: %s \n”,s.c.colle_name);
}

Output:
Student Id is: 100
Student Name is: Rajiv Sharma
Percentage of marks is: 80.000000
College Id is: 104
College Name is: GCE, KEONJHAR
366 Concepts and Techniques of Programming in C

Explanation:
In the above program the structure student has three data fields’, i.e., id, name, and
percentage. To access the student id, name, percentage of marks we can use structure
variable s.memeber name, e.g., s.id, s.name, s.percentage. To access college id and
college name we can use s.c.colle_id, s.c.colle_name. We cannot directly access the
college members because college members are declared inside another structure.
Therefore, college structure variable c is essential with student structure variable s to
access the college members.
/*Examples of Structure within Structure of Structure Pointer Variable*/
#include <stdio.h>
#include <string.h>
struct college
{
int colle_id;
char colle_name[30];
};
struct student
{
int id;
char name[30];
float percentage;
struct college c; /*structure within structure*/
}s,*s1;
void main()
{
struct student s ={100,”Rajiv sharma”,80.00,104,”GCE,KEONJHAR”};
s1=&s;
printf(“ Student Regd_Id is: %d \n”,s1->id);
printf(“ Student Name is: %s \n”,s1->name);
printf(“ Percentage of marks is: %f \n\n”,s1->percentage);
printf(“ College Regd_Id is: %d \n”,s1->c.colle_id);
printf(“ College Name is: %s \n”,s1->c.colle_name);
}

Output:
Student Regd_ Id is: 100
Student Name is: Rajiv Sharma
Percentage of marks is: 80.000000

College Regd_Id is: 104


College Name is: GCE, KEONJHAR

Explanation:
Here s is the structure variable of student,*s1 is pointer variable of structure student.
So when pointer variable s1 is used to access the student members then arrow operator
Structure, Union, Type Definition, Bit Field 367

(->) is used by pointer variable of structure type, i.e., s1->id, s1->name, s1->percentage.
To access college members use s1->c.colle_id, s1->c.colle_name.

TIPS TO REMEMBER
Dot(.) operator is used to access structure members by simple variables and
->(arrow) operators is used to access the structure member by using pointer
variables which is declared inside the structure.

14.7 ARRAY OF STRUCTURE


In structure if we want to store 20 students names then we would be required to create
20 structure variables individually from s1 to s20 which is not efficient. A better solution
is to use the concept array of structure. An array of structure means it is an array of
similar data types which themselves have a collection of dissimilar data types. In an
array of structure all the elements of the array are stored in adjacent memory locations.
Since each element of an array is a structure type, so all structure elements are stored
in adjacent location, e.g., s[0].name, s[0].regdno, s[0].branch in memory followed by
s[1].name, s[1].regdno, s[1].branch and so on.
/*Example of Array of Structure*/
#include<stdio.h>
struct student
{
char name[20];
int regdno;
char branch[20];
};
void main()
{
struct student s[5]; /*Here s[5] is the array of structure which contains
5 students different members defined inside the structure student*/
int j;
for(j=0;j<5;j++)
{
printf(“INPUT THE STUDENT NAME,REGDNO,BRANCH:”);
scanf(“%s%d%s”,&s[j].name,&s[j].regdno,&s[j].branch);
}
printf(“YOU HAVE INPUTTED STUDENT NAME,REGDNO,BRANCH\n”);
for(j=0;j<5;j++)
{
printf(“%s\t%d\t%s\n”,s[j].name,s[j].regdno,s[j].branch);
}
}
368 Concepts and Techniques of Programming in C

Output:
INPUT THE STDUENT NAME, REGDNO, BRANCH: DHABAL 100 CSE
INPUT THE STDUENT NAME, REGDNO, BRANCH: JUGAL 200 ETC
INPUT THE STDUENT NAME, REGDNO, BRANCH: RAJIB 300 MECHANICAL
INPUT THE STDUENT NAME, REGDNO, BRANCH: NUTAN 400 CIVIL
INPUT THE STDUENT NAME, REGDNO, BRANCH: PRAKASH 500 ELECT
YOU HAVE INPUTTED STDENT NAME, REGDNO, BRANCH
DHABAL 100 CSE
JUGAL 200 ETC
RAJIB 300 MECHANICAL
NUTAN 400 CIVIL
PRAKASH 500 ELECT

Explanation:
In the above program we declared the structure variable named s[5]; e.g., s is the
variable of which will hold 5 elements. Then using for loop we can input 5 elements
and will displaced on the computer screen.

14.8 STRUCTURE AND FUNCTION OR PASSING


STRUCTURE AS AN ARGUMENT IN FUNCTION
In structure and function, the structure variable is passed as an argument to user-defined
function. There are three different ways the values of structure variable are passed from
calling function to called function. First individual members of the structure are passed
as an actual argument in the function call; second passing entire structure variable as an
argument by using pass by value method and third by passing the address of structure
variable by using pass by reference. In pass by value the copy of entire structure
variables is passed as argument to the called function. Any change happens with
structure members within the function does not reflect the original value of structure.
But using pass by reference address of structure members are passed as an argument
to the called function and any changes happen with structure members inside the user
defined function they reflect the original value of calling function.

14.8.1 Passing Structure Member Individual as an Argument in Function


Here instead of sending structure variable we can pass each structure member as an
argument inside function call to called function.
The syntax of structure individual member as an argument in the calling function is:
Function_name (variable.member_name1, variable.memeber_name2………..
variable. member_nameN);
Structure, Union, Type Definition, Bit Field 369

The function definition is:


return_type function_name(structure_type variable1,strcture_type
varibale2)
{
------------------
-----------------
return expression;
}

/** Program to Implement Structure Individual Member as an Argument in


Function **/
#include<stdio.h>
#include<conio.h>
struct student
{
char name;
int rollno;
float marks;
};
struct student s(char, int, float); /*function prototype*/
void main()
{
struct student s1 = {‘X’,100,600};
s(s1.name, s1.rollno, s1.marks); /*function call*/
getch();
}
struct student s(char name, int rollno, float marks) /*function definition*/
{
printf(“Name\tRoll_No.\tMarks\n”);
printf(“%c\t%d\t\t%f”, name, rollno, marks);
}

Output:
Name Roll_No Marks
X 100 600.000000
Explanation:
Here user input the structure members individually as pass by value method, i.e., he
passes name, rollno and marks as an argument in function s. The function accepts the
members through calling function to called function and the called function displays
the output.

14.8.2 Passing Structure Variable at a Time by using Pass by Value


When number of structure members increases then it is difficult to pass each member
of structure as an argument. To solve that issue instead of passing each member, we
can pass the entire structure variable at a time in function call to called function by
pass by value.
370 Concepts and Techniques of Programming in C

The syntax of structure variable in an argument in the calling function is:


Function_name (structure_variable1, structure _variable2, ---------,
structure variable_N);

The function definition is:


return_type function_name(structure_variable1,strcture_varibale2)
{
------------------
-----------------
return expression;
}

#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
float marks;
};
void s(struct student); /*function prototype*/
void main()
{
struct student s1 = {“DHABAL”,100,600};
s(s1); /*function call*/
getch();
}
void s(struct student s) /*function definition*/
{
printf(“Name\tRoll_No.\tMarks\n”);
printf(“%s\t%d\t\t%f”, s.name, s.rollno, s.marks);
}

Output:
Name Roll_No Marks
DHABAL 100 600.000000

Explanation:
Instead of sending the individual element of structure variable from calling function
to called function the user can send whole structure variable as an argument to called
function.

14.8.3 Passing Address of Structure Variable by using Pass by Reference


Here instead of passing structure variable, we can pass address of structure variable.
The syntax of passing the address as an argument in the calling function is:
Function_name (&structure_variable1);
Structure, Union, Type Definition, Bit Field 371

The function definition is:


return_type function_name(struct structure_name *varibale1)
{
------------------
-----------------
return expression;
}
/*passing address of a structure variable*/
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
float marks;
};
void s(struct student *); /*function prototyping*/
void main()
{
struct student s1 = {“DHABAL”,100,600};
s(&s1); /*calling function*/
getch();
}
void s(struct student *s2) /*function definition*/
{
printf(“Name\tRoll_No.\tMarks\n”);
printf(“%s\t%d\t\t%f”, s2->name, s2->rollno, s2->marks);
}

Output:
Name Roll_No Marks
DHABAL 100 600.000000
Explanation:
Here user passes the structure variable as an argument by using the address of variable
to called function. This method is called pass by reference method.

14.9 POINTER TO STRUCTURE


Pointer to structure means a pointer variable pointing to a structure variable instead
of general declaration of variable. Such pointer variable is called structure pointer. We
know that the pointer is a variable which holds the address of another variable, i.e., a
pointer pointing to int, char, float or double.
/*Examples of Pointer to Structure*/
#include<stdio.h>
void main()
{
372 Concepts and Techniques of Programming in C

struct student
{
char name[30];
int regdno;
char branch[30];
} ;
struct student s1={“DHABAL”,100,”CSE”};
struct student *p;
p=&s1;
printf(“%s\t%d\t%s\t”,s1.name,s1.regdno,s1.branch);
printf(“\n%s\t%d\t%s\t”,p->name,p->regdno,p->branch);
}

Output:
DHABAL 100 CSE
DHABAL 100 CSE

EXPLANATION:
The first printf statement is simply displaying the initialized values of structure through
dot operator. The second printf statement displays the same initialized values by using
arrow operator because p is a pointer variable. If we want to access the structure
members through pointer variables we use the arrow (->) operator.
In the above program instead of ptr->name we can write (*p).name,(*p).regdno,(*p).
branch. Here parenthesis is required because (.) operator has highest precedence
then*operator.
We cannot use the p.name, p.regdno, p.branch because p is not a structure variable
but a pointer to structure. So instead of (.) dot operator provides an arrow (->) operator
to refer to the structure elements.

14.10 SELF-REFERENTIAL STRUCTURE


A self-referential structure is one of the data structures which refer to the pointer to
another structure of the same type. The syntax is
struct struct_name
{
datatype datatypename;
struct_name * pointer_name;
};

For example, a linked list is supposed to be a self-referential data structure. The next
node of a node is being pointed, which is of the same struct type. For example,
typedef struct node
{
void *data;
struct node *next;
} linked_list;
Structure, Union, Type Definition, Bit Field 373

In the above example, the node is a self-referential structure – because the *next is
of the type struct node.

14.11 UNION
Union is a derived data type like structure and it can contain members of different data
types. The syntax of union is same as structure, but the keyword union is used instead
of struct. The major difference between a structure and union is that, in structure each
member has its own/individual memory location; whereas in case of union all the
members have the same memory location, e.g., a union contains members of different
data types and it can handle one member at a time.

14.11.1 Union Declaration


The syntax of union is
union union_name
{
datatype member1;
datatype memeber2;
}variable_name;

Example:
union student
{
char name;
int regdno;
flaot marks;
} u1;

EXPLANATION:
The above example the variable u1 is of type union student. The union contains three
members, i.e., char, int, float which is different type. However, the union works single
data type at time. This is the fact that one location is allocated for union variable in
respect to its size. The highest size of data type is floating, i.e., 4 bytes. So maximum
four memory locations, each of size1 byte is created and all of them use it.

100 101 102 103

When char whose size is 1 byte is used others are not used. Same int whose size is
2 bytes when used others are not.
374 Concepts and Techniques of Programming in C

Q. Differentiate between structures and union.


Solution:
The concept of structure and union is same except allocating the memory for
its member. The structure allocates all its members in separate memory location
whereas union allocates all its members in one common memory location. The
structure can access all member values at the same time but in union we cannot
access all member values at the same time. In union we can access only one
member at a time. Structure occupies large memory space whereas union occupies
less memory space.

14.12 TYPE DEFINITION


The typedef is the user defined data type which is used to assign alternative names to
the existing types. It is mostly used with user defined data types, when names of data
types get slightly complicated.
The syntax for using typedef is
typedef data_type existing_name alias_name;

Example:
typedef int result; / *result is the data type*/
result r1,r2; /*r1,r2 are variables of type result*/

EXPLANATION:
Here result is the user-defined data type. So here the result is alternative name of int
data type. We can use the data type named result in place of anywhere in and r1, r2
are variables of type result.
/*Example 1 of Type-definition*/
#include<stdio.h>
#include<conio.h>
typedef struct student
{
char name[24];
int age;
};
void main()
{
typedef struct student b; /*here b is the data type*/
b z={“DHABAL”,30}; /*here z is the structure variable*/
clrscr();
printf(“The name and age is:%s %d”,z.name,z.age);
}
Structure, Union, Type Definition, Bit Field 375

Output:
The name and age is: DHABAL, 30
/*Example 2 of Type-definition*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct employee
{
char name[30];
int sal;
} emp;
void main( )
{
emp e1;
printf(“Input the Employee record\n”);
printf(“\Input the Employee name:”);
scanf(“%s”,e1.name);
printf(“Input Employee salary:”);
scanf(“%d”,&e1.sal);
printf(“Inputted Employee name is: %s”,e1.name);
printf(“\nInputted Employee salary is: %d”,e1.sal);
}

Output:
Input the Employee record
Input the Employee name: DHABAL
Input the Employee salary: 15600
Inputted Employee name is: DHABAL
Inputted Employee salary is: 15600

14.13 BIT FIELD


In many cases we declare the variable which holds 20 bytes of memory, e.g., in array
concept but actually when we inputted 10 values then rest 10 memory location holds
garbage value or zero. To minimize the wastage of memory cells we are going to use
bit field. A bit field is a set of adjacent bits, e.g., binary digits (0 or 1). The bit field is
used inside the structure members. Each member uses bit field to specify the size of
the each member.
The syntax of defining bit field is
struct structure_name
{
data_type varibale1:bit_length;
data_type varibale2:bit_length;
------------------------------------------
------------------------------------------
376 Concepts and Techniques of Programming in C

data_type varibaleN:bit_length;
};

TIPS TO REMEMBER
The data type of bit field can be int, unsigned int, signed int.

/*Examples of Bit Filed Uses*/


#include<stdio.h>
#include<conio.h>
struct values
{
unsigned a:2;
unsigned b:5;
unsigned c:4;
unsigned d:3;
};
void main()
{
struct values v={3,10,12,3};
clrscr();
printf(“the values of v are:%d %d %d %d”,v.a,v.b,v.c,v.d);
}

Output:
The values of v are: 3, 10,12,3
EXPLANATION:
Here the size of member “a” is 2-bit, i.e., the value may be 0 to 22-1=3 e.g. 0 or 1 or 2 or
3. Then size of member “b” is 5 bits, i.e., the value may be 0 to25-1=31, i.e., value may
be[0----31].The size of member “c “ is 4 bits, i.e., the value may be 0 to 2 4-1=15 [0----15].
The size of member “d” is 3-bit, i.e., the value may be 0 to 2 3-1=7[0----7].

SUMMARY
1. Structure is the mechanism for storing members of different data types into one
package.
2. The structure name is also called structure tag.
3. The variables inside the structure by using curly braces are called structure
elements or structure members but not called structure variables.
4. Suppose the structure name is student then the structure variable declaration is:
struct student s1;
5. When the structure members are associated with structure variable then it creates
memory space.
6. To access structure members the dot(.) operator is used to establish a connection
between structure members and structure variable.
Structure, Union, Type Definition, Bit Field 377

7. Assigning values to structure variable is called structure variable initialization.


8. One structure embedded within another structure is called a nested structure.
9. Passing structure variable to user defined function is called passing structure as
an argument in function.
10. Pointer to structure means a pointer variable of type struct pointing to a structure
variable is called pointer to structure.
11. In union all the members use same memory location instead of individual.
12. The typedef is the user defined data type which is used to assign alternative name
to the existing type.
13. To minimize wastage of memory cells we use bit field.
14. Each member uses bit field to specify the size of each member.

SHORT QUESTIONs
1. Define structure and its advantages?
2. Can we write a program written using an array in using structure? If yes give
example?
3. The members of structure are called structure variables? True or false. Give your
justification.
4. What is the declaration of structure variable?
5. Define structure.
6. How do we access the structure elements?
7. Define array of structure?
8. Define Nested structure with example.
9. Define pointer to structure?
10. What is union?
11. Differentiate between union and structure?

LONG QUESTIONS
1. Write a program to store 100 records in one structure with the help of an array.
2. Write a C program to create data for 50 students (roll, name, mark 1, mark 2,
mark 3, termmark) using structure and then find the total marks for each student
and average marks of all students.
3. What do you mean by self-referential structure? Give an example of it.

OBJECTIVE QUESTIONs WITH ANSWERs


1. What will be the output?
#include<stdio.h>
void main()
{
378 Concepts and Techniques of Programming in C

struct student
{
int age;
char x;
};
printf(“%d”,sizeof(student));
}
Output:
3
2. What will be the output?
#include<stdio.h>
void main()
{
struct student
{
int age;
char x[20];
};
printf(“%d”,sizeof(student));
}
Output:
22
3. What will be the output?
#include<stdio.h>
void main()
{
union student
{
int age;
char x;
};
printf(“%d”,sizeof(student));
}
Output:
2
4. What will be the output?
#include<stdio.h>
void main()
{
union student
{
int age;
char x[20];
};
printf(“%d”,sizeof(student));
}
Output:
20
15
File

15.1 Introduction
In console oriented programming every time beginner is given the input value and it
display the output on the computer screen because when the power is turned off or
when the program is closed its data is lost. In real-time storing of large amount of data,
it is difficult to handle/maintain using console oriented programming. To solve that
situation we can use the concept file. A file is a place on the computer hard drive where
the set of related data is stored. The advantage of file is that loss data is not possible.
Generally, in computer hard drive, all data is stored in binary file. Let’s see how data
is stored in computer hard drive.

C Program

C Library Functions

Operating System

Computer Hard Drive

Fig. 15.1 Data stored in a file

15.2 TEXT FILES AND BINARY FILES


A text file is a file which contains textual information, i.e., it contains digits, alphabets
and special symbols. Programs written in the editor (TURBO C) are examples of text
files. Suppose myfirstprog.c is the real time examples of text files.
380 Concepts and Techniques of Programming in C

Binary files are the collection of bytes. Programs are converted into binary files and
stored in computer hard disk. The binary files are the combinations of binary digit 0
and 1. Examples of binary files are program.exe or music stored in wave files or pictures
stored in graphic files.

15.3 FILE I/O OPERATION


Different operations done with the concept of file in C programming are
1. Creating/declaring a file
2. Opening a file
3. Reading a file
4. Writing a file
5. Moving a file to a specified location
6. Closing a file

DESCRIPTION ABOUT FILE OPERATION


1, 2) Creating/Declaring a file and opening a file
To read data from a file or write data to a file on the computer hard disk we have to
first declare the file and then to open the file. To open the file use the function fopen()
along with file opening mode, i.e., read mode or write mode etc.

The syntax of declaring and opening a file is:


FILE *x; /* syntax of declaring a file*/
x=fopen(“filename”,”mode”); /*syntax of opening a file*/

EXPLANATION:
In the above two lines, the first line: FILE *x; specifies that x is the pointer variable of
data type FILE. Note that FILE is the structures that are defined in the I/O library file.
The second line: x=fopen(“filename”,”mode”); the fopen() function consists of two
parameters. The first parameter ”filename” is the specified path where the data stored
and it is represented in the form of strings. The second parameter “mode” means to
place the mode, i.e., read, write or append, etc. The fopen() function assigns the value
to the file pointer x and it searches the location on the computer hard disk where it
will store the data and to be opened. Then it loads the data from the specified location
in to temporary memory place called buffer. Then it points the first character of buffer.
6) Closing a File
If the file reading from hard drive is finished then we need to close it. This can be done
by using the function fclose().
File 381

The syntax of closing a file is:


fclose(p);

TIPS TO REMEMBER
In file concept, the header file is: #include <stdio.h>

15.4 FILE OPENING MODE


(A) ” r”(read) mode
The “r”(read) mode used for to open the file for reading purposes. In this mode if the
file previously exists then the file is opened. If does not exist then an error message
will generate.

(B) “w “(write)mode
The “w”(write) mode used for to open the file for writing purposes. In this mode
when the file does not exist then the file with a name will be created. If the file exists
previously then data of the file is lost and new data is written in that file.

(C) “a”(append) mode


The “a”(append) mode used for to open the file for adding data to that file. If the file
does not exist then the file with specified name will be created. If the file exists then
current data will be added with previously existing data in that file but previous data
do not lost.

(D) ”r+” (read +write) mode


This “r+” (read + write) mode is same as “r” mode but in this mode we can write and
modify the existing data used for reading and writing purpose.

(E) “w+“(write +read) mode


This mode is same as “w” mode but in this mode we can also read and modify the
data. If the file exists, then its data is overwritten. If the file does not exist, a new file
is created.

(F) “a+“(append +read) mode


This mode is the same as “a” mode but in this mode we can also read the data stored in
the file. In this mode we cannot modify the previously existing data. If the previously
382 Concepts and Techniques of Programming in C

file does not exist then new file is created and if exists new data is appended with
existing data.

15.5 INPUT/OUTPUT FUNCTIONS IN FILE


15.5.1 getc() Function
This is the file input function, which is used to read a character from a file that has
been opened in read mode.
Example:
x=getc(p);

This declaration read a character from the file whose file pointer is p. The getc()
function returns an end-of-file(EOF),when end of the file has been reached. Therefore,
when EOF is reached then reading the file is terminated.
1. /*** Program to Read a Character from a File ***/
#include <stdio.h>
void main(void)
{
FILE *p;
char x;
p=fopen(“c:\\new\\a.txt”, “r”);
x=getc(p);
printf(“\nRead character is:%c”,x);
}

Output:
Read Character is: I

EXPLANATION:
Here before executing the program the programmer should create a folder in any hard
drive, i.e., C, D, E, etc. Here I have created in C drive and open a new notepad and
type the character, i.e., I and save it by giving a name with extension txt. Then copy
the path of notepad and paste in place of file name that are enclosed in double quotes
then give comma and again give second double quote and inside it place r for read
mode in the program. Then after writing the complete program run that program and
get the output I.

15.5.2 putc() Function


This is the file output function, which is used to write a character to the file.
Example:
putc(x,p);
File 383

This declaration writes a character contained in the character variable x to the file
pointer p.
2. /*** Program to Write a Character to a File ***/
#include <stdio.h>
void main(void)
{
FILE *p;
char x;
printf(“Input the character:”);
scanf(“%c”,&x);
p=fopen(“c:\\new\\a.txt”, “w”);
putc(x,p);
fclose(p);
}

Output:
Input the character: r (press enter and close and see a.txt file)

EXPLANATION:
Again I told that before run the above program first creates a folder named new in
any drive, i.e., C or other and inside the folder create a new notepad and save it with
extension txt inside the folder new. Then type the above program in editor and inside
the fopen() function copy the path of the notepad and paste it and then give comma
and again inside the double quotes write w for write purpose. After writing the
complete program run that program. When the message comes, input the character
in that position type the character suppose r and press the enter key then it activates
automatically and internally r stored in a.txt inside new folder. Then open the folder
new and again open a.txt and see the result.

TIPS TO REMEMBER
EOF means end of file.

3. /*C Program of Copying the File from One Location to other Locations*/
#include <stdio.h>
void main(void)
{
FILE *x,*y;
char z;
x=fopen(“d:\\dhabal\\source.txt”, “r”);
y=fopen(“d:\\dhabal\\destin.txt”, “w”);
while((z=getc(x))!=EOF)
putc(z,y);
fclose(x);
fclose(y);
}
384 Concepts and Techniques of Programming in C

Output:
Type the program and run it and see destin.txt

EXPLANATION:
Here in the above program two file pointer variables are declared, i.e., x and y. x
pointer variable holds data, i.e., reading the data from one file and y is another pointer
variable and is used to hold the data that is copied from another pointer variable x.
Before writing the above code first create the folder named dhabal and inside the folder
open two notepads and save as source.txt and other as destin.txt. In source.txt type the
text and save it then copy the path of source.txt and paste into the position of opening
file and assign to pointer variable x and in destin.txt file do not write any text and
copy the path and paste it into respective position of fopen() function and it assign
to pointer variable y . Lastly, type the above program turbo c4.5 editor or other editor
and run it .After run see the text stored in source.txt file are coped into destin.txt file.
4. /* Program to write the String to the File and then Read it*/
#include <stdio.h>
void main(void)
{
FILE *p;
char x[40],y[40];
printf(“\nInput the string: “);
gets(x);
p=fopen(“c:\\new\\a.txt”, “w”);
fputs(x,p);
fclose(p);
p=fopen(“c:\\new\\a.txt”, “r”);
fgets(y,40,p);
printf(“\nThe inputted string is:\n”);
puts(y);
}

Output:
Input the string: DHABAL
The inputted string is: DHABAL

EXPLANATION:
This program demonstrates that user input the strings that are stored in a.txt file and
then it will display on the computer screen. Here user input the string through gets
function and then fopen() function creates a file named as a.txt because we have used
w mode. The function w mode will store the input in file and old value of file will be
erased. The fputs()function will store the input into the created file a.txt. Again fopen()
function is used to read the input data from file and stores in to y variable through
fgets() function and last puts function display the input string.
File 385

15.5.3 getw() Function


This function is used for reading the integer values.

The syntax of getw() is:


getw(p);

Here p is the file pointer.

15.5.4 putw() Function


This function is used for writing the integer values.

The syntax putw() function is:


putw(p);

Here p is the file pointer.

15.5.5 fprintf Function

The syntax of fprintf is:


fprintf(p,”control string”,varible1,varible2………variable-N);

Where p is a file pointer that has been opened for writing, the control string contains
the conversion specification character.
5. /*Program to write Data (roll number, name, marks) into a File using fprintf() */
#include <stdio.h>
void main(void)
{
FILE *x;
int roll_no;
char name[20];
float marks;
printf(“\nInput your roll number:”);
scanf(“%d”, &roll_no);
printf(“\nInput your name: “);
fflush(stdin);
gets(name);
printf(“\nInput your marks: “);
scanf(“%f”,&marks);
x=fopen(“c:\\new\\a.txt”, “w”);
fprintf(x,”%d %s %f”, roll_no, name, marks);
fclose(x);
}
386 Concepts and Techniques of Programming in C

Output:
Input:
Input your roll number: 110
Input your name: DHABAL
Input your marks: 80

EXPLANATION:
After running the program when the user types the above input and presses enter by
keyboard then in the background in a.txt, all data is stored in serial. i.e., in a.txt the
data are: 110 DHABAL 80

15.5.6 fscanf() Function


The fscanf() function is used to read the input from file.

The syntax of fscanf function is


fscanf(fp,”control string”,varibale1,varibale2----variable-N);

6. /*C Program to Read (retrieve) Data from File using fscanf()*/


#include <stdio.h>
void main(void)
{
FILE *x;
int rollno;
char name[30];
float marks;
x=fopen(“c:\\new\\a.txt”, “r”);
fscanf(x, “%d %s %f”, &rollno, name, &marks);
printf(“\nRoll _No.: %d”, rollno);
printf(“\n\nName = %s”, name);
printf(“\n\nMarks = %.2f”, marks);
fclose(x);
}

Output:
Roll_No: 110
Name: DHABAL
Marks: 80.00

EXPLANATION:
Here the output is 110, DHABAL, 80.00 because before running the above program
in a.txt file 110DHABAL89.00 is stored. The fscanf() function reads that and displays
using printf() function.
File 387

15.6 ERROR HAPPENED DURING I/O OPERATION


1. When programmer trying to open a file in read mode and the file is not present
in the computer hard drive then error happens.
2. when trying to open a file for writing, but the fopen() function fails due to
insufficient memory space avail in the hard drive to create a new file or disk is
write protected or damage of hard drive and so on then error happens.
3. If the file already exists and we do not have permission to delete the file then in
that case error happens. If the file opening fails due to the above reason and so
on then fopen() function returns a NULL value.
Let’s see the example
7. /*Example how Error Occurs in Program*/
#include<stdio.h>
#include<stdlib.h>
void main(void)
{
FILE *x;
x=fopen(“C:\\new\\a.txt”,”r”);
if(x==NULL)
printf(“File does not present on hard drive”);
}

Output:
File is not present on hard drive

EXPLANATION:
To test the above program the programmer first create a folder named new in the c
drive then copy the path of the drive and paste it in the fopen() function with double
quotes and second quotes in r mode. You may create the folder in any name with any
drive to store. Since no data exists in a.txt file therefore NULL assigns to x and again x
is compared with NULL. As it matches the output is file does not present on hard drive.

15.7 RANDOM ACCESS TO FILE


In file we can access data in two ways i.e., sequential access and other is random
access. In sequential access if a person wants to access 10 th record then he has to visit
9th record before to reach the 10th record in sequential manner. But in case of random
access, if a person wants to access the 10th record then he does not need to visit each
record sequentially, he can directly access the 10th record. Random access takes less time
in comparison to sequential access. So random access is faster.
The random access file operation functions are:
388 Concepts and Techniques of Programming in C

15.7.1 fseek() Function


This function is used to move/place the file pointer to a desired location in the file.
The syntax is:
fseek(fp, offset, position);

EXPLANATION:
Here fp is a pointer to file, Offset is a number/variable of data-type long, Position is
the integer number.
The offset specifies the number positions/bytes to be moved from current location
to the specified location. The offset may be positive move or negative move. Positive
move means move forward and negative move means move backward.

Value Meaning

0 Starting of file
1 Current position
2 End of the file

Fig. 15.2 Positional value of fseek()function.

8. /*Examples of fseek() Function*/


#include <stdio.h>
void main (void)
{
FILE *x;
x=fopen(“c:\\new\\file.txt”,”w+”);
fputs(“Government College of Engineering, Keonjhar”, x);
fseek(x,2,2);
fputs(“ Concepts& Techniques of C programming”, x);
fclose(x);
}

15.7.2 ftell() Function


It tells the byte location of current position in file pointer.
#include <stdio.h>
void main (void)
{
FILE *x;
int len;
x=fopen(“c:\\new\\file.txt”,”w”);
if(x==NULL)
{
perror(“Error opening file”);
}
File 389

fseek(x,0,SEEK_END);
len=ftell(x);
fclose(x);
printf(“Total size of file.txt = %d bytes\n”,len);
}

15.7.3 rewind() Function


It moves the control to beginning of a file.

SUMMARY

1. A file is a place on the computer hard drive where the set of related data is stored.
2. A text file contains textual information where binary files are collection of bytes.
3. Different file operations are: creating a file, opening a file, reading a file, writing
a file and others.
4. The syntax of creating a file is
FILE *x;
5. The syntax of opening a file is
FILE *x;
X=fopen(“file name”,”mode”);
6. The file opening modes are: read mode, write mode, append mode, read and
write mode, write and read mode, append and read mode.

SHORT QUESTIONS

1. Write the general syntax for opening a file named as “sample.txt” stored in a hard
drive.
2. What is file?
3. What is the difference between text file and binary file.
4. What is fseek, ftell and rewind functions.
5. What is the difference between random acess and sequential access.
6. Write short notes on:
(a) getc() function
(b) putc()function
(c) getw() function
(d) putw() function
(e) fprintf() function
(f) fscanf() function.
390 Concepts and Techniques of Programming in C

LONG QUESTIONS

1. What kind of file accesses is possible with C programming? What are the different
modes that a file in C can be handled?
2. Write a program that reads the contents of a file and prints it on the screen.
3. Write a short note on error handling in file management.

MULTIPLE-CHOICE QUESTIONS

1. While opening a file if there is an error, the fopen() function will return____
(a) EOF (b) Nothing
(c) NULL (d) Depends on compiler
[Answer: c]
2. FILE is of ______ type?
(a) chart *type (b) int type (c) struct type (d) none
[Answer: c]
3. In the given syntax ‘a ‘stand for ___?
fp=fopen(“a.txt”,”a”);
(a) add (b) append (c) attach (d) apprehend
[Answer: b]
4. Which type of file cannot opened using fopen() function?
(a) .bin (b) .c (c) .txt (d) none
[Answer: d]
5. Which of the following causes an error?
(a) failure to allocate memory with the help of malloc.
(b) trying to read a file that does not exist.
(c) inability to write data in a file.
(d) all the above [Answer: d]
16
Preprocessor Directive

16.1 INTRODUCTION
The preprocessor directive instructs the compiler to preprocess the information before
the compilation starts. That is, C preprocessor modifies the programming code before
compilation by allowing the conditional compilation using #ifdef, defining the constant
value by using #define, including the header file by using #include directive. The
preprocessor directives are not statements therefore semicolon (;) is not required at the
end. The preprocessor directive is usually placed at the top of the source code with
starting character”#” followed by directive name and an optional white space before
and after it.
They are macro substation directives, Header file inclusion directive, conditional
compilation directive, and other directive.

16.2 DIFFERENT TYPES OF PREPROCESSOR DIRECTIVES


There are different types of preprocessor directives in c. They are macro substation
directive, header file inclusion directive, conditional compilation directive, and other
directives.

16.2.1 Macro Substation Directive


Macro substation is the process where the identifier is substituted by a predefined string
which consists of one or more tokes. The syntax of macro substitution is:
#define identifier string

There are different types of macro substitution directives, i.e., simple macro
substitution directive, argument macro substitution directive and nested macro
substitution directive.
The simple macro defines constant value and can be any of the basic fundamental
data types.
392 Concepts and Techniques of Programming in C

Example:
#define PI 3.14

16.2.2 Header File Inclusion Directive


The source code of the file “file_name” is included in the main program at the specified
place, i.e., #include along with the file name, e.g., library file which consists of different
categories of functions.
We can declare the header file in two different ways:
(a) #include<filename>
(b) #include”filename”
Example:
#include<stdio.h>
#include”stdio.h”
stdio.h means standard input output .header file.

16.2.3 Conditional Compilation Directive


The syntax of conditional compilation is: #ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in source program before compilation
with respect to the condition.

16.2.4 Other Directives


The syntax of other directive is: #undef, #pragma
#undef is used to undefine a defined macro variable. #Pragma is used to call a
function before and after the main function in a C program.

SUMMARY

1. The preprocessor directive instructs the compiler to preprocess the information


before compilation starts.
2. There are different types of preprocessor directives in C. They are macro substation
directive, header file inclusion directive, conditional compilation directive, and
other directives.
3. Macro substation is the process where the identifier is substituted by a predefined
string which consists of one or more tasks.
4. The source code of the file “file_name” is included in the main program at the
specified place.
Preprocessor Directive 393

SHORT QUESTIONS

1. What is preprocessor directive?


2. What are the different types of preprocessor directive?
3. What is macro substitution directive?
4. What is header file inclusion directive?
5. What is conditional compilation directive?

LONG QUESTION

1. What is preprocessor directive? Explain different types of preprocessor directives


with examples.

MULTIPLE-CHOICE QUESTIONS

1. The preprocessor directive starts with symbol_________


(a) @ (b) # (c) & (d) *
[Answer: b]
2. Which among the following is a preprocessor directive?
(a) header list (b) conditional list
(c) macro substitution directive (d) none
[Answer: c]
Appendix A

For successful run the C program in TURBO C Editor use the following key
1. For compilation press the key ALT and + F9.
2. For running the program press the key CTR and +F9
3. For displacing the output on computer screen press the key ALT and +F5

POINTS TO NOTE:
1. The header file #include<stdio.h> is called the preprocessor directive and its
purpose is to do input and output operation and inform to the c complier before
compilation.
2. The header file of printf(); function and scanf(); function is #include<stdio.h> .
3. The getch(); is a function used in the last portion of the program because when
any key is pressed it only displays the output. If we did not write in the program
then to display the output on the computer screen we can use the key: ALT
and +F5.
4. The header file of getch(); function is #include<conio.h>.
5. The keyword clrscr(); is used to clear the screen whose header file is #include<conio.
h>. After using it, when the programmer runs the program any number of times
then it does not show the previous output and it only displays the current output.
6. The most frequently used header files are:
#include<conio.h> or #include”conio.h” for clear screen and for
getch(); function.
#include<math.h> or #include”math.h” for mathematical operation.
#include<string.h> or #include”string.h” for group of character or
string related operation.
Bibliography

1. “Programming in ANSI C” by E. Balgurusamy, McGraw-Hill.


2. “Let us C” by Yaswant Kanitkar, BPB Publications.
3. Foundation Program, Volume 1, Infosys Technologies, Bangalore.
4. ”C in Depth” by S. K. Shrivastav and Deepali Shrivastav, BPB Publications.
Index

A C program using editor 44


Actual parameters 247 C program, basic structure of 42
Address (pointer) arithmetic 339 C programming language, features of 33
Algorithm designs 15 C programming, errors in 36
Algorithm, properties of 14 C, storage class in 263
advantages of 14 Cache memory 7
Application software 1 Call by pointer 249
Arithmetic Logic Unit (ALU) 4 Call by reference 249
Arithmetic operator 77 Call by value 248
Array 275 Called function 228
Array of pointer 347 calloc() function 349
Assembler 35 CD 7
Assignment operator 79 CD-ROM 8
Automatic variable 263 Central Processing Unit (CPU ) 4
B Character constant 68
Binary files 379 Character set 69
Binary representation 8 Command-line arguments 351
Bit 5 Compiler 34
Bit field 375 Complete algorithm 15
Bitwise operator 93 Computer, block diagram of 1
Branching statements 123 Conditional compilation directive 392
Break statement 208 Conditional operator 88, 123
Byte 5 Conditional statements 123
C Constants, types of 67
C operator 77 Continue statement 211
C program execution, internal structure of 45 Control Unit (CU) 4
400 Index

D free() function 350


Data types 71, 72 fscanf() function 386
Decimal representation 8 fseek() function 388
Decision making statements 123 ftell() function 388
Decrement operator 80 Function 220
Delimiters 114 Function call 228
Do while loop, programming examples of 182 Function prototyping (declaration) 227
concepts of 182 Function types 225
Dynamic memory management 348 Function, general structure of 229
E diagrammatic representation of 230
else-if statement/ladder, concepts of 136 with arguments and no return values 233
programming examples of 137 with arguments and one return values 234
Error 387 with no arguments and return values 234
Escape sequences 113 with no arguments and no return values 232
Evaluation, precedence of 98 G
order of, 98 Generic pointer 332
Executable code 35 getc() function 382
exit() statement 213 getchar() function 308
Explicit type conversions 97 gets() function 308
External variable 266 getw() function 385
F Global variable 251
File I/O operation 380 goto statement 209
File opening mode 381 H
File, random access to 387 Hard disk 7
Floppy disk 7 Hardware 1
Flowchart, advantages of 19 Header file inclusion directive 392
disadvantages of 19 Header files 113
symbols 20 Hexadecimal number system 10
examples 21 High level language 34
For loop, concepts of 186 I
multiple initializations in 187 I/O operation 387
For loop, programming examples of 189 Identifier 71
Formal parameters 247 if statement 124
Format specifications 112 programming examples of 125
Formatted input 114 if-else statement, concepts of 128
Formatted output 116 programming examples of 129
fprintf function 385 Implicit type casting 95
Index 401
Increment operator 80 Numeric constant 67
Input device 1 O
Input/output functions 382 Object code 35
Integer constant 67 Octal number system 9
Integer numbers, inputting 114 One-dimensional array 277
formatted output of 116 declaration of 277
Interpreter 34 initialization 278
K programming examples of 279
Keyboard 2 Operating system 35
Keywords 70 Output device 4
L P
Library functions 225 Parameter passing technique 248
Linker 35 Pass by address 249
Loader 35 Pass by pointer 249
Local variable 250 Pass by reference 249
Logical error 36 Pass by value 248
Logical operator 87 Pen drive 2
Looping, concept of 160 Pointer to array 344
Low level programming languages 34 Pointer to structure 371
M Pointer variable 326
Macro substation directive 391 declaration of 326, 328
main ( ) function 40 initialization of 328
Main memory 6 Pointer, as function arguments 337
malloc() function 349 and one-dimensional array 341
Memory 6 and multidimensional arrays 344
Modular program 220 Pointers, advantages 325
Monitor 4 Pointer-to-pointer declaration 332
Monolithic program 220 Preprocessor directives, types of 391
Mouse 3 Primary memory 6
N Problem solving methods 11
Nested for loop 188 Program, steps for writing a 37
Nested if-else statement, concepts of 133 putc() function 382
programming examples of 134 putchar() function 309
Nested structure 365 puts() function 309
Nibble 5 putw() function 385
Null pointer 330 R
Number system representation 8 RAM (Random Access Memory) 6
402 Index

Real numbers, output of 118 defining of 360


Real/float number, inputting 116 declaring of 360
realloc() function 350 array of 367
Recursion 251 Structure member, accessing 361
programming examples 252 passing of 368
Register variable 265 Structure variables, declaration of 361
Relational operator 86 initialization of 362
Return statement 229 Switch case statement 153
rewind() function 389 concepts of 145
ROM (Read Only Memory) 6 programming examples of 146
Runtime error 36 Symbolic constant 68
S Syntax error 36
Scanner 3 System software 1
Secondary memory 7 T
Selection statements 123 Three-dimensional arrays 300
Self-referential structure 372 declaration of 300
Single character constant 68 initialization of 300
Single character, reading of 109 Text files 379
writing of 111 Tokens 70
Software 1 Two-dimensional arrays, programming
Source code 35 examples of 292

Special operator 91 Type casting 95

Static variable 264 Type conversion 95

Storage unit 3 U
strcat() function 313 Union 373

strcmp() function 311 declaration of 373

strcpy() function 311 User defined function 226, 228, 232

String constant 68 V
String handling library functions 310 Variable, accessing a 331

String variable, declaration of 306 Variable, scope of 250

String, initialization of 306 declaration of 63

reading a 308 initialization of 65

writing a 309 W
displaying a 309 While loop, concepts of 161

strlen() function 310 programming examples of 162

strrev() function 314 Wrong pointer variable initializations 328

Structure 360

You might also like