Professional Documents
Culture Documents
FUNDAMENTAL
OF
COMPUTER PROGRAMMING
with more than 250 Lab Programs
J. K. Sharif
JHUNJHUNUWALA
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Copyright © By JHUNJHUNUWALA
Information contained in this book has been obtained by author, from sources believes to be
reliable. However, neither Jhunjhunuwala nor its author guarantee the accuracy or completeness
of any information herein, and Jhunjhunuwala nor its author shall be responsible for any
error, omissions, or damages arising out of use of this information. This book is published with
the understanding that Jhunjhunuwala and its author are supplying information but are not
attempting to render engineering or other professional services.
MRP 360.00
JHUJHUNUWALA
55, Suryalok Complex, Abids, Hyderabad – 500001
Ph : +91 40 64582577,
www.jhunjhunuwala.com
email : info@jhunjhunuwala.com
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
SYLLABUS
UNIT – 1
Programming in C: Structure of C Program, Concept of Preprocessor, Macro Substitution, Intermediate
code, Object Code, Executable Code. Compilation Process,
Basic Data types, Importance of braces ({ }) in C Program, enumerated data type, Identifiers, Scope of
Variable, Storage Class, Constants, Operators & Expressions in C, Type Casting, printf( ) and scanf ( )
with format specifires, reading single character.
UNIT – 2
Control Statements, Command Line Arguments, Arrays in C, Pointers, Using pointers to represent arrays,
Pointer & address arithmetic. Structures, using typedef.
UNIT – 3
Arrays of Structures & pointers, File Handling (fscanf, fprintf, feof, fopen, fclose, fread, fwrite only).
Dynamic memory Allocation.
UNIT – 4
Functions in C, Passing Parameters (By value & Reference), using returned data, Passing arrays,
structures, array of structures, pointer to structures etc., passing characters and strings, The void pointer.
UNIT – 5
Stored Program Architecture of Computers, Storage Device- Primary Memory and Secondary Storage,
Random, Direct, Sequential access methods. Concept of High-Level, Assembly and Low Level programming
languages. Representing Algorithms through flow chart, pseudo code, step by step.
Number System: Data Representation, Concept of radix and representation of numbers in radix r with
special cases of r=2, 8, 10 and 16 with conversion from radix r1 to radix r2. r’s and (r-1)’s complement,
Representation of alphabets.
Suggested Readings :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
PREFACE
This book is written for B. TEch 2nd semester syllabus of RTU, Kota. This book Fundamental
of Computer Pgoramming contains some special features to aid you on your path to learn
about fundamental concepts of computer and later programming with C in easy way. Each
chapter provides concrete examples and explanation of concepts. Numerous sample programs
illustrate C’s features and concepts, so that you can apply them in your computer lab with
ease. Each chapter ends with section containing review questions relating to the chapter with
reference to old year questions asked in university exams. It contains programming output quiz.
That tests your knowledge of the concepts and helps you to prepare for aptitude test conducted
by various software companies at the time of recruitment. You won’t learn Computer
Fundamentals and C just by reading this books, however. If you want to be a good computer
programmer, you’ve got to write programs in lab sessions. You can use Lab Programs for that.
We recommend that you attempt each exercise. Writing C code is the best way to learn C.
Unlike most other C books, this books, this books offers many sample programs and exercises
with clear explanations and answers, which makes the concepts of the C languages easier to be
understood. After reading this book, you’ll be able to write C programs on your own.
J. K. Sharif
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
CONTENTS
1 BASIC CONCEPTS
1.1 Introduction 1
1.2 Stored Program Architecture 1
1.3 Primary and Secondary Memory 2
1.4 Access Mechanism 3
1.5 Basic Model of Programming 4
1.6 Steps for Program Development 5
1.7 Algorithm 6
1.8 Flowchart 8
1.9 Pseudo Code 10
1.10 Programming Language Classification 11
1.11 Machine Language 11
1.12 Assembly Language 12
1.13 High Level Language 14
2 INTRODUCTION TO C
2.1 Introduction 17
2.2 Uses of C 18
2.3 Structure of a C program 18
2.4 C Programming Rules 20
2.5 Writing the first C Program 20
2.6 Files Used in a C Program 21
2.7 Compiling and Executing C Programs 23
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
6. DECISION MAKING
6.1 Introduction 82
6.2 If Statement 82
6.3 If Else Statement 86
6.4 Nested If 88
6.5 Using the If-Else Ladder 90
6.6 Switch Statement 91
7. ITERATION
7.1 Introduction 103
7.2 While Loop 105
7.3 Do While Loop 108
7.4 For Loop 109
7.5 Jump Statement 117
8. ARRAY
8.1 Introduction 129
8.2 Array 130
8.3 Type of Array 130
8.4 One Dimensional Array 130
8.5 Declaring One Dimensional Array 131
8.6 Storing Values in One Dimensional Arrays 132
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
9. STRINGS
9.1 Introduction 153
9.2 Understanding Strings in C 153
9.3 Declaring and Initializing a String 154
9.4 Reading and Displaying the Strings 155
9.5 Creating an Array of Strings 160
9.6 Performing String Operations 161
9.7 Using String Handling Functions 165
10. FUNCTIONS
10.1 Introduction 182
10.2 Function Declaration 184
10.3 Function Definition 185
10.4 Function Call 187
10.5 Passing Parameter to Function 189
10.6 Passing Array in Function 193
10.7 Recursive Function 197
10.8 Recursion vs Iteration 199
10.9 Storage Classes 200
10.10 Functions and Variables 202
12. POINTERS
12.1 Memory Organization 229
12.2 Understanding Pointers 230
12.3 Declaring a Pointer Variable 230
12.4 Using the Address of (&) Operator 231
12.5 Initializing a Pointer Variable 233
12.6 Dereferencing a Pointer 234
12.7 Performing Operation on Pointer 236
12.8 Null and Void Pointer 240
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
15 NUMBERS SYSTEMS
15.1 Number Systems 303
15.2 Number System Conversion 306
15.3 Summary of Number Conversion 316
15.4 Complements of Numbers 323
15.5 Data Representation in Binary 328
15.6 Floating Point data Representation 332
15.7 Representation of Alphabets 336
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
1
BASIC CONCEPTS
1.1 INTRODUCTION
All stored - program computer use the Von Neumann architecture. The
characteristics of stored-program machine are as follows :
• Consists of three hardware systems: A central processing unit (CPU)
with a control unit, an arithmetic logic unit (ALU), registers (small
storage areas), and a program counter; a main-memory system,
which holds programs that control the computer’s operation; and
an I/O system.
• Capacity to carry out sequential instruction processing.
ʇ NOTE
• Contains a single path, either physically or logically, between the This single path is often
main memory system and the control unit of the CPU, forcing referred to as the von Neumann
alternation of instruction and execution cycles. bottleneck.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
ʇ NOTE
1.3 PRIMARY AND SECONDARY MEMORY The primary memory itself
is implemented by two types
Primary memory, often called main memory, constitutes that device, of memory technologies. The
first is called Random Access
or group of devices, that holds instructions and data for rapid and
Memory (RAM) and the other
direct access by the computer’s central processing unit (CPU). The is read only memory (ROM).
processor or the CPU directly stores and retrieves information from A more appropriate name for
RAM is RWM (Read Write
it. This memory is accessed by CPU, in random fashion. That means Memory), the CPU can write
any location of this memory can be accessed by the CPU to either read and read information from
information from it, or to store information in it. any primary memory location
implemented using RAM. The
Secondary memory, also called auxiliary memory or mass storage, other part of primary memory is
consists of devices not directly accessible by the CPU. It stores the implemented using ROM which
data permanently unless it is erased. The secondary memory is usually stands for Read Only Memory.
available in the form of floppy disk storage media, hard disk, CD, DVD,
Pen drive (i.e. Mass storage devices), memory chips. The data on the
floppy disk is organized in terms of tracks and sectors. Hard disk can
have large capacity something like 80-300 GB’s or higher. Hard disk
itself is made up of, large number of platters. Hard disk is usually much
faster compared to floppy disk. CD can store up to 750 mb of data.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
flowchart. You can also divide a program into smaller sub-programs for
easier programming. This procedure is called refinement of the original
problem. You can define the data items, variables, and constants while
writing the code for the program.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
1.7 ALGORITHM
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
(c) Brackets ({}). The pair of braces is used to write comments for
the purpose of documentation. For example,
(a) BEGIN {Start of the algorithm}
(b) Set N ! N + 1 {Increase the value of N by 1}
(c) END {End of the algorithm}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Advantage of Algorithms
(1) It is simple to understand step by step solution of the problem.
(2) It is eacy to debug i.e., errors can be easily pointed out.
(3) It is independent of programming languages.
(4) It is compatible to computers in the sense that each step of
algorithm can be easily coded into its equivalent in high level
language.
1.8 FLOWCHART
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
total ! 0.0
count ! 0
for each input data value found
If data value > 0 (precondition: a data value was found)
total ! total + data value
count ! count + 1
Endif
Endfor
average ! total/count (precondition: positive data value was found)
print average
Stop
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
For example, a sequence of 0’s and 1’s such as 11001010 has a specific
meaning for a computer although it may appear as an ordinary binary
number to us.
Advantages of Machine Language
(1) Programs written in machine language can be executed very
fast by the computer because the instructions are understood
directly by the computer and no translating program is required.
(2) It is highly suited for small computers having limited memory.
Limitations of Machine Language
(1) Machine dependent. The machine language is machine dependent
i.e., it is different from computer to computer and depends
upon the actual design of the ALU (Arithmetic Logic Unit),
the Control Unit and the size as well as the word limit of the
memory unit.
(2) Difficult to use. It is difficult to understand and develop a
program using machine language. For any-body checking such a
program, it would be difficult to forecast the output when it is
executed. Nevertheless, computer hardware recognizes only this
type of instruction code.
(3) Error prone. It is hard to understand and remember the various
combinations of 1’s and 0’s representing data and instructions.
This makes it difficult for a programmer to concentrate fully on
the logic of the problem, thus frequently causing errors.
(4) Difficult to debug and modify. Checking machine instructions
to locate errors are about as tedious as writing the instructions.
Further, modifying such a program is highly problematic.
Following is an example of a machine language program for
adding two numbers.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Working of an Assembler :
An assembly language program i.e., the source program is fed to the
computer through an input device. The assembler program present in
the computer memory translates this source program to an equivalent
machine language program called the object program by translating
one instruction at a time.
In fact the assembler reads the program twice. During first reading
it develops the table of names used in the source program, assigns and
stores the numerical address for each name. Then in the second reading
it translates the instructions into machine language and generates the
object program. The object program is stored on the disk. The errors
in the program like syntax errors are also pointed out during assembly
process. Such an assembler is called Two-Pass Assembler. There is also
One-Pass Assembler which reads the assembly program only once.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
1.1 What do you mean by a program? 1.21 Write a algorithms to find the biggest of three
1.2 Distinguish between system software and application numbers.
software. 1.22 Given three sides A, B, C of a triangle. Write a
1.3 State the advantages and disadvantages of machine algorithms to find the area (if possible). S denotes
language and assembly language. the semi perimeter.
1.4 Compare and contrast assembly language and high- 1.23 Draw a algorithm for solving a given quadratic
level language. equation.
1.5 What are different phase of basic model of
programming?
1.6 Explain different types of computer language in FLOWCHARTS
details.
1.7 What is pseudocode. Write the advantage ane 1.24 Draw a flowchart for swapping two numbers without
limitation of pseudocode. using a temporary variable.
1.8 State the advantages and disadvantages of machine 1.25 Draw a flowchart for checking a year for leap year.
language and assembly language. (If a year is divisible by 4 and not divisible by 100,
1.9 What is a translator? or, if the year is divisible by 400, it is a leap year)
1.10 What are the differences between a compiler and 1.26 Draw a flowchart to find out the biggest of three
an interpreter? numbers.
1.11 What is a structured code? 1.27 Draw a flowchart for printing the multiplication
table of an integer.
1.12 What is an algorithm?
1.28 Draw a flowchart for generating first n _n $ 2i
1.13 What is top-down analysis? Describe the steps
fibonacci terms (Fibonacci terms are 0, 1, 1, 2, 3,
involved in top-down analysis.
5, 8, 13, 21 ...).
1.14 What are the advantage and disadvantage of
1.29 Draw a flowchart for checking an integer for prime
flowcharts?
number.
1.15 What are the benefits of algorithms. Describe the
1.30 Draw a flowchart for solving a given quadratic
characteristic of good algorithms.
equation.
1.16 What is the difference between compiling and
1.31 Draw a flowchart for finding the area of a triangle
linking?
and its type (that is equilateral, isosceles or scalene).
1.17 What is bug?
1.32 Draw a flowchart for simulating a simple calculator
1.18 What do you mean by language translator. Explain (that is performing +, –, ×, /).
with example.
1.33 Draw a flowchart describing the process of creation
1.19 Differentiate ROM and PROM. to execution of a program.
1.20 List the most important differnece between 1.34 Draw a flowchart for finding the biggest and smallest
(1) Assembler, Compiler and Interpreter of given set of numbers in an array.
(2) Machine, Assembly and High Level Language 1.35 Draw a flowchart for addition of two matrices.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
2
INTRODUCTION TO C
2.1 INTRODUCTION
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
2.2 USES OF C
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
user_defined_funcion()
(
/* comments */
Declaration part
Executable part
}
/****************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
To write a C program, we first need to write the code. For this, open
ʇ NOTE
a text editor. If you are a Windows user you may use Notepad Once Unix\Linux user can use emacs
the text editor is opened on your screen, type the following statements: or vi.
/*****************************************************************************/
#include <stdio.h>
int main()
{
printf(“\nWelcome to the world of C”);
return 0;
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Welcome to the word of C
Every C program has four kinds of files associated with it. These are
shown in figure 2.2.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
the various object files to produce a binary file that can be directly
executed. On Windows operating system, the executable files have
‘.exe’ extension.
ʇ NOTE
2.7 COMPILING AND EXECUTING C PROGRAMS While the C program is human-
readable, the executable file on
C is a compiled language. So once the C program is written, you must the other hand, is a machine-
readable file available in an
run it through a C compiler that can create an executable file to be run
executable form.
by the computer. The process of compilation and execution is shown
in figure 2.3.
Creating of Program :
The program should be written in C editor. The file name does not
necessarily include extension .C. The default extension is .C. The user
can also specify his own extension.
ʇ NOTE
Compilation and Linking a Program : All the given steps can be
performed using menu options
With alt-c keys, the source program statements should be translated of the editor.
into object program, which is suitable for execution by the computer.
The translation is done after correcting each statement as per C syntax.
If there is no error, compilation proceeds and translated program is
stored in another file with the same file name, but with an extension
.obj. If at all errors are there, the programmer should correct them.
The linking is also an essential process. It puts all other program files
and functions together that are required by the program. For example,
if the programmer is using pow() function, then the object code of
this function should be brought from math.h library of the system and
linked to the main() program.
Executing the Program :
After the compilation, the executable object code will be loaded in the
computers main memory and the program is executed. This is done
with keys alt-r.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
3.3 TOKENS
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Keyword Description
Auto Defines a local variable having local lifetime
break Allows to pass the control out of block
case Used in switch statements to mark blocks of text
char Refers to a data type that holds characters
const Used to define constants
continue Sends control back to the top of a loop
default Specifies the default block of code in a switch statement
do starts a do-while loop
double Refers to a data type that holds 64-bit floating-point numbers
else Indicates an alternative branch in the if statement
enum Refers to a class of constants that represents fixed choices
extern Indicates that an identifier is defined elsewhere
float Represents a single precision floating point data type
for Provides iteration facility repeatedly
goto Used to jump the control from one part of program to another
if Used to execute specified statements if the specified condition is true
int Refers to a data type that holds integer type values
long Refer to a data type that holds the long type values
register Informs the compiler Ato store the variable that is declared in a CPU register
return Returns the value to calling function
short Refers to the type modifier
signed Refers to the type modifier that holds the signed type values of a data type
sizeof Returns the size (in bytes) of a specified parameter
static Preserves the value of a variable even after its scope ends
struct Groups variables in a single record
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Keyword Description
switch Represents multiple branching statement
typedef Assigns symbol name to data type definition
union Groups the variables sharing the same storage space
unsigned Refers to the type modifier that holds the unsigned type values of a data type
void Represents the empty data type
volatile Indicates that variable can be changed by background routine
while Repeats the execution of a block, if the condition remains true
ʇ NOTE
3.3.2 Identifiers Identifiers, as the name suggests
helps us to identify data and
Identifiers are basically the names given to program elements such as other objects in the program.
variables, arrays, and functions. Identifier may consist of an alphabet,
digit, or an underscore.
Rules for Forming Identifier Names :
Some rules have to be followed while forming identifier names. They
are as follows:
(1) Identifier name must begin with an alphabet or an underscore.
(2) It cannot have a C reserved keyword.
(3) It cannot include any special characters or punctuation marks
(like #, $, ^, ?, ., etc.) except the underscore ‘_’.
(4) There cannot be two successive underscores.
(5) The case of alphabetic characters that form the identifier name
is significant. For example, “FIRST” is different from ‘first’ and
‘First’.
PROGRAMMING TIPS
(6) Identifiers can be of any reasonable length. They should not Although it is a good practice to
contain more than 31 characters. It can actually be longer than use meaningful identifier names,
31, but the compiler looks at only the first 31 characters of the it is not compulsory. Good
identifiers are descriptive but
name. short. To cut short the identifier,
As a general practice, if the identifier is a little long, then you may you may use abbreviations.
use an underscore to separate the parts of the name or you may use
capital letters for each part.
Examples of valid identifiers are:
roll_number, marks, name, emp_number, basic_pay,
ltc, hra, DA, dept_code, DeptCode, RollNo, EMP_NO
ʇ NOTE
Examples of invalid identifiers are: C is a case-sensitive language.
Therefore rno, Rno, RNo,
45_student, %marks, @name, #emp_no,
RNO are different considered as
basic.pay, -HRA, (DA), &dept_code, auto identifiers.
3.3.3 Constants
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
ʇ NOTE
A constant is a fixed value assigned to a variable, which cannot be Later we will discuss in details
modified in a program. It can be a number, character, or a character about constants.
string that may be used in a program. The constants are also known as
constant literals. In the C program, you can declare a constant by using
the const keyword, as shown in the following statement:
const int id_number = 2474;
In this statement, the id_number is a constant variable declared
by the const keyword and it is assigned as a fixed value, 2474. You
cannot modify the value of a constant in a program.
3.3.4 Strings
The string literals are the characters from the source character set and
are enclosed within the double quotation marks (“ ”). The following
statement shows a simple string literal:
char *display = “Computer Programming”;
In this statement, the char type pointer, display, is declared and
assigned the string Literal value.
ʇ NOTE
3.3.5 Operators We will discuss in detail about
operator in next chapter.
The word operator explains itself as something that is used to perform
some operation. Any expression consists of an operator and operand.
An operator acts upon the operand. In the C language, there are the
following three types of operators:
(1) Unary Operators: Consists of a unary operator pre-appended
with an operand.
(2) Binary Operators: Consists of two operands joined by the binary
operator.
(3) Ternary Operators: Consists of three operands joined by the
conditional expression operator.
Within the binary operators, the arithmetic operators are the most
commonly-used operators. The following are the arithmetic operators
used in a C program:
Operator Operation
* Multiply
+ Addition
/ Division
- Subtraction
% Modulus
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
A data type defines the type of data that is stored in a variable. The
data in a variable can be of any type. For example, the data can be
either numeric or string. A data type determines how much storage
should be allocated to a variable. It also determines the permissible
operations on variables. C has some built-in data types for which the
programming language offers built in support. The built-in data types
are also called basic or primary data types. Table 3.4 lists the built-in
data types supported by C on a 16 bit machine.
Apart from these built-in data types, the C language also offers
other data types, which are called data type modifiers or data qualifiers.
The data modifiers provide precision to the data.
ʇ NOTE
3.4.1 char Data Type ASCII is acronym for the
American Standard Code for
The char data type is used to store character type data. A char data Information Interchange. It is
type takes 1 byte for storage. It can store data that can be either a a code for representing english
characters as numbers, with
character constant or a string constant. each letter assigned a number
A character constant is a single character enclosed within a from 0 to 127. For example, the
pair of single quotes. For example ‘A’, ‘s’, ‘@’, ‘4’. The character ASCII code for uppercase M is
77. Most computers use ASCII
constant can be either signed or unsigned. The signed characters are codes to represent text, which
those characters that have values in the range of -128 to +127 whereas, makes it possible to transfer
the unsigned characters have values in the range from 0 to 255. Each data from one computer to
another.
character constant contains an integer value, which is provided by
the ASCII (American Standard Code for Information Interchange)
character set. Table 3.5 lists some of the character constants along with
their corresponding ASCII values:
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
ʇ NOTE
3.4.3 float Data Type The scientific notation, also
called the mantissa-exponent
The float data type is used to store real numbers that have a single notation, is a method of writing
precision floating point. Floating-point numbers are numbers that numbers that holds values
that are too large or small to
contain a decimal point either to the left or to the right of an integer. be written easily in standard
These numbers can be expressed in decimal notation (in the form of decimal notation.
decimals) or in scientific notation. Table 3.7 lists some valid and invalid
floating-point numbers:
Valid Invalid
-261.218 4,4 (comma not allowed)
2.43130E+02 -1.8.9 (two decimal points are not allowed)
0.0233333E+04 -999999999.999999 (out of valid range )
25313.8E+04 -+18.88 (two successive operators are not allowed)
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
3.5 CONSTANTS
In figure 3.3, sign indicates the optional plus or minus sign. Integer
portion is a sequence of numbers prior to a decimal point. Decimal point
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Multiple Assignment :
You can assign a single initial value to multiple variables using a
single assignment statement. This type of initialization requires more
than one assignment operator. Therefore, such assignments are called
multiple assignments. Let’s now take an example in which you initialize
three variables a, b, and c of int data type with the value as 20.
The following statements snippet shows the initialization of the three
variables by using the single assignment statement:
int a = 20;
int b = 20;
int c = 20;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
The first example indicates the compiler that the value stored
in the float variable PI is 3.142, which you cannot change during
the execution of a program. Similarly, the second example instructs
the compiler that the constant value in the variable size must not be
changed during the program execution.
In the above statements, the first example indicates that the value
of the variable b can be changed any time by any external factor.
Similarly, the second example indicates that the values in the integer
array y can be changed in many ways, and by any factor undetected by
the C compiler.
All the built-in data types except the void data type can easily be
ʇ NOTE
modified by using a series of type modifiers. As you know, the double The data type modifiers are also
data type is used for accuracy in real numbers. Similarly, you can known as qualifiers.
obtain accuracy for integer type data by using some modifiers. The
data type modifiers are divided into the following four types:
3.8.1 Signed
It indicates that the value stored in a variable is capable of storing
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
ʇ NOTE
negative values. The signed characters are those characters that have By default, in case a data type
values in the range of -128 to +127. The signed data type modifier also modifier is not specified, then
the signed data type modifier is
applies to a char data type to create a small integer. In some cases, char applied to all data types except
is declared unsigned, which means that it can contain integers from 0 the void data type.
to 255. The following statement declaring an int data type as signed is:
signed int y;
3.8.2 unsigned
It indicates that the value stored in a variable is capable of storing only
positive values. The unsigned characters are those that have values in
the range of 0 to 255. For example, the age of a person can never be
a negative number. Therefore, when you declare the variable age, the
following statement is used to declare the variable as unsigned:
unsigned int age;
3.8.3 long
In a C program you can increase the storage capacity of a variable from
the storage capacity of the basic data type. For that, you must use
the data type modifier long. Using the long data type modifier, you
can double the storage capacity of the data type that you are using
to declare a variable. For example, the following statement is used to
declare a variable salary of int data type with the long data type
modifier:
long int salary;
By default, an int data type has a storage capacity of 2 bytes,
but when you use a long data type modifier with the int data type the
storage capacity increases to 4 bytes. Therefore, in the above statement,
the variable salary now has a storage capacity of 4 bytes.
3.8.4 short
A short data type modifier reduces the storage capacity of a data type
to half of its basic storage capacity. Let’s again take the example of the
age variable. The following statement is used to declare the variable
age of int data type with the short data type modifier:
short int age;
With the above statement, the variable age now has a storage
capacity of 1 byte and has a data range of 128 to 127. Table 2.9 list
the storage capacity and the range of values these data type modifiers
have in combination with the data types on a 16 bit computer:
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
TABLE 3.9 : Data Type Modifiers along with their Size and Range on a 16 bit Computer
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
3.11 DELIMITERS
Closing bracket )
Opening braces {
Closing braces }
Comma ,
Semicolon ;
Colon :
Period .
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
The unary operators in C are used to act upon only one operand, to
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
produce a new value. The unary operators appear before the operand
and are associated with the operand from left to right. The most
commonly used unary operator in C is the unary minus operator. In
the unary minus operator, a minus sign precedes the operand assigning
a negative value to the operand. For example,
a = 3;
b = 4;
c = a + (-b);
/*****************************************************************************/
/* Program 4.1 : Using the Unary Operator */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int a , b;
int sub;
a = 5;
b = 3;
sub = a + -b;
printf(“The subtraction of a and b is = %d.“, sub);
getch();
}
/*****************************************************************************/
OUTPUT :
The subtraction of a and b is 2.
EXPLANATION :
When you run the Program 4.1, you get the output as 2. This is because, b. which is
a positive value, is assigned a negative unary operator.
ʇ NOTE
4.4 ASSIGNMENT OPERATORS Here you may be confused
by the statement a=a+c.
Assignment operators are used for assigning a new value to a variable. In programming this is not
equality. Here it mean that
The equal sign (=) is the assignment operator in C. When the C
we have assign a+c to a. For
compiler encounters an = sign, it processes the statement on the right example if value of a and c are
side of the operator and then assigns the result to the variable on the 4 and 5, then after execution of
this statement value of a will be
left side of the operator. 4+5=9.
The general format for an assignment operator is
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
var = expression;
Some example of assignment operator are shown below
a = a + c; a = b + c*d;
i = i + 2; i = j + 2;
/*****************************************************************************/
/* Program 4.2 : Using the Assignment Operators */
/*****************************************************************************/
#include<stdio.h>
main()
{
int a,b,c,d;
printf(“ENTER VALUES OF a,b, c, d :\n”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
a = a + b*c + d;
printf(“\na = %d”,a);
getch();
}
/*****************************************************************************/
OUTPUT :
ENTER VALUES OF a,b, c, d :
5 5 7 8
a = 48
EXPLANATION :
When you run the expression given in Program 4.2, you are asked to provide values
for a, b, c, and d. As you provide the values, a computed value of a is displayed. You
will get the value 48, which is evaluated in the following manner:
1. 5*7 gives 35.
2. 5+35+8 gives 48 which is assign to a.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 4.3 : Using the Shorthand Assignment Operators */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int x, y, z;
printf(“\nEnter Values of x, y, z : ”);
scanf(“%d%d%d”,&x,&y,&z);
x+=y; /* Statement A */
y-=z; /* Statement B */
z*=x; /* Statement C */
printf(“\nx = %d”, x);
printf(“\ny = %d”, y);
printf(“\nz = %d”, z);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter Values of x, y, z: 5 8 10
x = 13
y = -2
z = 130
EXPLANATION :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Program ask to enter the values of x, y and z. After the statement A the value of
x(5+8) is 13. After the statement B the value of y (8-10) is -2. After the statement
C the value of z (10*13) is 130.
C has all the basic type of arithmetic operators. They are listed in
Table 4.2.
/*****************************************************************************/
/* Program 4.4 : Using the arithmetic operators */
/*****************************************************************************/
#include<stdio.h>
main()
{
int a,b,c,d;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Enter Values of b, c, d : 10 5 3
sum = 15
sub = 5
mul = 50
div = 2.000000
Remainder of division of b & d is 1.
a = 6
EXPLANATION :
In Program 4.4 you have the expression a = b/c * d. In this expression both / and
* have the same priority. Since, the expression is evaluated from left to right, so first
b/c is evaluated. After evaluating the expression b/c * d, the value is assigned to a
because the assignment operator has an order of evaluation right to left, which implies
that the right expression in first evaluated.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 4.5 : Using the Increment and Decrement Operators */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int i, j, k, l, m, n;
i = 7;
j = 3;
k = i++ + -j;
l = ++i + -j;
m = i-- + -j;
n = --i + -j;
printf(“i = %d,\tj = %d”, i, j);
printf(“\nk = %d, \tl = %d, \tm = %d, \tn = %d”, k, l, m, n);
getch();
}
/*****************************************************************************/
OUTPUT :
i = 7, j = 3,
k = 4, l = 6, m = 6, n = 4
EXPLANATION :
In Program 4.5, first value of i = 7 is used and then incremented. So we get the
value of k as follows
k = 7 + -3 = 4
Now the value of i is 8. In next statement value of i first incremented and then used.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 4.6 : Using the Relational Operators */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int x, y;
printf(“\nEnter value of x and y :”);
scanf(“%d%d”,&x,&y);
if(x == y)
printf(“x and y are equal.\n”);
if(x < y)
printf(“x is less than y.\n”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
if(x > y)
printf(“x is greater than y.\n”);
getch();
}
/*****************************************************************************/
OUTPUT :
Run 1
Enter value of x and Y : 56 78
x is less than y.
Run 2
Enter value of x and Y : 45 23
x is greater than y.
Run 3
Enter value of x and Y : 45 45
x and y are equal.
EXPLANATION :
Program is self explanatory. Depending on the value of x and y, respective message
is displayed.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 4.7 : Using the Logical Operators */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int x, y, z;
printf(“\nEnter Values of x, y and z : ”);
scanf(“%d%d%d”,&x,&y,&z);
if((x < y)&&(x < z))
printf(“\nx is less than y and z.”);
if(!(x < y))
printf(“\nx is greater than y.”);
if((x < y)||(x < z))
printf(“\nx is less than y or z or both.”);
getch();
}
/*****************************************************************************/
OUTPUT :
RUN 1
Enter Values of x, y and z : 16 91 33
x is less than y and z.
x is less than y or z or both.
Run 2
Enter Values of x, y and z : 34 23 43
x is greater than y.
x is less than y or z or both
Run 3
Enter Values of x, y and z : 54 23 12
x is greater than y.
EXPLANATION :
When you run the program in Program 4.7, you are asked to enter the values for x,
y, and z, based on which the result will be returned.
As the name suggest, bitwise operator are those operators that perform
operations at bit level. These bitwise operators assume operands as
ʇ NOTE
string of bits and the bit operations are done on this operand. The Bitwise operator may not be
different bitwise operators have been explained in detail in Table 4.5: applied to float or double.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Operator Explanation
& Compares each bit of the first operand with the corresponding bit of the second
operand. If both bits are 1, then the corresponding bit is set to 1, else it is set to 0.
| Compares each bit of the first operand with the corresponding bit of the second
operand. If either of the bit is 1, the result is set to 1, otherwise the result is set to 0.
^ Compares each bit of the first operand with the corresponding bit of the second
operand. If one bit is 0 and the other bit is 1, the result is set to 1, otherwise the
result is set to 0.
~ Assigns every bit that is 1 in the operand as 0 in the result and vice-versa.
<< Shifts their first operand to its left.
>> Shifts their first operand to its right.
/*****************************************************************************/
/* Program 4.8 : Using the Conditional Operator */
/*****************************************************************************/
#include<stdio.h>
void main ()
{
int a = 35;
int b = 95;
int result1;
int result2;
result1 = a > b ? a : b;
result2 = a < b ? a : b;
printf(“The value of result1 is =%d\n”, result1);
printf (“The value of result2 is = %d\n”, result2);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
getch();
}
/*****************************************************************************/
OUTPUT :
The value of result1 is = 95
The value of result2 is = 35
EXPLANATION :
In this program a > b is false and a < b is true. So in first case b is selected and in
second case a is selected.
Along with the preceding operators, there are also some special operators
that are used in C. The special operators in C are used to perform
certain special functions, for instance combining multiple expressions
into a single expression. The special operators in C are:
1. The comma operator
2. The sizeof() operator
/*****************************************************************************/
/* Program 4.9 : Using the Comma Operator */
/*****************************************************************************/
#include<stdio.h>
main()
{
int i, j, k;
k = (i = 4, j = 5);
printf(“i = %d , j = %d, k = %d”, i, j, k);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
i = 4, j = 5, k = 5
EXPLANATION :
Here, the expression is evaluated from left to right, that is i = 4 is evaluated first,
then j = 5 is evaluated. The value of right most expression is specified as output;
therefore, k will get the value 5.
/*****************************************************************************/
/* Program 4.10 : Using the sizeof() Operator */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int x;
float y;
x = 1000;
y = 800.0;
printf(“size of x = %d\n”, sizeof(x));
printf(“Size of y = %d\n”, sizeof(y));
getch();
}
/*****************************************************************************/
OUTPUT :
size of x = 2
size of y = 4
EXPLANATION :
Since x is integer so it require 2 bytes of storage and y is float which require 4 byte,
so the output is 2 and 4.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
of the operators with respect to each other that determine the order in
which the expression will be evaluated.
Associativity defines the direction in which the operator having the
same precedence acts on the operands. It can be either left-to-right or
right-to-left. Priority is given precedence over associativity to determine
the order in which the expressions are evaluated. Associativity is then
applied, if the need arises.
Table 4.6 lists the operators that C language supports in the order
of their precedence (highest to lowest). The associativity indicates the
order in which the operators of equal precedence in an expression are
evaluated.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 4.11 : Calculation of simple interest and compound interest */
/*****************************************************************************/
#include <stdio.h>
#include <math.h> /* For the function pow */
void main()
{
float p, t, r, ncmp_year;
float simple, compound, cmp_amount;
printf(“\nPrincipal : ”);
scanf(“%f”, &p);
printf(“Rate : ”);
scanf(“%f”,&r);
printf(“Time : ”);
scanf(“%f”, &t);
printf(“Compoundings per year : ”);
scanf(“%f”, &ncmp_year);
simple = p * t * r/100;
/* Calculate the amount resulting from compound interest. */
cmp_amount = p * pow(1 + r/(ncmp_year*100), ncmp_year * t);
/* Compute the compound interest from the amount and principal */
compound = cmp_amount - p;
printf(“\nThe simple interest is: %f”, simple);
printf(“\nThe compound interest is: %f”, compound);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Run 1:
Principal : 2000
Rate : 12
Time : 3
Compoundings per year : 4
The simple interest is : 720.000000
The compound interest is : 851.521729
ʇ NOTE
4.13 TYPE CONVERSION AND TYPECASTING Type conversion is implicit
type conversion, also known as
Till now we have assumed that all the expressions involved data of the coercion. It is an automatic type
conversion by the compiler
same type. But what happens when expressions involve two different
whereas, typecasting has to
data types, like multiplying a floating point number and an integer. be done explicitly by the
Such type of situations are handled either through type conversion or programmer.
typecasting.
Type conversion or typecasting of variables refers to changing a
variable of one data type into another. Type conversion is done implicitly
whereas, typecasting has to be done explicitly by the programmer.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
4.13.2 Typecasting
Typecasting is also known as forced conversion. Typecasting an
ʇ NOTE
arithmetic expression tells the compiler to represent the value of the Typecasting is done to make a
expression in a certain way. This cast is under the programmer’s control variable of one data type to act
like a variable of another type.
and not under compiler’s control. For example, if we need to explicitly
type cast an integer variable into a floating point variable, then the
code to perform type casting can be given as,
float salary = 10000.00;
int sal;
sal = (int) salary;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 4.12 : To convert a floating point number into the integer */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
main()
{
float f_num;
int i_num;
clrscr();
printf(“\nEnter any floating point number : ”);
scanf(“%f”, &f_num);
i_num = (int)f_num;
printf(“\nThe integer variant of %4f is = %d”, f_num, i_num);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter any floating point number : 63.45
The integer variant of 63.450000 is = 63
/*****************************************************************************/
/* Program 4.13 : To convert a floating point number into the integer */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
main()
{
float f_num;
int i_num;
clrscr();
printf(“\nEnter any integer: “);
scanf(“%d”, &i_num);
f_num = (float)i_num;
printf(“\nFloating point variant of %d is = %f”, i_num, f_num);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter any integer: 24
Floating point variant of 24 is = 24.00000
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Function Action
abs(ival) Returns the absolute value of ival
acos(x) Returns the cos value of x [cos-1 (x)]
asin(x) Returns the sin value of x [sin-1 (x)]
atan(x) Returns the tan value of x [tan-1 (x)]
atan2(x, y) Returns the tan value of x/y [tan-1 (x/y)]
cos(x) Returns the cos value of x
cosh(x) Returns the hyperbolic cos value of x
exp(x) Returns the e to the power x value
fabs(x) Returns the absolute value of x
floor(x) Returns the nearest round value of x
fmod(x, y) Returns the floating point reminder value of x/y
log(x) Returns the logarithm value of x
log 10(x) Returns the logarithm value with base 10 of x
pow(x, y) Returns x to the power y
sin(x) Returns the sin value of x
sqrt(x) Returns the square root value of x
tan(x) Returns the tan value of x
/*****************************************************************************/
/* Program 4.14 : Using Mathematical Functions */
/*****************************************************************************/
#include <stdio.h>
#include <math.h>
void main ()
{
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
float x, y;
float square;
float sinx;
float cosx;
float tanx;
printf(“Enter value of x in Degree < 90 : “);
scanf(“%f”, &x);
square = sqrt(x);
y = x*(3.142/180.0);
sinx = sin(y);
cosx = cos(y);
tanx = tan(y);
printf(“\nSquare root of x = %f”, square);
printf(“\nsine value of y = %f”, sinx);
printf(“\ncosine value of y = %f”, cosx);
printf(“\nTangent value of y = %f”, tanx);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter value of x in Degree < 90 : 60
Square root of x = 7.745967
Sine value of y = 0.866093
Cosine value of y = 0.499882
Tangent value of y = 1.732954
The header files in C are used to contain C declarations and are included
in the head of your C program. The header files have a .h extension.
The header file contains prototypes of the different library functions
included in C. For example, the prototypes for all the mathematical
functions are stored in the math.h header file and all the declarations
for the input and the output functions are included in stdio.h header
file. The commonly used header files in C are listed in Table 4.8.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
The syntax of using the preprocessor directive and the header file
in a C program is:
#include <stdio.h>
You observe that the header file is enclosed within angular (<>)
brackets. You can also include the header file within a pair of double
quotes (“ ”). as shown in the following syntax:
#include “stdio.h”
The difference between the two is that, when the header file is
included within a pair of angular brackets, the file is searched only in
standard directives. When the header file is included within a pair of
double quotes, the file is first searched within the specified directory
and then in the standard directories.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
4.7 Describe bitwise operators in C. Each with an 4.4 Identify the errors in the following code.
example. #include<stdio.h>
4.8 List the different type of operators in C. Discuss the #include<conio.h>
main()
following with examples. (a) Conditional operators {
(b) Relational operators. int a=6,c=7,d=8,n=9;
4.9 Discuss the concept of precedence of operators in C float ans;
ans=l0.2/a+(2*a+(3c+4)/a*d/(12/n);
language with examples. clrscr();
4.10 Give the operator precedence chart. printf(“%f”, ans);
getch();
4.11 Explain various unary operators in C. }
4.12 What do you understand by type casting? Give 4.5 The following program is not displaying the correct
example of explicit and implicit type casting. output. Identify the errors.
4.13 Differentiate between typecasting and type #include<stdio.h>
conversion. #include<conio.h>
main()
4.14 When will you use cast operator? Illustrate its use.
{
int num;
clrscr();
printf(“Enter a number: ”) ;
PROGRAM OUTPUT scanf(“%d”, &num) ;
(num=1?printf(“The number entered is 1”);
printf(“The number entered is not 1”));
4.1 The following code is not displaying the correct getch();
output, which is 3600. Identify the error. }
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
} printf(“%u”, i-*i);
getch();
4.8 What is the output of the following code?
}
#include<stdio.h>
void main() 4.15 What is the output of the program?
{ #include<stdio.h>
int var=6234.5678; #include<conio.h>
printf(“%d”, var); void main()
} {
int i=4;
4.9 What is the output of the following code? clrscr();
#include<stdio.h> printf(“%d”, i++*i++);
void main() printf(“\n%d”, ++i*++i);
{ getch();
int var1=15,var2=10,p,q; }
p=var1>14;
q=var1>8 && var2==8;
4.16 What is the output of the program?
printf(“p=%d q=%d”, p,q); #include<stdio.h>
} #include<conio.h>
void main()
4.10 What is the output of the following code? {
#include<stdio.h> int i=6, j=9;
main() clrscr();
{ j = j || (i++ && printf(“HELLO RTU”));
int var=--4; printf(“%d%d\n”, i, j);
printf(“var = %d”,var); getch();
} }
4.11 What is the output of the following code? 4.17 What is the output of the program?
#include<stdio.h> #include<stdio.h>
main() #include<conio.h>
{ void main()
float flt=l5,g=10; {
enum{var1=l0,var2=20,var3=50}; int x;
printf(“%d\n”,++var3); clrscr();
printf(“%f\n”,flt<<2); x=~!printf;
printf(“%lf\n”,flt%g) ; printf(“%x”,x);
printf(“%lf\n”,fmod (flt,g)); getch();
} }
4.12 What is the output of the following code? 4.18 What is the output of the program ?
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int var=6; short m=8, n=0, p=0;
printf(“%d”, var=++var==7); p+=n+=m;
p+=n+=m+=-p;
}
printf(“m=%d n=%d p=%d”, m, n, p);
4.13 What is the output of the following code? }
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
{ printf(“%d”,++j);
int i; }
clrscr();
printf(“i=%d\n”,i); 4.26 What is the output of the following program ?
printf(“j=%d\n”,j); #include<stdio.h>
printf(“k=%d”,k); #include<conio.h>
} main()
{
4.21 What is the output of the following program ? int j = 0xff;
#include<stdio.h> clrscr();
#include<conio.h> printf(“j=%d”, j<<2);
main() }
{
int i=6; 4.27 What is the output of the following program ?
clrscr(); #include<stdio.h>
i++= 1; #include<conio.h>
printf(“%d”, i); void main()
} {
4.22 What is the output of the following program ? float j=‘A’;
clrscr();
#include<stdio.h> printf(“j=%d\n”,j%2);
#include<conio.h> }
void main()
{ 4.28 What is the output of the program ?
char a=200; #include<stdio.h>
signed char b=200; main ()
unsigned char i=200; {
char j=200; int num1 = 10, num2 = 20;
clrscr(); num2=num1, num2?(num1,num2)?num1:num2:num2;
printf(“i=%d j=%d\n”, i, j); printf(“%d %d”,num1,num2);
printf(“a=%d b=%d”, a, b); }
}
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 5.1 : Using the printf() Function */
/*****************************************************************************/
#include <stdio.h>
int main()
{
int i = 0;
i = printf(“\nabcde”); /* statetment A */
printf(“\nTotal characters printed %d.”, i); /* statetment B */
return 0;
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
abcde
Total characters printed 6.
EXPLANATION :
In this program, Statement A prints 6 characters and return 6 which is assign to i.
Statement B prints the value of i as 5. Here note that 5 character are printed but
compiler also recognise \n as newline character. So it return 6. If we remove \n, it
will return 5.
Place holders are used to print the values of arguments specified in the
printf() function. The directives in place holders control printing. The
general form of a place holder is:
% flags field_width precision type_prefix type_identifier
Type-identifiers Description
d, i Represents signed integers.
o Represents unsigned integers displayed in octal form
u Represents unsigned integer in decimal form
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Type-identifiers Description
x Represents unsigned integer in hexadecimal form and hexadecimal
characters such as a, b, c, d are printed in lowercase.
X Represents unsigned integer in hexadecimal form form and hexadecimal
characters such as A, B, C, D are printed in uppercase.
c Converts any value to an unsigned char and displays it. It is used mainly
for printing characters.
s Converts the argument into a character array and prints it; last null in
the string characters
f Prints floating point
e, E Represents floating point in exponential form. It has one digit to the left
of the decimal point; the number of digits on the right side of decimal
point depends on the required precision.
g, G Prints a floating point number in exponential form. The exponential
form is used if the exponent is less than -1. However, these both are
slightly different in functionality.
n Prints the number of characters, which are printed so far by printf
function.
p Specifies the value of a pointer.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
5.4.3 Field-width
Field-width indicates the least number of columns that are allocated to
the output. For example, if you write %4d to i and the value of i is 10
then 4 columns are allocated for i and 2 blanks are added on left side
of the value of i, so the output is bb10. Here, we are representing b
to indicate blank space. If the value is more than the specified column
then field-width is ignored and the number of columns used is equal to
the number of columns required by the arguments. So if i is 12345 then
5 columns are used even if %4d is specified. The output width is not
shortened because of the field-width. If you specify * instead of field-
width then you have to specify additional arguments.
For example:
printf (“%*d”, 5, 20); /* statetment A */
printf (“%*d”, 20, 5); /* statetment B */
5.4.4 Precision
Precision indicates the number of minimum digits printed for integers,
i.e. for type integers d, o, u, x and X. For example,
printf(“%10.4d”, 35);
Here 10 is the field-width and 4 is the precision, so 10 columns
ʇ NOTE
are used for the output and the output is 4-digit. To divide 35 in 4 For floating arguments,
digits, 00 are padded on left side to make it as 0035. To print 0035 in precision indicates the number
10 columns, blanks are added to make the output bbbbbb0035. of digits that are printed after
decimal points.
If precision is more than the number of digits on the right side
of decimal point then 0’s are padded on the right side. If precision
indicates very few digits then it is ignored and the number of digits are
printed as required.
5.4.5 Flags
Flag characters are used to provide directives for the output. You can
use multiple flag characters in any order. Following are flag characters:
1. - indicates that the output is left justified.
printf(“%-10.4”, 25);
It prints 0025bbbbbb, thus blanks are padded on right side. In
the absence of flag, it is printed as bbbbbb0025.
2. + indicates that i number is printed using sign character + or -.
printf(“%+d”, -25);
printf(“%+d”, 25);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
It causes printing as
-25
+25
It causes printing as
b25
25
These are the special directives used to format printing. Table 5.4 shows
the escape sequences:
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 5.2 : Using the scanf() Function */
/*****************************************************************************/
#include<stdio.h>
int main()
{
int m;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
int i, j, k;
printf(“\nEnter Three Integer : ”);
m = scanf(“%d %d %d”, &i, &j, &k); /* statement A */
printf(“Total values inputted : %d\n”, m);
printf(“The input values are : %d %d %d\n”, i, j, k);
return 0;
}
/*****************************************************************************/
OUTPUT :
Run1 :
Enter Three Integer: 34 56 43
Total values inputted : 3
The input values are : 34 56 43
Run2:
Enter Three Integer: 45 38 a
Total values inputted : 2
The input values are : 34 56 4923
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
5.7.2 Use of *
The * is used to suppress the input. For example, %*d, if your input
consists of 5 values and you want to ignore middle 3 values then you
can write:
scanf(“%d %*d %*d %*d %d”, &i, &j);
then i gets the value 10 and j gets the value 50, this is useful
when you are getting the input from the file.
5.7.3 Field-width
It indicates the maximum number of characters that are read into the
variables. It is a string of non-space characters. It extends to the next
inappropriate character or until the field-width limit (if specified) is
reached.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 5.3 : Using the getchar() Function */
/*****************************************************************************/
#include<stdio.h>
void main()
{
char var1;
printf(“\nType a character : ”);
var1 = getchar();
printf(“\nYou typed : %c”, var1);
getch();
}
/*****************************************************************************/
OUTPUT :
Run 1
Type a character : a
You typed : a
Run 2
Type a character : F
You typed : F
The gets() function reads a string of characters from the user until a
<newline> is read or an end-of-file condition is encountered. It stores
the string of characters in a set of consecutive memory locations, which
is called an array. The example for this function is as follows:
char string[50];
gets(string);
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<stdio.h>
int main()
{
char string1[100];
printf(“\nType Something : ”);
gets(string1);
printf(“You typed : %s\n”, string1);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Type Something : Rajasthan Technical University
You typed : Rajasthan Technical University
/*****************************************************************************/
/* Program 5.5 : Using the putchar() Function */
/*****************************************************************************/
#include<stdio.h>
int main()
{
char var1;
printf(“\nType a character : ”);
var1 = getchar();
printf(“\nYou typed : ”);
putchar(var1);
getch();
}
/*****************************************************************************/
OUTPUT :
Type a character : N
You typed : N
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 5.6 : Using the puts() Function */
/*****************************************************************************/
#include<stdio.h>
int main()
{
char string1[100];
printf(“\nType Something : ”);
gets(string1);
printf(“You Typed : ”);
puts(string1);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Type Something : Rajasthan Technical University
You typed : Rajasthan Technical University
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
5.12 What is the advantage of the using function gets( ) 5.5 What is the output of the program ?
over scanf( ) for reading strings?
#include <stdio.h>
5.13 What is the difference between the digit 8 and #include <Conio.h>
character ‘8’ ? main ()
{
5.14 How many digits after decimal are displayed using char text[40];
format specifier % f ? puts(“Enter a line of text”);
gets(“%s”,text);
puts(text);
getch();
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<conio.h> main()
#include<stdlib.h> {
void main() printf(“computer\nScience\n”);
{ printf(“Computer\rScience”);
int i; }
clrscr();
scanf(“%d”,printf(“\d\n”,scanf(“%d”,&i))); 5.14 What is the output of the following code ?
/* input 30 * /
getch(); #include<stdio.h>
main()
}
{
printf(“Computer\b\b\b\b\b”);
5.8 What is the output of the program? printf(“Hi!\b\b\bScience”);
#include<stdio.h> }
#include<conio.h>
void main() 5.15 What is the output of the following code?
{
int y; #include<stdio.h>
clrscr(); main()
y=printf(“HI\n”); {
printf(“%d”,printf(“HELLO\n”),y); char str=‘\ni’;
/* input: 30 */ printf(“str=%c“,str);
getch(); }.
}
5.16 What is the output of the following code?
5.9 What is the output of the program? #include<stdio.h>
#include<stdio.h> #include<conio.h>
void main() main()
{ {
static int y=0xB; char ch, ch1;
printf{“%d”,getch(y)); /* input: 0 */ clrscr();
scanf(“%c”,&ch); /* input: ab */
}
scanf(“%1c”,&ch1);
printf(“ch=%c,ch1=%c\n”,ch,ch1);
5.10 What is the output of the program? printf(“ch=%1c,ch1=%1c\n”,ch,ch1);
#include<stdio.h> printf(“ch %1s,ch1=%1s\n”,ch,ch1);
#include<math.h> getch();
void main() }
{
static int x; 5.17 What is the output of the following code?
printf(“%d”, x=(pow(printf(“hi\b”),-~x)));
#include<stdio.h>
}
#include<conio.h>
void main()
5.11 What is the output of the following code ? {
#include<stdio.h> int f;
main () clrscr();
{ f=‘%’;
float PI=3.14; printf(“%cd”,f,f);
printf(“\nPI=%f”,PI); }
printf(“\nPI=%6.2f”,PI);
printf(“\nPI=%6.0f”,PI); 5.18 What is the output of the following code ?
}
#include<stdio.h>
#include<conio.h>
5.12 What is the output of the following code? main()
#include<stdio.h> {
main() int a,b;
{ clrscr();
printf(“%20s\n”,”Computer”); scanf(“%d”+scanf(“%d %d”,&a,&b));
printf(“%20s\n”,”Computer Science!”); /* input 21 45 */
} printf(“a=%d b=%d\n”,a,b);
printf(“\%\n”);
5.13 What is the output of the following code? printf(“\\%\n” );
printf(“%%\n”);
#include<stdio.h> printf(“\%%\n”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
clrscr();
}
printf(“a=%s, b=%s”,a,b);
}
5.19 What is the output of the following code ?
#include<stdio.h>
#include<conio.h>
main() LAB PROGRAMS
{
unsigned int a=l28;
clrscr();
5.1. Write a program that reads a character from the
printf(“%d”,a);
{ standard input device, i.e. keyboard and displays
char a=l28; it on the screen.
printf(“%d”,a);
}
} 5.2. Write a program that reads a character from the
standard input device, i.e. keyboard and displays
5.20 What is the output of the following code? it on the screen using the putchar() function.
#include<stdio.h>
#include<conio.h> 5.3. Write a program that accepts an age of person from
main() the keyboard using scanf() function and displays it
{ on the screen.
char a[]=”\\?/”;
char b[]=”\/?\”; 5.4. Write a program that accept the value of two
integer numbers and display them.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
DECESION MAKING
6
6.1 INTRODUCTION
6.2 IF STATEMENT
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
is false then the C compiler does not do anything. Note that the test_
expression given in parentheses, must be evaluated as true (non-zero
value) or false (zero value). Some examples of using a test_expression
in the if statements are given as follows:
if(7) /* a non-zero value returns True*/
if(0) /* zero value returns False*/
if(i==0) /* True if i=0 otherwise False*/
if(i = 0) /* False because value of the expression is zero*/
/*****************************************************************************/
/* Program 6.1 : Using the if Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int age;
clrscr();
printf(“\nEnter your age : ”);
scanf(“%d”,&age);
if(age<18)
printf(“\nYou are not eligible to give vote.\n”);
if(age>=18)
printf(“\nYou are eligible to give vote.\n”);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Run 1
Enter your age : 17
You are not eligible to give vote.
Run 2:
Enter your age : 18
You are eligible to give vote.
EXPLANATION :
In this program you have to enter your age at the runtime. If the entered age is less
than 18, You are not eligible to give vote. message appears; and if the entered age
is greater than 18, You are eligible to give vote. message appears.
/*****************************************************************************/
/* Program 6.2 : Program to find the largest of three numbers */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int a, b, c, big;
printf(“\nInput a b c : ”);
scanf(“%d %d %d”, &a, &b, &c);
/* computing the largest of three numbers */
big = a; /* statement A*/
if(b > big) /* statement B*/
big = b;
if(c > big) /* statement C*/
big = c;
printf(“Largest of the three numbers = %d \n”,big);
getch();
}
/*****************************************************************************/
OUTPUT :
Run1:
Input a b c : 15 20 55
Largest of the three numbers = 55
Run2:
Input a b c : 88 198 102
Largest of the three numbers = 198
EXPLANATION :
In this program first 3 input is provide. By Statement A, a is assigned to big. Now in
statment B, big is compared with b. If b is greater than big, then big is assigned b.
In statement C, big is compared with c. If c is greater than big, then big is assigned
c. Thus big has biggest of a, b and c.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 6.3 : To calculate the Total Pay of a Employee
/*****************************************************************************/
#include<stdio.h>
main()
{
int empno, ltc;
float bpay, bonus, hra, total=0.0;
char category;
printf(“\nGive Category : ”);
scanf(“%c”, &category);
printf(“\nGive Employee Number : ”);
scanf(“%i”, &empno);
printf(“\nGive Basic Pay : ”);
scanf(“%f”, &bpay);
if(category == ’r’)
{
bonus = bpay*50.00/100.00;
ltc = 5000;
hra = bpay *25.0/100.0;
total = bpay + bonus + ltc + hra;
}
else
{
bonus = bpay*30.0/100.00;
ltc = 2000;
hra = bpay*10.0/100.0;
total = bpay + bonus + ltc + hra;
}
printf(“\nBasic Salary = %g”, bpay);
printf(“\nBonus = %g”,bonus);
printf(“\nLTC = %i”, ltc);
printf(“\nHouse rent = %g”, hra);
printf(“\nTotal salary = %g”, total);
getch();
}
/*****************************************************************************/
OUTPUT :
Run 1:
Give Category : r
Give Employee Number : 23
Give Basic Pay : 4000
Basic Salary = 4000
Bonus = 2000
LTC = 5000
House Rent = 1000
Total Salary = 12000
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Run 1
Give Category : a
Give Employee Number : 13
Give Basic Pay : 10000
Basic Salary = 10000
Bonus = 3000
LTC = 2000
House Rent = 1000
Total Salary = 16000
EXPLANATION :
Here program ask the user for category. If category is r, statement block following if
is executed. If category is any other, statement following else are executed.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 6.4 : Checking the Age for Vote */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int age;
clrscr();
printf(“\nEnter your age : ”);
scanf(“%d”,&age);
if(age<18)
printf(“\nYou are not eligible to give vote\n”);
else
printf(“\nYou are eligible to give vote\n”);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Run 1:
Enter your age : 24
You are eligible to give vote
Run 2:
Enter your age : 15
You are not eligible to give vote.
EXPLANATION :
In above program, you have to enter your age at the runtime. If the entered age is less
than 18, You are not eligible to give vote. message appears; otherwise, You are
eligible to give vote. message appears.
/*****************************************************************************/
/* Program 6.5 : Checking the number for Nonzero */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int input;
printf(“\nInput an integer : ” );
scanf(“%d”, &input );
if(input)
printf(“\nIt is non-zero.”); /* Statement A */
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
else
printf(“\nIt is zero.” ); /* Statement B */
getch();
}
/*****************************************************************************/
OUTPUT :
Run1:
Input an integer: 12
It is non-zero.
Run2:
Input an integer: 0
It is zero.
EXPLANATION :
In this program you have to enter a number. If it is nonzero, statement A is executed
otherwise statement B is executed.
6.4 NESTED IF
/*****************************************************************************/
/* Program 6.6 : Program 3: Using Nested if Statements */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
int num;
clrscr();
printf(“\nEnter a number gerater than 0 : ”);
scanf(“%d”,&num);
if(num>0)
{
if(num>50)
{
if(num>100)
{
if(num>500)
printf(“\nThe number is greater than 500.”);
printf(“\nThe number is greater than 100.”);
}
printf(“\nThe number is greater than 50.”);
}
printf(“\nThe number is greater than 0.”);
}
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Run 1:
Enter a number greater than 0 : 200
The number is greater than 100.
The number is greater than 50.
The number is greater than 0.
Run 2 :
Enter a number greater than 0 : 76
The number is greater than 50.
The number is greater than 0.
EXPLANATION :
In Program 6.6, num is integer variable, which is initialized at runtime by user. The
if statements are used four times, which are nested one into another. The first if
statement checks whether the entered value of num variable is greater than 0. If the
value of num variable is greater than 0, then the second if statement checks whether
the entered value of num variable is greater than 50. When second if statement also
comes out to be true, the third if statement checks whether the num variable is
greater than 100. When third if statement also comes out to be true, the fourth if
statement checks whether the num variable is greater than 500. At each level of the if
statement, the corresponding message is displayed by using the printf() function. In
our case, we have entered the number, 400, at runtime, so the corresponding messages
are displayed.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 6.7 : Using the if-else Ladder */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char alphbt;
clrscr();
printf(“\nEnter an alphabet : ”);
scanf(“%c”,&alphbt);
if(alphbt == ‘a’)
printf(“It is a vowel.”);
else if(alphbt == ‘e’)
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
printf(“It is a vowel.”);
else if(alphbt== ‘i’)
printf(“It is a vowel.”);
else if(alphbt == ‘o’)
printf(“It is a vowel.”);
else if(alphbt == ‘u’)
printf(“It is a vowel.”);
else
printf(“It is not a vowel.”);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Run 1:
Enter an alphabet : e
It is a vowel.
Run 2:
Enter an alphabet : g
It is not vowel.
EXPLANATION :
In this program alphbt is a character variable and its value is provided at runtime.
The character supplied at runtime is tested successively across the multiple if-else
statements until a match is found. In our case, we provide the e character, which
displays the It is a vowel message.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 6.8 : Using the switch Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char alphbt;
clrscr();
printf(“\nEnter an alphabet : ”);
scanf(“%c”,&alphbt);
switch(alphbt)
{
case ‘a’:
printf(“It is a vowel”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
break;
case ‘e’:
printf(“It is a vowel”);
break;
case ‘i’:
printf(“It is a vowel”);
break;
case ‘o’:
printf(“It is a vowel”);
break;
case ‘u’:
printf(“It is a vowel”);
break;
default:
printf(“It is not a vowel”);
}
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Run 1:
Enter an alphabet : e
It is a vowel
Run 2:
Enter an alphabet : g
It is not vowel
EXPLANATION :
In program 6.8, the value supplied by you at runtime is stored as an alphbt variable.
This variable is used as a parameter to the switch clause and is compared against the
various constants in the case labels. Statements following the case label are executed
whose constant is equal to the value of the expression in the switch statement. The
default label is executed when none of the case labels matches with the value stored
in the switch expression.
/*****************************************************************************/
/* Program 6.9 : Roots of a quadratic equation */
/*****************************************************************************/
#include<stdio.h>
#include<math.h>
main()
{
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Run1 :
Input a b c : 1 2 1
Discriminant = 0.00
Roots are real and equal.
Root1 = Root2 = -1.00
Run2 :
Input a b c : 1 2 7
Discriminant = -24.00
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Run 3:
Input a b c: 0 4 7
Equation is linear.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 6.10 : Demonstration of if else construct */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int choice;
printf(“\nChoice of Destinations: \n” );
printf(“\t1 - Mercury\n” );
printf(“\t2 - venus\n”);
printf(“\t3 - Mars\n”);
printf(“Enter the number corresponding to your choice : ”);
scanf(“%i”, &choice );
printf(“\n”);
if( choice == 1)
{
puts(“Mercury is closest to the sun.”);
puts(“So the weather may be quite hot there.”);
puts(“The journey will cost you 5200 IGCs.”);
}
else
if(choice == 2 )
{
puts(“Venus is the second planet from the sun.”);
puts(“The weather may be hot and poisonous.”);
puts(“The journey will cost you 3200 IGCs.”);
}
else
if( choice == 3)
{
puts(“Mars is the closest planet to the earth.”);
puts(“The weather has been excellent till now.”);
puts(“The journey will cost you 1200 IGCs.”);
}
else
puts(“\nUnknown destination, Unpredictable IGCs.”);
puts( “\nNote: IGC = Inter-Galactic Currency” );
getch();
}
/*****************************************************************************/
OUTPUT :
Choice of Destinations:
1 - Mercury
2 - Venus
3 - Mars
Enter the number corresponding to your choice : 2
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Now the same example, using the switch statement is given below:
/*****************************************************************************/
/* Program 6.11 : Program to demonstrate the use of switch statement */
/*****************************************************************************/
#include <stdio.h>
void main()
{
int choice;
printf(“\nChoice of destinations:\n” );
printf(“\t1 - Mercury\n”);
printf(“\t2 - venus\n” );
printf(“\t3 - mars\n” );
printf(“Enter the number corresponding to your choice :” );
scanf(“%i”, &choice );
printf(“\n”);
switch( choice )
{
case 1:
puts(“Mercury is closest to the sun.”);
puts(“So the weather may be quite hot there.”);
puts(“The journey will cost you 5200 IGCs.”);
break;
case 2:
puts(“Venus is the second planet from the sun.”);
puts(“The weather may be hot and poisonous.”);
puts(“The journey will cost you 320 IGCs.”);
break;
case 3:
puts(“Mars is the closest planet to the earth.”);
puts(“The weather has been excellent till now.”);
puts(“The journey will cost you 1200 IGCs.”);
break;
default:
puts(“Unknown destination. Unpredictable IGCs.”);
break;
}
puts(“\nNote: IGC = Inter-Inter-Galactic Currency”);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
main()
6.6 What is the output of the following program?
{
#include<stdio.h> int k=1;
main() switch(k)
{ {
int var1, var2=2, num=50, a; case 1 : goto label;
if(var1=var2%2) case 2 : printf(“\nHello...“);
num=2; break;
printf(“%d %d”, num, var1); }
} printf(“\nHi ... “);
label:
6.7 What is the output of the program ? }
#include<stdio.h>
main() 6.12 What is the output of the following code?
{ #include<stdio.h>
float num=1.5; #include<conio.h>
switch(num) main()
{ {
case 1: printf(“1”); char k=4;
case 2: printf(“2”); clrscr();
default: printf(“0“); switch(k)
} {
} default:printf(“LAST\n”);
case 4:printf(“FOUR\n”);;
6.8 What is the output of the program ? case 1:break;
printf(“ONE\n”);
#include<stdio.h> case 2:printf(“TWO\n”);
#include<conio.h> break;
void main() }
{ getch();
static char k;
}
clrscr();
while(k<=10)
k>0?k++:k--; 6.13 What is the output of the following code?
if(printf(“%d\n”,k)) #include<stdio.h>
printf(“Hi Jaipur”} ; #include<conio.h>
getch(); main()
} {
int i=1,j=2;
6.9 What is the output of the program? clrscr();
switch(i,j)
#include<stdio.h> {
void main (int) default :
{ printf(“LAST”);
int y=1; break;
if(“%d=hello”, y); case 3 :
} printf(“THREE\n”);
break;
6.10 What is the output of the program? case 2:
printf(“TWO\n”) ;
#include<stdio.h>
break;
#include<conio.h>
case 1:
void main()
printf(“ONE\n”) ;
{
break;
int i=1,j=-1;
}
clrscr();
if((printf(“%d\n”, i)) <(printf(“%d\n”, j))) }
printf(“%d\n”,i);
else 6.14 What is the output of the following code?
printf(“%d\n”,j); #include<stdio.h>
getch(); #include<conio.h>
} main()
{
6.11 What is the output of the following code ? int j=4;
clrscr();
#include<stdio.h>
switch(j)
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
6.3. Write a program for leap year checking.
6.24 What is the output of the following code? 6.4. Write a program to check an integer for perfect
#include<stdio.h> square.
#include<conio.h>
main() 6.5. Write a program to find biggest of three numbers.
{
6.6. Write a program to check the category of the
int i=4;
int s=2; entered character.
clrscr(); 6.7. Write a program to find summation of the series a+
switch(i)
{
ar + ar^2 + ... + ar^(n-1)
case s*s : printf(“\nABCDEF”); 6.8. Write a program to find grade of a student.
break;
case 2+3+1: printf(“\nGHIJKL”); 6.9. Write a program to find area of a triangle and it’s
break; type.
}
6.10. Write a program to find roots of a quadratic
}
equation.
6.11. Write a program to print all possible combinations
of 3 digits.
LAB PROGRAMS
6.12. Write a program to which accepts input a number
from 1-7 and display corresponding day of week
using switch .. case control structure.
6.1. Write a program to find smallest of three numbers. 6.13. Write a program to simulate a simple calculator.
6.14. Write a program to print first n natural numbers in
6.2. Write a program to calculate sum of first n natural ascending/descending order
numbers using goto.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
7
ITERATION
7.1 INTRODUCTION
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
C has three loop structure: while, for, and do-while. The first
two are pre-test loops and do-while is a post-test loop.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
while(num>0)
printf(“%d\t”, num--);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
10 9 8 7 6 4 3 2 1
EXPLANATION :
In this program, integer variable, num is initialized with the number 10. The while
loop checks in the num variable, and decreases the value of num by using the decrement
(--) operator. The while loop stops executing, when the value of num variable become
zero.
/*****************************************************************************/
/* Program 7.2 : Using the While loop with a Compound Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int value,temp;
double factorial = 1;
clrscr();
printf(“\nEnter a number : ”);
scanf(“%d”, &value);
temp = value;
while(temp>0)
{
factorial*= temp;
temp--;
}
printf(“%d! = %.0f”, value, factorial);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter a number : 5
5! = 120
EXPLANATION :
In above program, the statement Inside the while loop continues to execute until the
value stored In the temp variable becomes zero, When the value stored in the temp
variable becomes zero, then the while loop exits and displays the factorial of number
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
5.
/*****************************************************************************/
/* Program 7.3 : Creating a Nested while loop */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int num1=1, num2, num3;
clrscr();
printf(“\nEnter a number between 1 to 10: ”);
scanf(“%d”, &num3);
while(num1<= num3)
{
num2 = 1;
while(num2<=num1)
{
printf(“%d\t”, num2);
num2++;
}
printf(“\n”);
num1++;
}
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter a number between 1 to 10: 6
1
1 2
1 2 3
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
EXPLANATION :
In Program 7.3, three integer variable, num1, num2 and num3 are declared. The num1 and
num2 variables are initialized with the number 1. You have to enter a number from 1
to 10 for the num3 variable at runtime. The outer while loop keeps track of the entered
number of the num3 variable, and the inner while loop displays the numbers stored in
the num2 variable.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
The do-while loop is used when you want to execute the loop body at
least once. It executes the statement specified in the loop body, first,
and then evaluates the condition. The do-while loop executes a group
of statements as long as the specified condition is true. If the condition
becomes false, the flow of execution comes out of the do-while loop.
The syntax to use the do-while loop is shown below :
/*****************************************************************************/
/* Program 7.4 : To check for a palindrome */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int n, num, digit, sum = 0, rev = 0;
printf(“\nInput the number : ”);
scanf(“%d”,&num);
n = num;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
do
{
digit = num % 10;
sum += digit;
rev = rev * 10 + digit;
num /= 10;
}while(num!=0);
printf(“\nSum of the digits of the number = %d”,sum);
printf(“\nReverse of the number = %7d”,rev);
if(n == rev)
printf(“\nNumber is a palindrome.”);
else
printf(“\nNumber is not a palindrome.”);
getch();
}
/*****************************************************************************/
OUTPUT :
Run1:
Input the number: 1234
Sum of the digits of the number = 10
Reverse of the number = 4321
Number is not a palindrome.
Run2:
Input the number: 1221
Sum of the digits of the number = 6
Reverse of the number = 1221
Number is a palindrome.
EXPLANATION :
The program checks for a palindrome using a do-while construct. Note the use of mod
operator%.
The for loop iterates over a fixed number of times and consists of three
parts, such as initialization, test expression, and updation. The syntax
of the for loop is shown in figure 7.4.
ʇ NOTE
The initialization part initializes the variable with a value. The Note that when the for loop
initialization part executes only once, which is followed by the test_ is constructed with a simple
expression. If the test_expression evaluates to true, then the body of statement, the curly braces
in the body of the loop is not
the for loop is executed. If the test_expression evaluates to false, the necessary.
the statement following the for loop is evaluated. The updation is used
to increment or decrement or updating a counter variable controlling
the loop. The for loop continues to execute until the test_expression
evaluates to false. The statementblock represents the loop body of the
for loop.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 7.5 : Using the for Loop with a simple Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
int i;
printf(“First ten even numbers are as follows:\n”);
for(i=2;i<=20;i=i+2)
printf(“%d\t”,i);
getch();
}
/*****************************************************************************/
OUTPUT :
First ten even numbers are as follows:
2 4 6 8 10 12 14 16 18 20
EXPLANATION :
In this program, the first 10 even numbers are displayed with the help of the for
loop. The i variable is initialized with the value 2, and incremented by 2 to display
even numbers on each iteration. The evaluation becomes false when the value of the
i variable exceeds 20 and the loop terminates.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Consider another program that finds the sum, and the sum of
squares of the first 15 positive, even numbers.
/*****************************************************************************/
/* Program 7.6 : Program to illustrate the sum of the squares */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int i, n;
int sum = 0, sum_of_squares = 0;
printf(“\nEnter the Number : ”);
scanf(“%d”,&n);
for(i=2; i<=n; i+=2)
{
sum+= i;
sum_of_squares+= i*i;
}
printf(“\nSum of first positive even numbers till %d : %d”, n, sum );
printf(“\nSum of their squares : %d”, sum_of_squares );
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the Number : 14
Sum of first positive even numbers till 14 : 56
Sum of their squares : 560
/*****************************************************************************/
/* Program 7.7 : To compute the sine series SIN(X)=X-X^3/3!....X^N/N! */
/*****************************************************************************/
#include<stdio.h>
#include<math.h>
void main()
{
float x, t, sum;
int i, n, singn = 1;
printf(“\nInput X in degree and N : ”);
scanf(“%f%d”,&x,&n);
x*= 3.1412/180; /* Convert x into radians */
sum = t = x;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Run1:
Input X and N
90.00 10
SIN (X) = 1.00
Run2:
Input X and N
60.00 12
SIN(X) = 0.86
/*****************************************************************************/
/* Program 7.8 : Displaying Highest Marks from 5 Students */
/*****************************************************************************/
#include<stdio.h>
main()
{
int i, roll, roll_higest, marks;
int big = 0;
clrscr();
printf(“This program find the highest marks between 5 students.\n”);
for(i=0; i<5; i++)
{
printf(“\nGive roll number : ”);
scanf(“%i”,&roll);
printf(“Give marks : ”);
scanf(“%i”,&marks);
if(marks>big)
{
big = marks;
roll_higest = roll;
}
}
printf(“\nHighest marks %i secured by roll no %i.”, big, roll_higest);
getch();
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
This program find the highest marks between 5 students.
Give Roll number : 1001
Give marks : 23
Points to Remember :
1. In a for loop, any or all the expressions can be omitted. In
case all the expressions are omitted, then there must be two
semicolons in the for statement.
2. There must be no semicolon after a for statement. If you do
that, then you will get some unexpected results. Consider the
following code.
#include <stdio.h>
main()
{
int j;
for(j=0; j<20; j++);
printf(“ %d”, j);
return 0;
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
main()
{
int j;
for(j=100000; j>0; j--);
printf(“%d”, j);
return 0;
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
10. Never use a floating point variable as the loop control variable.
This is because floating point values are just approximations and
therefore may result in imprecise values and thus inaccurate test
for termination. For example, the following code will result in an
infinite loop because of inaccuracies of floating point numbers.
#include <stdio.h>
main()
{
float j;
for(j = 100; j>=10;)
{
printf(“ %f”, j);
j = (float)j/10;
}
return 0;
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
and the control passes to the inner for loop. The inner for loop then
continues execution till the condition of inner for loop evaluates to true.
When the inner for loop is completed, the flow of execution is passed
to the outer for loop to continue to next iteration and then again the
inner for loop is executed. This implies that for the each iteration
of the outer loop, the inner loop is executed completely. Program 7.9
shows an example of the nested for loop.
/*****************************************************************************/
/* Program 7.9 : Nesting for Loop */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int x, y, sum;
clrscr();
for(x=1;x<=2;x++)
for(y=1;y<=3;y++)
{
sum = x+y;
printf(“\nx: %d\t”,x);
printf(“y: %d\t”,y);
printf(“Sum: %d”,sum);
}
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
x: 1 y: 1 Sum: 2
x: 1 y: 2 Sum: 3
x: 1 y: 3 Sum: 4
x: 2 y: 1 Sum: 3
x: 2 y: 2 Sum: 4
x: 2 y: 3 Sum: 5
EXPLANATION :
In this program, the execution begins with an outer for loop in which the x variable is
initialized to 1. Now, the execution enters into the inner for loop where the y variable
is set to 1. The sum of two numbers (x and y) gets printed.
The inner for loop continues to execute until the condition, y<=3, becomes false.
In this way, the inner for loop is executed three times, with the changing value of
the y variable from 1 to 3. When the inner for loop is completed, the execution goes
to the outer for loop and the x variable is set to 2. This time, the inner for loop is
executed again and the statements following this loop are executed thrice. In this way,
the outer for loop and inner for loop are in the code.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Jump statements are the statements that transfer control from one part
of the program to another. The jump statements supported by C are
follows:
(1) break statement
(2) continue statement
(3) goto statement
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 7.10 : Using the break Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int j = 0;
clrscr();
while(“true”)
{
j = j+2;
if(j>10)
break;
printf(“%d\n”, j);
}
return 0;
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
2
4
6
8
10
EXPLANATION :
In this program, the j variable is initialized with zero value and the while loop is
used to display even numbers from 2 to infinity. However, the program displays even
numbers up to 10. This is because, an if statement checks whether the number
stored in the i variable is greater than 10; and if is greater than 10, the while loop
is terminated by the break statement.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 7.11 : To calculate square root of a number */
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include <stdio.h>
#include <math.h>
main()
{
int num;
do
{
printf(“\nEnter any number. Enter 999 to stop : ”);
scanf(“%d”, &num);
if(num == 999)
break; /* quit the loop */
if (num < 0)
{
printf(“\nSquare root of negative numbers is not defined.”);
continue; /* skip the following statements */
}
printf(“\n The square root of %d is %.2f.”,num, sqrt(num));
}while(1);
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter any number. Enter 999 to stop : 49
The square root of 49 is 7.00.
Enter any number. Enter 999 to stop : -34
Square root of negative numbers is not defined.
Enter any number. Enter 999 to stop : 81
The square root of 81 is 9.00.
Enter any number. Enter 999 to stop : 999
/*****************************************************************************/
/* Program 7.12 : Using the continue Statement */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
for(i=2;i<=20;i=i+2)
{
if(i==6 || i==14)
continue;
printf(“%d\t”,i);
}
getch();
return 0;
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
2 4 8 10 12 16 20
EXPLANATION :
In Program 7.12, first 10 even numbers are shown, excluding 6 and 14 from the result.
This is done with the help of the continue statement inside an if condition, which gets
executed in case the value of i variable becomes either 6 or 14. In the output of this
program, even numbers are shown successfully until the value of i becomes 6 or 14.
When the value of i becomes 6, the control of execution quits from the current loop
and returns back to the for loop. The next iteration then displays the remaining even
numbers till the value of i becomes 14. Then, the control of execution again quits
the current loop and returns back to the for loop. The next iteration displays the
remaining even numbers.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
goto lable;
/*****************************************************************************/
/* Program 7.13 : Calculates the sum of all positive numbers entered */
/*****************************************************************************/
#include <stdio.h>
main()
{
int num, sum=0;
printf(“\nThis program find the sum of all positive number entered.”);
read: /* label for goto statement */
printf(“\nEnter the number. Enter 0 to end : ”);
scanf(“%d”, &num);
if(num!=0)
{
if(num < 0)
goto read; /* jump to label - read */
sum+= num;
goto read; /* jump to label - read */
}
printf(“\nSum of the all positive numbers entered by the user is %d.”, sum);
printf(“\nProgram End. Press any Key”);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
This program find the sum of all positive number entered.
Enter the number. Enter 0 to end : 23
Enter the number. Enter 0 to end : 34
Enter the number. Enter 0 to end : 78
Enter the number. Enter 0 to end : -45
Enter the number. Enter 0 to end : 67
Enter the number. Enter 0 to end : 0
Sum of the all positive numbers entered by the user is = 202
Program End. Press any Key
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
REVIEW QUESTIONS }
while(i<4);
getch();
7.1 Write a short not on iterative statements that C }
language supports.
7.3 The following code is written to get the sum of all
7.2 Give the syntax of for loop and explain how it the even integer numbers between 1 to 10. Identify
works, with an example. the error.
7.3 Give the points of similarity and differences between #include<stdio.h>
a while loop and a do-while loop. #include<conio.h>
void main()
7.4 Distinguish between the break and the continue
{
statement. int i, j=0;
7.5 Write a short note on goto statement? Why should clrscr();
for(i=0;i<10;);
it be avoided?
{
7.6 Write a program which demonstrates the use of j =j+i;
goto, break, and continue statements. i+=2;
}
7.7 In what situation will you prefer to use for, while printf(“Sum of first 10 even numbers is:%d” ,j);
and do-while loop? getoh();
}
7.8 Can we use a for loop when the number of iterations
is not known in advance? If yes, give a program that 7.4 Find out the error in the following program.
illustrates how this can be done. #include<stdio.h>
7.9 Explain the difference between break and continue #include<conio.h>
statements of C language. void main()
{
int i;
printf(“Enter the value of i :”);
scanf(“%d”, &i);
PROGRAMMING OUTPUT QUIZ if(i<7)
{
i++;
continue;
7.1 We require a code to print the integer values from
}
0 to 9. Identify the error ? printf(“Final value of i is: %d”, i);
#include<stdio.h> getch();
#include<conio.h> }
void main()
{ 7.5 What is the output of the following code?
static int i;
#include<stdio.h>
clrscr();
main()
for(;i<=9;);
{
{
int var=0;
printf(“\nvalue is: %d”,i);
for(;var++;printf(“%d”, var));
i++;
printf(“%d”,var);
}
}
getch();
}
7.6 What is the output of the following program?
7.2 Find the output of the following code ? #include<stdio.h>
void main()
#include<stdio.h>
{
#include<conio.h>
while(1)
void main()
{
{
if(printf(“%d”,printf(“%d”)))
int i;
break;
printf(“Enter the value of i : “);
else
scanf(“%d”,&i); /* input: 5 */
continue;
clrscr();
}
do
}
{
i++;
printf(“\nHello User”);
7.7 What is the output of the following code ?
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<stdio.h> break;
#include<conio.h> case 3:printf(“%d”,i);
main() case 4:printf(“%d”,i);
{ }
int i; }
clrscr();
for(i=1;i<10, printf(“Hi ... “);i++) 7.13 What is the output of the program?
{
#include<stdio.h>
if(i<5)
#include<conio.h>
break;
void main()
break; continue; break;
{
break;
int i=1,j=1;
printf(“Hello ... “);
clrscr();
}
while(++i <= 15)
}
{j++;}
printf(“%d%d”,i,j);
7.8 What is the output of the following code ? getch();
#include<stdio.h> }
main()
{ 7.14 What is the output of the program ?
signed char i=0;
#include<stdio.h>
for(;i>=0;i++);
#include<conio.h>
printf(“%d\n”,i);
void main()
}
{
int i=5;
7.9 What is the output of the following program? clrscr();
#include<stdio.h> for(;i;printf(“%d”,i--));
main() getch();
{ }
unsigned char var=0;
for(;var>=0;var++); 7.15 What is the output of the following code?
printf(“%d\n”,var);
#include<stdio.h>
}
main()
{
7.10 What is the output of the following program? char j;
#include<stdio.h> for(j=1;100;j++)
main() printf(“%d\n”,j);
{ }
int var=3;
for(;var++=0;) 7.16 What is the output of the following code ?
printf(“%d”,var);
#include<stdio.h>
}
main()
{
7.11 What is the output of lhe program? int j;
#include<stdio.h> for(j=0;j++ <= 4; printf(“%d”,j));
void main() }
{
signed char var; 7.17 What is the output of the following code ?
for(var=0;var<=127;var++)
#include<stdio.h>
printf(“%c%d \n”,var,var);
#include<conio.h>
}
main()
{
7.12 What is the output of the program ? char i=128;
#include<stdio.h> clrscr();
main() while(i)
{ {
int i; printf(“%d\n”,i);
for(i=1;i<4;i++) i=i+l;
switch(i) }
{ }
case 1:printf(“%d”,i);
break; 7.18 What is the output of the following code ?
case 2:printf(“%d”,i);
#include<stdio.h>
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<conio.h>
7.22 Find out the error in the following code.
main()
{ #include<stdio.h>
int i==2; #include<conio.h>
clrscr(); void main()
do {
{ int x, y, Z;
printf(“%d\n”, i); clrscr();
}while(i=0); for(x=y=0;x<10;x++;y+=2)
printf(“%d”, i); {
} if((y-x)<=2)
{
7.19 What is the output of the following code ? printf(“\n\n %d”,(z=y-x));
getch();
#include<stdio.h> }
#include<conio.h> else
main() {
{ printf(“\n\n\n %d”, x);
clrscr(); getch();
switch(0) }
printf(“A”); }
while(0) }
printf(“B”);
if(0)
7.23 What is the output of the following code ?
printf(“C”);
for(;0;) #include<stdio.h>
printf(“D”); #include<conio.h>
do main()
{ {
printf(“E”); int a=0;
}while(0); clrscr();
} for(a=0;a<=3;a++)
{
7.20 What is the output of the following code ? switch(a)
{
#include<stdio.h> case 0 : a+=1;
#include<conio.h> case 1 : a+=2;
main() case 2 : a+=3;
{ default : a+=4;
unsigned char i; break;
clrscr(); }
for(i=~10;i<-1;i++) printf(“%d\n”,a);
printf(“%d\n”,i); }
printf(“%d\n”,i); }
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
5 5 5 5 5 1+2+3+4+5+6+7+8+9+10+11+12+13=91
6 6 6 6 6 6 1+2+3+4+5+6+7+8+9+10+11+12+13+14=105
7.40. Write a program to display the pattern of digits. 7.43. Write a program to display the following pattern of
1234567 n lines using nested loops
123456 A
12345 ABC
1234 ABCDE
123 ABCDEFG
12 ABCDEFGHI
1 ABCDEFGHIJK
12
123 7.44. Write a program to display the following pattern
1234 of digits.
12345 6
123456 6 5 6
1234567 6 5 4 5 6
6 5 4 3 4 5 6
7.41. Write a program to display the following pattern 6 5 4 3 2 3 4 5 6
7 6 5 4 3 2 1
6 5 4 3 2 1 2 3 4 5 6
6 5 4 3 2 1
6 5 4 3 2 3 4 5 6
5 4 3 2 1
6 5 4 3 4 5 6
4 3 2 1
6 5 4 5 6
3 2 1
6 5 5
2 1
6
1
7.45. Write a program to display Armstrong numbers
7.42. Write a program to display the following pattern
1=1
upto a specific limit.
1+2=3 7.46. Write a program to display perfect numbers upto a
1+2+3=6
sepecific limit.
1+2+3+4=10
1+2+3+4+5=15 7.47. Write a program to determine all pythagorean
1+2+3+4+5+6=21 triplets in the range 1 to 100.
1+2+3+4+5+6+7=28
1+2+3+4+5+6+7+8=36 7.48. Write a program to display composite numbers
1+2+3+4+5+6+7+8+9=45 between 1 to n.
1+2+3+4+5+6+7+8+9+10=55
1+2+3+4+5+6+7+8+9+10+11=66 7.49. Write a program to convert decimal numeral to
1+2+3+4+5+6+7+8+9+10+11+12=78 roman numeral.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
8
ARRAY
8.1 INTRODUCTION
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
8.2 ARRAY
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
array are stored with the index values starting from zero to one less
than the size of the array. Each element in a one-dimensional array is
accessed using the same name and a single subscript. A one-dimensional
array is similar to a row matrix or a column matrix.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
..........
..........
}
When we declare and define an array, we are just allocating space for
the elements; no values are stored in the array. To store values in the
array, there are three ways
 to initialize the array elements,
 to input value for every individual element
 to assign values to the elements.
This is shown in following figure .
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 8.1 : Initializing All the Array Elements at the Same Time */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5] = {34, 123, 375, 267, 745};
int i;
clrscr();
printf(“Elements of the array are:\n”);
for(i=0; i<5; i++)
printf(“%d\t”, arr[i]);
getch();
}
/*****************************************************************************/
OUTPUT :
Elements of the array are:
34 123 375 267 745
ʇ NOTE
8.6.2 Inputting Values The C language does not
perform bound checking for
An array can be filled by inputting values from the keyboard. In this arrays; therefore, you need to
method, a while/do-while or a for loop is executed to input the value ensure that you are not trying
to access an array element that
for each element of the array. For example, look at the code shown falls outside the array boundary.
below
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
int i, marks[20];
for(i=0; i<20; i++)
scanf(“%d”, &marks[i]);
In the code, we start with the index i at 0 and input the value
for the first element of the array. Since the array can have 20 elements,
we must input values for elements whose index varies from 0 to 19.
Therefore, in the for loop, we test for condition (i<20) which means
the number of elements in the array.
Program 8.2 shows how to input values to array.
/*****************************************************************************/
/* Program 8.2 : Inputting Values to Array */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[30], i, n;
clrscr();
printf(“\nEnter the size of the array : ”);
scanf(“%d”, &n);
printf(“\nEnter the elements of the array :\n”);
for(i=0; i < n; i++)
scanf(“%d”, &arr[i]);
printf(“\nElements of the array are:\n”);
for(i=0; i<n; i++)
printf(“%d\t”, arr[i]);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the size of the array : 6
Enter the elements of the array:
20 40 60 80 100 120
Elements of the array are:
20 40 60 80 100 120
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
specified as marks[4].
We cannot assign one array to another array, even if the two arrays
have the same type and size. To copy an array, you must copy the value
of every element of the first array into the element of the second array.
Following statements illustrates the code to copy an array.
int j , array1[16], array2[16];
for(j=0; j<10; j++)
array2[j] = array1[j];
In this example, the code accesses each element of the first array
and simultaneously assigns its value to the corresponding element of
the second array. Finally, the index value j is incremented to access the
next element in succession. Therefore, when this code is executed,
array2[0] = array1[0];
array2[1] = array1[1];
array2[2] = array1[2];
and so on.
We can also use a loop to assign a pattern of values to the array
elements. For example, if we want to fill an array with even integers
starting (from 0), then we will write the code as below
int i, myArray[10];
for(i=0; i<10; i++)
myArray[i] = i*2;
/*****************************************************************************/
/* Program 8.3 : To read and display n random numbers using an array */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define MAX 10
main()
{
int arr[MAX], i, RandNo;
for(i=0; i<MAX; i++)
{
RandNo = rand()%MAX; /* Scale the random number in the range 0 to MAX-1 */
arr[i] = RandNo; /*rand() is a pre-defined function */
}
printf(“\nThe contents of the array are:\n”);
for(i=0; i<MAX; i++)
printf(“%d\t”, arr[i]);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
The contents of the array are:
6 0 2 0 6 7 5 5 8 6
Figure 8.6 shows the result of the above code. The code accesses
every individual element of the array and sets its value to -1. In the for
loop, first the value of marks[0] is set to -1, then the value of the index
(i) is incremented and the next value, i.e., marks[1] is set to -1. The
procedure is continued until all the 8 elements of the array are set to -1.
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include <stdio.h>
#include <conio.h>
int main()
{
int i=0, n, arr[20];
clrscr();
printf(“Enter the number of elements:”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\nArr[%d] = ”, i);
scanf(“%d”, &arr[i]);
}
printf(“\nThe array elements are\n“);
for(i=0;i<n;i++)
printf(“Arr[%d] = %d, ”, i, arr[i]);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter the number of elements: 5
Arr[0] = 5
Arr[1] = 4
Arr[3] = 3
Arr[4] = 2
Arr[5] = 1
The array elements are
Arr[0] = 5 Arr[1] = 4 Arr[3] = 3 Arr[4] = 2 Arr[5] = 1
/*****************************************************************************/
/* Program 8.5 : To find mean of n numbers using arrays */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, arr[25], sum =0;
float mean = 0.0;
clrscr();
printf(“Enter the number of elements in the array: ”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\nArr[%d] = ”, i);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
scanf(“%d”, &arr[i]);
}
for(i=0;i<n;i++)
sum+= arr[i];
mean = sum/n;
printf(“\nSum of the array elements = %d”, sum);
printf(“\nMean of the array elements = %.2f”, mean);
getch(0);
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter the number of elements in the array: 5
Arr[0] = 1
Arr[1] = 2
Arr[2] = 3
Arr[3] = 4
Arr[4] = 5
Sum of the array elements = 15
Mean of the array elements = 3.00
/*****************************************************************************/
/* Program 8.6 : To generate first n terms FIBONACCI series */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main() {
int fib[50], n, i;
clrscr();
printf(“\nEnter the number of terms to generate : ”);
scanf(“%d”, &n);
fib[0] = 0;
fib[1] = 1;
printf(“\nFibonacci series :\n”);
for(i=2; i<n; i++)
fib[i] = fib[i-1] + fib[i-2];
for (i=0; i<n; i++)
printf(“%d\t”, fib[i]);
getch();
}
/*****************************************************************************/
OUTPUT :
Run 1
Enter the number of terms to generate : 6
Fibonacci series :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
0 1 1 2 3 5
Run 2
Enter the number of terms to generate : 9
Fibonacci series :
0 1 1 2 3 5 8 13 21
/*****************************************************************************/
/* Program 8.7 : To generate sum of two array */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], b[20], c[20];
int i, n;
clrscr();
printf(“\nEnter the number of elements for each array : ”);
scanf(“%d”, &n);
printf(“\nEnter the elements of array a:\n”);
for(i=0; i<n; i++)
scanf(“%d”, &a[i]);
printf(“\nEnter the elements of array b:\n”);
for(i=0; i<n; i++)
scanf(“%d”, &b[i]);
for(i=0; i<n; i++)
c[i] = a[i] + b[i];
printf(“Elements of array c:\n”);
for (i=0; i<n; i++)
printf(“%d\t”, c[i]);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the number of elements for each array : 5
Enter the elements of array a:
23 45 12 45 34
Enter the elements of array b:
12 45 43 56 12
Elements of array c:
35 90 55 101 46
The subscript or the index represents the offset from the beginning of
the array to the element being referenced. With just the array name
and the index, C can calculate the address of any element in the array.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
In order to input the values from the keyboard, you must use the
following code.
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”, &arr[i][j]);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 8.8 : Using Two-dimensional Array */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[4][4]={ {1,2,3,4}, {2,3,4,1}, {3,4,1,2}, {4,1,2,3},};
int i, j, m=4, n=4;
clrscr();
printf(“Elements of the array are:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d “,arr[i][j]);
printf(“\n”);
}
getch();
}
/*****************************************************************************/
OUTPUT :
Elements of the array are:
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
/*****************************************************************************/
/* Program 8.9 : To read and print a two-dimensional array */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10][10], i, j, m, n;
clrscr();
printf(“\nEnter the number of rows in the array : ”);
scanf(“%d”, &m);
printf(“\nEnter the number of columns in the array : ”);
scanf(“%d”, &n);
printf(“\nEnter the elements of the array:\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
scanf(“%d”, &arr[i][j]);
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Enter the number of rows in the array : 3
Enter the number of columns in the array : 3
Enter the elements of the array:
5 6 8 2 4 3 1 9 7
Elements of the array are:
5 6 8
3 4 3
1 9 7
/*****************************************************************************/
/* Program 8.10 : To add the elements of two two-dimensional arrays */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr1[3][3] = {{1, 2, 3}, {2, 4, 5}, {4, 5, 3}};
int arr2[3][3] = {{3, 5, 2}, {2, 5, 6}, {1, 2, 3}};
int arr3[3][3];
int i, j;
clrscr( );
printf(“Elements of the first array are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf(“%d\t“, arr1[i][j]);
printf(“\n”);
}
printf(“Elements of the second array are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf(“%d\t”, arr2[i][j]);
printf(“\n”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
printf(“Elements of the resultant array are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
arr3[i][j] = arr1[i][j] + arr2[i][j];
printf(“%d\t”, arr3[i][j]);
}
printf(“\n”);
}
getch();
}
/*****************************************************************************/
OUTPUT :
Elements of the first array are:
1 2 3
2 4 5
4 5 3
Elements of the second array are:
3 5 2
2 5 6
1 2 3
Elements of the resultant array are:
4 7 5
4 9 11
5 7 6
Program 8.11 multiply two matrix and store the result in third
matrix.
/*****************************************************************************/
/* Program 8.11 : To print the product of two Matrix */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int matrix1[2][3] = {{4, 2, 5}, {3, 5, 7}};
int matrix2[3][2] = {{7, 4}, {6, 2}, {4, 8}};
int matrix3[2][2];
int i, j, k;
clrscr( );
printf(“Elements of the first Matrix are:\n”);
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
printf(“%d\t”, matrix1[i][j] );
printf(“\n”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
printf(“Elements of the second Matrix are:\n”);
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
printf(“%d\t“, matrix2[i][j]);
printf(“\n”);
}
printf(“Elements of the resultant matrix are:\n”);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
matrix3[i][j] = 0;
for(k=0; k<3; k++)
matrix3[i][j] = matrix3[i][j] + (matrix1[i][k]*matrix2[k][j]);
}
}
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
printf(“%d\t“,matrix3[i][j]);
printf(“\n”);
}
getch();
}
/*****************************************************************************/
OUTPUT :
Elements of the first matrix are:
4 2 5
3 5 7
Elements of the second matrix are:
7 4
6 2
4 8
Elements of the resultant matrix are:
60 60
79 78
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 8.12 : To read and display a 2 × 2 × 2 array. */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
main()
{
int array1[2][2][2], i, j, k;
clrscr();
printf(“\nEnter the 8 elements of the matrix:\n ”);
for(i = 0; i < 2; i++)
{
for(j = 0; j <2; j++)
{
for(k = 0; k < 2;k++)
scanf(“%d”, &array1[i][j][k]);
}
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Enter the elements of the matrix :\n
1 2 3 4 5 6 7 8
array1[0][0][0] = 1
array1[0][0][1] = 2
array1[0][1][0] = 3
array1[0][1][1] = 4
array1[1][0][0] = 5
array1[1][0][1] = 6
array1[1][1][0] = 7
array1[1][1][1] = 8
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<stdio.h> main()
#include<conio.h> {
void main() static int arr[3][3]={1,2,3,4,5,6,7,8,9};
{ /* Assume that array begins at address 4004 */
int a[2][2]={{2}, {3}}; printf(“%d%d%d”, arr, arr[2], arr[2][2]);
clrscr(); }
printf(“%d”, a[0][0]);
printf(“%d”, a[0][1]); 8.15 What would be the output of the following code?
printf(“%d”, a[l][0]);
#include<stdio.h>
printf(“%d”, a[1][1]);
main()
getch();
{
}
static int arr[3][3]={1, 2, 3, 4, 5, 6, 7, 8, 9};
int *ptr;
8.10 What is the output of the program? ptr=(int *)arr;
#include<stdio.h> printf(“%d”, arr[2]); /* arr[2]=4016 */
#include<conio.h> printf(“%d”, ptr[2]);
void main() printf(“%d”, *(ptr + 2));
{ }
int a[]={15, 16, 17, 18};
clrscr(); 8.16 What would be the output of the following code ?
printf(“%d”, a[2.9999]);
#include <stdio.h>
getch();
void main()
}
{
int arr[2][3][4]={{{1, 2, 3, 4}, {5, 6, 7, 8},
8.11 What would be the output of the following code ? {8, 7, 6, 5}},{{4, 3, 2, 1}, {5, 6, 7, 8},{1, 2, 3,
#include<stdio.h> 4}}};
main() printf(“%d%d\n”, arr[1][2][3], *(*(*(arr+1)+2)));
{ }
static float arr[]={13.24,1.5,1.5,5.4,3.5};
float *var1, *var2; 8.17 What would be the output of the following code ?
var1=arr;
#include<stdio.h>
var2=arr + 4;
#include<conio.h>
var1=var1 * 2;
void main()
var2=var2 / 2;
{
printf(“%f %f”, *var1, *var2);
int arr[4]={‘0’, ‘1’, ‘2’, ‘3’}, i;
}
clrscr();
for(i=0;i<4;i++)
8.12 What would be the output of the following code ? arr[i]=arr[3-i];
#include<stdio.h> for(i=0;i<4;i++)
main() printf(“%d\n”, arr[i]);
{ getch();
static int arr[]={10, ll, 12, 13, 14}; }
int i, *var;
var = &arr[4] - 4; 8.18 What would be the output of the following code ?
for(i=0; i <= 4; i++)
#include<stdio.h>
{
#include<conio.h>
printf(“%d”, *var);
main()
var++;
{
}
int n=3, i, j, k, x;
}
int a[7]={12, 13};
clrscr();
8.13 What would be the output of the following code ? for(i=0;i<n-l;i++)
#include<stdio.h> {
main() k=i;
{ x=a[k];
int arr[]={0, 1, 2, 3, 4}; for(j=i+l;j<n;j++)
int *ptr, i; {
for(ptr=arr+4; ptr >= arr; ptr--); if(a[j]<k)
printf(“%d”, arr[ptr - arr]); {
} k=j;
x=a[k];
8.14 What would be the output of the following code ? a[k]=a[i];
a[i]=x;
#include<stdio.h>
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
} #include<stdio.h>
} #include<conio.h>
for(i=0;i<n-1;i++) main()
printf(“%d”, a[i]); {
getch(); int arr[]={0, 1, 2, 3, 4, 5};
} int i, *ptr;
clrscr();
8.19 What would be the output of the following code ? for(ptr=arr+5;*ptr;--ptr)
printf(“%d\n”, *ptr) ;
#include<stdio.h>
}
#include<conio.h>
main()
{
LAB PROGRAMS
int arr[]={1, 2, 3 , 4, 5, 6, 7};
char crr[]={‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
clrscr();
printf(“&arr[4]=%u\t &arr[0]=%u\n”, &arr[4],&arr
[0]); 8.1. Write a program to find largest and smallest of
printf(“&crr[4]=%u\t &crr[0]=%u\n”, &crr array of n elements.
[4],&crr[0]);
printf(“&arr[4]-&arr[0]=%d\n”, arr[&arr[4]- 8.2. Write a program to calculate sum and average of
&arr[0]]); n numbers
printf(“&crr[4]-&crr[0]=%c\n”, crr[&crr[4]-
&crr[0]]);
8.3. Write a program to generate Pascal triangle using
printf(“%d\t%d”,(&arr[4]-&arr[0]),(&crr[4]- array.
&crr[0]));
8.4. Write a program to find even numbers among array
}
of n numbers.
8.20 What would be the output of the following code? 8.5. Write a program to find sum of even and odd
#include<stdio.h> numbers among n integers using array.
#include<conio.h>
main()
8.6. Write a program to reverse an array.
{ 8.7. Write a program to calculate mean,variance and
int i, j;
standard deviation.
int arr[3][3]={1,2,3,4,5,6,7,8,9};
clrscr(); 8.8. Write a program to evaluate the given polynomial
for(i=2;i>=0;i--) using Horner’s method
for(j=2;j>=0;j--)
printf(“arr[%d][%d]=%d\n”, i, j, arr[i][j]); 8.9. Write a program to generate prime number from 1
for(i=2; i>=0; i--) to SIZE (say 200)by sieve of Eratosthenes method.
for(j=2;j>=0;j--)
printf(“%d\n”, *(*(arr+j)+i)); 8.10. Write a program to insert in an array at a specific
} position.
8.21 What would be the output of the following code? 8.11. Write a program to delete from an array from a
specific position.
#include<stdio.h>
#include<conio.h> 8.12. Write a program to find the transpose of a matrix.
main()
{
8.13. Write a program to trace of a square matrix.
int arr[2]; 8.14. Write a program to find norm of a matrix. Norm is
clrscr();
square root of the sum of squares of all elements.
*arr[0]=1;
*arr[1]=2; 8.15. Write a program to find sum of all elements of a
printf(“%d\n”, &arr[1]-arr); matrix.
}
8.16. Write a program to check a number for palindrome
8.22 What is the output of the following code? 8.17. Write a program to generate a magic square of odd
#include<stdio.h> order.
void main (void)
{ 8.18. Write a program to print the square of all elements
int a[9] = {“12345678”}; of a square matrix.
printf(“%d”, ((a+6) + (a+1)));
} 8.19. Write a program to check a square matrix for
symmetry.
8.23 What is the output of the following code ?
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
8.20. Write a program for concatenation of two arrays. array is in descending order.
8.21. Write a program which reverse an array of n 8.35. Write a program for merging of two sorted arrays
elements without using temporary variable. given in ascending order merged array is also in
8.22. Write a program for insertion in a sorted array and ascending order.
the array remains sorted after insertion. 8.36. Write a program to remove the duplicate elements
8.23. Write a program to print the matrix along with row from an array.
and column sum. 8.37. Write a program to delete all occurrences of an
8.24. Write a program for row wise sorting of a matrix integer number. Shift all the non deleted members
(selection sort). to left and fill the unused space by 0 (zero).
8.25. Write a program to check whether given odd order 8.38. Write a program for deletion from a sorted array
matrix is a magic square or not. given in ascending order. After deletion of only first
occurrence of the element the array remains sorted
8.26. Write a program to multiply two matrices.
8.39. Write a program for deletion of a specific element
8.27. Write a program for subtraction of two matrices. from an unsorted array. Only first occurrence is
8.28. Write a program for addition of two matrices. deleted.
8.29. Write a program to display the upper and lower 8.40. Write a program to find the maximal subsequence
triangles of a square matrix. out of a given sequence
8.30. Write a program to find the sum of non diagonal 8.41. Write a program which accept and count votes of
elements of a square matrix. candidates print the number of discarded votes (if
any).
8.31. Write a program to calculate the sum of elements
of either diagonals of a square matrix 8.42. Write a program find average male and average
female height.
8.32. Write a program to find transpose of a square
matrix where transpose is stored in the original 8.43. Write a program which read n integers from the
matrix. keyboard and store them in the array ar and then
copy the odd numbers from array ar to array oar ,
8.33. Write a program to mix elements of two integer
even numbers to array ear also display arrays oar
arrays A and B of sizes M and N. All even numbers
and ear.
of A from left to right are copied into C from left to
right. All odd numbers of A from left to right are 8.44. Write a program to find minimum, maximum and
copied into C from right to left. All even numbers sum of array elements
of B from left to right are copied into C from left 8.45. Write a program to check a square matrix for
to right. All odd numbers of B from left to right orthogonality.
are copi~d into c from right to left. For example :
A is {3, 2, 1, 7, 6, 3} and B is {9, 3, 5, 6, 2, 8, 10}. 8.46. Write a program to find the inverse of a square
The resultant array C is {2, 6, 6, 2, 8, 10, 5, 3, 9, matrix. Check for the singularity of the given
3, 7, 1, 3} matrix and append a unit matrix of same order.
Swap current row with the row having maximum
8.34. Write a program for merging of two sorted arrays, element, in the column corresponding to the
given arrays are in ascending order and merged diagonal element.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
9
STRINGS
9.1 INTRODUCTION
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
In this the scanf() functions read the strings for month_name and
employee_name string variables or char array variables.
The printf() function along with the %s format specifier prints a
string stored in character array to the console. You can use the printf()
function to display the string data with the help of two ways. Either
you can pass the string data directly within the printf() function or
you can store the string data in a character array, for instance str, and
then pass the str array as a parameter in the printf() function.
The following examples show the both ways of using the printf()
function to display a string data:
printf(“Test string”); /* Example 1*/
or
char str[]={“Test string”}; /* Example 2*/
printf(“%s”,&str);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
string data is stored in the memory. Program 9.1 shows the use of the
printf() function:
/*****************************************************************************/
/* Program 9.1 : Using the printf() function to print string */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char str[100]={“Using printf() function for displaying the string”};
clrscr();
printf(“%s”,str);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
This program is using printf() function for displaying the string
EXPLANATION :
In this program, a character array or string variable, str, is declared of the 100 size.
This str variable is initialized with a string message that is displayed to the console
by using the printf() function and the %s format specifier.
/*****************************************************************************/
/* Program 9.2 : Displaying Specific Days of a Week by Using the printf() */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char s1[] = “Sunday”;
char s2[] = “Wednesday”;
clrscr();
printf(“%s\n”, s1, s1);
printf(“%s\n”, s2, s2);
getch();
return 0;
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Sunday
Wednesday
EXPLANATION :
In program 9.2, two strings, s1 and s2, are initialized with the string data, sunday
and wednesday, respectively. Then, the printf() function is used two times along with
the %s format specifier to display the string data.
/*****************************************************************************/
/* Program 9.3 : Showing the ASCII Value of a Character Constant */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char nm[5]=“kabir”;
clrscr();
printf(“ASCII Value: %d\n”,nm[2]);
printf(“Character in upper case: %c\n”,nm[2]-32);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
ASCII Value: 98
Character in upper case: B
Now, let’s use the scanf() function along with the printf()
function for reading and displaying a string data. Program 9.4 shows
the use of the scanf() and printf() functions:
/*****************************************************************************/
/* Program 9.4 : Using the scanf() and printf() Functions */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char name[20];
clrscr();
printf(“What is your name?\n”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
scanf(“%s”,&name);
printf(“Welcome, %s!!!\n”,name);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
What is your name?
Mahesh
Welcome, Mahesh!!!
EXPLANATION :
In this program, a string variable or a character array, name, is declared of the 20
size. The printf() function is used to display a string message. What is your name?
The name, which is entered by you, will be stored in the name variable. For instance,
in out case, the name is Mahesh. Then, the second occurrence of the printf() function
along with the %s format specifier is used to display the stored name in the name
variable.
/*****************************************************************************/
/* Program 9.5 : Displaying the Limitation of the scanf() */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char msg[70];
clrscr();
printf(“Enter a message : ”);
scanf(“%s”,msg);
printf(“%s”,msg);
getch();
return 0;
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Enter a message : welcome to Jhunjhunuwala
welcome
EXPLANATION :
Program 9.5 shows that the scanf() function does not read multiple words into an
array. This is because when you enter a space after the word welcome, the scanf()
function considers it as the end of string and do not consider any character typed
after it.
/*****************************************************************************/
/* Program 9.6 : Displaying the Limitation of the scanf() */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char msg[70];
clrscr();
printf(“Enter a message : ”);
gets(msg);
printf(“You Entered : %s”,msg);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter a message : welcome to Jhunjhunuwala
You Entered : welcome to Jhunjhunuwala
/*****************************************************************************/
/* Program 9.7 : Using the gets() and puts() Functions */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int main()
{
char msg[70];
clrscr();
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Enter a message : welcome to Jhunjhunuwala
You Entered : welcome to Jhunjhunuwala
Press any Key.
As you get familiar with the process of creating a single string that
is also called as one dimensional character array. Now, you can also
create an array of string that is known as two-dimensional character
arrays. Two-dimensional character array is an array of one-dimensional
character array, which consists of strings as its individual elements. The
following code snippet an example of two-dimensional character array:
char days[7][10]=
{“Sunday”,“Monday”,“Tuesday”,“Wednesday”,“Thursday”,Friday”,“Saturday”};
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 9.8 : Creating and Displaying an Array of String */
/*****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
int i;
char montharr[12][10]={“January”,“February”,“March”,“April”,“May”,“June”,
“July”,“August”,“September”,“October”,“November”,“December”};
clrscr();
for(i=0;i<12;i++)
printf(“%s\n”,montharr[i]);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
January
February
March
April May
June
July
August
September
October
November
December
EXPLANATION :
In this program, an array of string or a two-dimensional array of character, montharr,
is declared and initialized. Then, the string elements stored in the string array are
displayed by using the printf() function.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 9.9 : Concatenating Two Strings */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[50], s2[50];
int i, j, k;
puts(“Enter First String :”);
gets(s1);
puts(“Enter Second String :”);
gets(s2);
for (i=0;s1[i]!=‘\0’;i++)
{
;
}
k=i;
for(i=k, j=0;s2[j]!=’\0’;i++,j++)
{
s1[i]=s2[j];
}
s1[i]=’\0’;
puts(“After concatenating the first string is :”);
puts(s1);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter First String :
Welcome to Jaipur
Enter First String :
Welcome to Rajasthan
After concatenating the first string is :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
EXPLANATION :
In program 9.9, two strings, s1 and s2, are declared. We read the string using gets
function. Then, the s1 string is traversed to its end. Next, the second string, s2, is
attached at the end of the s1 string. The last character of the resultant string is set
to null character (\0).
/*****************************************************************************/
/* Program 9.10 : Calculating the Length of a String */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
char str[200];
int num, strlength = 0;
clrscr();
printf(“Enter String : ”);
gets(str);
for(num=0; str[num]!=’\0’;num++)
strlength=strlength+1;
printf(“Length of the string is : %d”,strlength);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter String : welcome to jaipur
Length of the string is : 17
EXPLANATION :
In program 9.10, a string is read using gets() function. A counter is declared and
initialized with the value zero, so that whenever the characters are read, the value of
this counter is also increased. The provided string is traversed character by character.
and the value of the counter is increased, whenever a new character is encountered.
The process continues until, all the characters present in the provided string are
traversed completely.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
whether the strings are equal or not. Program 9.11 shows an example
of comparing two strings:
/*****************************************************************************/
/* Program 9.11 : Comparing Two Strings */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100], s2[100];
int num, strlength1=0, strlength2=0, n=0, strflag;
clrscr();
puts(“Enter First String : ”);
gets(s1);
puts(“Enter Second String : ”);
gets(s2);
for(num=0; s1[num]!=‘\0’;num++)
strlength1=strlength1+1;
for(num=0; s2[num]!=‘\0’;num++)
strlength2 = strlength2+1;
if(strlength1==strlength2)
{
while (n<strlength1 && n<strlength2)
{
if(s1[n]<s2[n])
{
strflag=-1;
break;
}
if(s1[n]>s2[n])
{
strflag=1;
break;
}
if(s1[n]==s2[n])
{
strflag=0;
n++;
}
}
printf(“String Comparasion Result : %d”, strflag);
}
else
printf(“String length is not equal.”);
getch();
}
/*****************************************************************************/
OUTPUT :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Run1
Enter First String :
rajasthan
Enter Second String :
jaipur
String length is not equal.
Run2:
Enter First String :
rajasthan
Enter Second String :
karnataka
String Comparasion Result : 1
EXPLANATION :
In program 9.11, two strings, s1 and s2, are compared character by character. A
counter is declared and initialized with zero. When the first character of both strings is
matched. The value of the counter is incremented, and then the subsequent characters
of the strings are compared. This process continues, untill a character is mismatched
in both strings, or until the string is reached. The strflag variable can return any one
of the following values:
(1) 0 (zero): Specifies that both string are equal.
(2) 1: Specifies that the s1 string is greater than the s2 string.
(3) -1: Specifies that the s1 string is less than the s2 string.
9.7.1 strlen()
The strlen() function is used to find out the length of a string. The
syntax to use the strlen() function is as follows:
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
strlen(string_data);
In this syntax, you see that the strlen() function takes a string
parameter to count the number of characters in the string. Program
9.12 shows an example of using the strlen() function:
/*****************************************************************************/
/* Program 9.12 : Displaying the Length of a String */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char s1[100];
clrscr();
puts(“Enter any String : ”);
gets(s1);
printf(“String Length: %d”,strlen(s1));
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Run1
Enter any String :
It is very nice
String Length: 15
Run 2
Enter any String :
Jhunjhunuwala is best publication.
String Length: 34
EXPLANATION :
In program 8.12, the strlen() function takes a string argument, The length of this
string is. The len variable stores the number of characters, which is returned by the
strlen() function. Then, the printf() function is used to display the value stored in
the len variable.
9.7.2 strcmp()
The strcmp() function is used to compare two string data. The syntax
to use the strcmp() function is as follows:
strcmp(string_data1,string_data2);
In the above syntax, you see that the strcmp() function takes
two parameters of strings for comparing. It returns an integer value
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
indicating the relationship between the strings. The returned value can
be zero, greater than zero, or less than zero. A zero value indicates that
the both strings are equal. A value, which is greater than zero, indicates
that the first character that does not match has a greater value in
string1 than in string2. Finally, a value less than zero indicates that
the first character that does not match has lesser value in string1 than
in string2. Program 9.13 shows an example of comparing two strings
by using the strcmp() function:
/*****************************************************************************/
/* Program 9.13 : Using the strcmp() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[80];
clrscr();
printf(“Enter password: “);
gets(s);
if(strcmp(s, “pass”))
printf(“Invalid Password\n”);
else
printf(“Valid Password\n”);
getch();
}
/*****************************************************************************/
OUTPUT :
Run 1
Enter password: pass
Valid Password
Run 2
Enter password: computer
Invalid Password
EXPLANATION :
In program 9.13, a prompt appears to enter a password. If you enter a correct password,
the Valid Password message appears; and if you enter incorrect password, the Invalid
Password message appears. The process of checking the password is performed by
using the strcmp() function.
9.7.3 strncmp()
The strncmp() function is used to compare two strings up to a specified
number of characters. The syntax to use the strncmp() function is as
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
follows:
strncmp(string_data1,string_data2,n);
In the above syntax, you can see that the strncmp() function
compares two string up to the nth character, where n is the number of
characters. This function takes three parameters, where two parameters
are the strings, which have to be compared; and the third parameter
is the number of characters up to which the two strings are compared.
Program 9.14 shown an example of using the strncmp() function for
comparing two strings up to given number of characters:
/*****************************************************************************/
/* Program 9.14 : Using the strncmp() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char s1[50], s2[50];
int n;
clrscr();
puts(“Enter First String :”);
gets(s1);
puts(“Enter Second String :”);
gets(s2);
printf(“Enter the value of n: ”);
scanf(“%d”, &n)
if(!strncmp(s1, s2, n))
printf(“Strings are same.\n”);
else
printf(“Strings are not same.\n”);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Run 1
Enter First String :
rajkumar sharma
Enter Second String :
rajkumar verma
Enter the value of n: 7
Strings are same.
Run 2
Enter First String :
rajkumar sharma
Enter Second String :
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
rajkumar verma
Enter the value of n: 11
Strings are not same.
EXPLANATION :
In program 9.14, user input two string and enter the value to which comparasion is
to be make. In first run user enter the vlaue of n as 7. As you can see that first nine
characters of both strings are same from the beginning. Therefore, the message. The
strings are same, is displayed on the console.
In second run user enter the vlaue of n as 11. So the string are not same, is
displayed on the console.
9.7.4 strcat()
The strcat() function is used to concatenate two strings. The syntax
to use the strcat() function is as follows:
strcat(string_data1,string_data2);
In the above syntax, you can see that the strcat() function takes
two arguments to add second string to first string. This means that
second string is appended to first string and the concatenated string is
stored in the first string. Program 9.15 shows an example of using the
strcat() function for adding two strings:
/*****************************************************************************/
/* Program 9.15 : Using the strcat() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str1[50], str2[50];
clrscr();
printf(“Enter str1: ”);
gets(str1);
printf(“Enter str2: ”);
gets(str2);
strcat(str1, str2);
printf(“\nstr1: %s”, str1);
printf(“\nstr2: %s”,str2);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter str1: What is your name :
Enter str2: Raju
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
EXPLANATION :
In this program two strings, str1 and str2, are entered by user. Then the str2 string
is appended at the end of the str1 string.
9.7.5 strncat()
/*****************************************************************************/
/* Program 9.16 : Using the strncat() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char s1[50], s2[50];
unsigned int len;
clrscr();
printf(“Enter First name : ”);
gets(s1);
printf(“Enter Last name : ”);
gets(s2);
len = 50-strlen(s2);
strncat(s1, s2, len);
printf(“\nFull Name : %s”, s1);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter First name : What is your name ?
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
EXPLANATION :
In program 9.16, two strings, s1 and s2, are provided at the runtime. A variable,
len, is used to store the number of characters, which is obtained by subtracting the
string length of s2 string from the number, 19. The strncat() function takes three
arguments, s1, s2, and len. It adds the characters from the s1 string to the end of the
s2 string, up to the number of characters stored in the len variable.
9.7.6 strcpy()
/*****************************************************************************/
/* Program 9.17 : Using the strcpy() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char first_name[100], last_name[100], full_name[200];
clrscr();
printf(“Enter First Name : ”);
gets(first_name);
printf(“Enter Last Name : ”);
gets(last_name);
strcpy(full_name, first_name);
strcat(full_name, “ ”);
strcat(full_name, last_name);
printf(“\nYou Entered First Name : %s”, first_name );
printf(“\nYou Entered Last Name : %s”, last_name );
printf(“\nFull Name : %s”, full_name);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Run 1
Enter First Name : Mahesh
Enter Last Name : Singh
Run 2
Enter First Name : Mahesh Pratap
Enter Last Name : Singh
EXPLANATION :
In program 9.17, three string variables, first_name, last_name, and full_name are
declared. The first_name and last_name string are provided at the runtime by using
the gets() function. Next, the string stored in first_name string is copied into the
full_name string by using the strcpy() function. Then blank character is append by
strcat() function at the end of first_name Finally, the strcat() function is used to
append the last_name string at the end of the full_name string.
9.7.7 strncpy()
/*****************************************************************************/
/* Program 9.18 : Using the strncpy() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str1[100], str2[100];
int n;
clrscr();
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Enter first string : baba baba black ship have you any wool
Enter second string : twinkle twinkle little star how are wonder what you are
Enter the number of character to be copied : 10
str1: twinkle twblack ship have you any wool
str2: twinkle twinkle little star how are wonder what you are
EXPLANATION :
In program 9.18, two strings, str1 and str2, are provided at the runtime. The
strncat() function takes three arguments, str1, str2, and a number 10. The first 10
characters of the str1 string are copied to the str2 string. Finally, str1 and str2 are
displayed.
9.7.8 strchr()
/*****************************************************************************/
/* Program 9.19 : Using the strchr() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25], ch;
clrscr();
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Run 1
Enter the String : Computer Programming
Enter the character to be searched : r
This string contain this character.
Run 2
Enter the String : Computer Programming
Enter the character to be searched : z
This string does not contain this character.
EXPLANATION :
In program 9.19, the strchr() function is used to search the given character, in the
provided string.
9.7.9 strlwr()
/*****************************************************************************/
/* Program 9.20 : Using the strlwr() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25];
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
clrscr();
printf(“Enter the String : ”);
gets(str);
printf(“\nString in lowercase: %s”, strlwr(str));
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter the String : A Great LOVE
String in lowercase: a great love
EXPLANATION :
In program 9.20, str is a string variable that is provided data runtime. The strlwr()
function is used to convert the string data stored in the str string into lower case.
9.7.10 strupr()
/*****************************************************************************/
/* Program 9.21 : Using the strupt() Function */
/*****************************************************************************/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25];
clrscr();
printf(“Enter the String : ”);
gets(str);
printf(“\nString in Uppercase: %s”, strupr(str));
getch();
return 0;
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Enter the String : A Great LOVE
String in Uppercase: A GREAT LOVE
EXPLANATION :
In program 9.20, str is a string variable that is provided data runtime. The strupr()
function is used to convert the string data stored in the str string into upper case.
9.7.11 strrev()
/*****************************************************************************/
/* Program 9.22 : Using the strrev() Function */
/*****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main ()
{
char str[25];
clrscr();
printf(“Enter the String :\n”);
gets(str);
strrev(str); /*reverse string1*/
printf(“Reverse string is :\n”);
puts(str);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
Enter string : This is a reverse program.
Reverse string is : .margorp esrever a si sihT
EXPLANATION :
In program 9.22, a string variable, str, reads the value at run time using gets()
function. The strrev() function is used to reverse the string stored in the str variable.
Using puts() function reversed string is displayed.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
int l; clrscr();
char string[30]; x=strcmp(strl[], str2[]);
clrscr(); if(x==0)
strcpy(string[30], “My First C program”); printf(“Strings are equal”);
l=strlen(string); else
printf(“%d”, 1); printf(“Strings are not equal”);
getch(); getch();
} }
9.25 What is the output of the program ? 9.29 What is the output of the program?
/*to print the reverse of a string/* #include<stdio.h>
#include<stdio.h> #include<string.h>
#include<conio.h> main ()
#include<string.h> {
main() char str[]=”Computer\0”;
{ int i=strlen(str);
char sl[30], s2[30]; printf(“Str length is %d\n”, ++i);
clrscr(); }
printf(“Enter a string: “);
gets(sl);
s2=strrev(sl);
printf(“\nThe reverse string is:%s”, s2); LAB PROGRAMS
getch();
}
9.1. Write a program which illustrate array initialization
9.26 What is the output of the program?
during compilation.
#include<stdio.h>
#include<conio.h> 9.2. Write a program which illustrate the use of scanf()
#include<ctype.h> and printf() for string Input/Output.
main()
{
9.3. Write a program which illustrate the use of scanf()
char c; and printf() for string I/O. scanf() must accepts
clrscr(); multiword string.
printf(“Enter a character: “);
scanf(“%c”, &c); 9.4. Write a program for conversion of lower case
printf(“%c”, isupper(c)); characters to upper case in a string.
getch();
9.5. Write a program to copy a string using library
}
function strcpy().
9.27 Follwoing program is to print a string. What is the 9.6. Write a program for conversion of a characters
output of the program ? string having digits to its integer equivalent.
#include<stdio.h>
9.7. Write a program which replace lowercase with
#include<conio.h>
main() uppercase and viseversa.
{ 9.8. Write a program for concatenation of strings using
char str[25] ;
library function strcat().
clrscr();
puts(“Enter a string:”) ; 9.9. Write a program to display all consonants in a
gets(str); given line, without using any if.
puts(“\nThe entered string is:”, str);
getch(); 9.10. Write a program to copy a string without using
} library function.
9.28 Following program is to compare two string. What 9.11. Write a program to check a string for palindrome
is the output of the program? using library functions.
/*to compare two strings/* 9.12. Write a program which accept a month number
#include<stdio.h> and display the month name.
#include<conio.h>
#include<string.h> 9.13. Write a program which compare string using library
main() function strcmp().
{
char strl[]=”abc”; 9.14. Write a program to emulate strcmp using functions.
char str2[]=”abc”; 9.15. Write a programme to count number of vowels and
char x=0;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
consonants in the given sentence 9.26. Write a program which search a substring in a
9.16. Write a program to display the length of a string given string and replace all the occurrence of the
and count number of vowels in it. substring by another string of equal length. ( use
library functions ).
9.17. reverse a given string
9.27. Write a program to search a substring in a given
9.18. Write a program which accepts input a person’s string and replace only the first occurrence of the
name in first, middle, last form and display in the substring by another string of equal length. ( use
form last, first, M where M is the first letter in the library functions ).
person’s middle name using built in functions.
9.28. Write a program to rearrange an array without
9.19. Write a program to check a string for palindrome using any temporary array
without using string function.
9.29. Write a program to calculate the frequency of all
9.20. Write a program which accepts a string and a characters in a stream of data.
character and check if that character is present in
the string or not. 9.30. Write a program to count number of characters,words
and lines in a given text multiple blanks between
9.21. Write a program to reverse all strings stored in an words are counted as characters.
array
9.31. Write a program to count number of vowels, blanks
9.22. Write a program to sort names in alphabetical and consonants in a given text.
order.
9.32. Write a program to check for lexical equivalence of
9.23. Write a program to calculate frequency of a two strings without using any library function.
particular character in a stream of data.
9.33. Write a program to concatenate two strings without
9.24. Write a program to decode a brief message using using strlen() and strcat().
substitution cipher.
9.34. Write a program to perform various operations on
9.25. Write a program for encryption and decryption of strings without using language supported built-in
a string. functions.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
10
FUNCTIONS
10.1 INTRODUCTION
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 10.1 : To add two integer using function */
/*****************************************************************************/
#include <stdio.h>
int sum (int a, int b); /* Function Declaration */
int main()
{
int num1, num2, total = 0;
clrscr();
puts(“This program calculate the sum of two number using function.”);
printf(“\nEnter the first number : ”);
scanf(“%d”,&num1);
printf(“\nEnter the second number : ”);
scanf(“%d”,&num2);
total = sum(num1, num2); /* Function Call */
printf(“\nTotal = %d”, total);
getch();
return 0;
}
/* Function Defination */
int sum(int a, int b) /* Function Header */
{ /* Function Body */
int result;
result = a + b;
return result;
}
/*****************************************************************************/
OUTPUT :
This program calculate the sum of two number using function.
Enter the first number : 45
Enter the second number : 35
Total = 80
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 10.2 : Passing Parameter by using call by Value Method */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int area(int length, int breadth)
{
int area_rec;
area_rec = length*breadth;
return(area_rec);
}
void main()
{
int lngth, brdth, result;
clrscr();
printf(“This program is the example of passing parameter call by value method.”);
printf(“Changes made in the formal parameters are not visible outside the
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
function definition.”);
printf(“\nEnter length: “);
scanf(“%d”, &lngth);
printf(“Enter breadth: “);
scanf(“%d”, &brdth);
result = area(lngth, brdth);
printf(“Area of rectangle is: %d”, result);
getch();
}
/*****************************************************************************/
OUTPUT :
This program is the example of passing parameter call by value method. Changes
made in the formal parameters are not visible outside the function definition.
Enter length: 10
Enter breadth: 20
The area of rectangle is: 200
EXPLANATION :
In program 10.2, the area() method created, is invoked by using the call by value
method. The parameters lngth and brdth, which are used invoke the function are
called actual parameters. The argument length and breadth, which are used in the
function definition, are called formal parameters. When the function is called, the
value of the actual parameter is copied into the formal parameter.
/*****************************************************************************/
/* Program 10.3 : Making Changes in formal Parameter */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int area(int length, int breadth)
{
int area_rec;
area_rec = length*breadth;
length = 10;
printf(“\nValue of length inside function definition: %d”, length);
return(area_rec);
}
void main()
{
int length, breadth, result;
clrscr();
printf(“This program is the example of passing parameter call by value method.”);
printf(“\nEnter length: “);
scanf(“%d”,&length);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
This program is the example of passing parameter call by value method.
Enter length: 5
Enter breadth: 6
Value of length before function invocation: 5
Value of length inside function definition: 10
Value of length after function invocation: 5
Area of rectangle is: 30
EXPLANATION :
In program 10.3, the value of the length formal parameter has been changed inside
the function definition. However, this change is not visible inside the main() function
where the area() function is invoked.
ʇ NOTE
Points To be Remember: Using call be value method of
passing values must be preferred
The following points are to be noted while passing arguments to a to avoid inadvertent changes to
function using call-by-value method. variables of the calling function
(1) When arguments are passed by value, the called function creates in the called function.
new variables of the same data type as the arguments passed to
it.
(2) The value of the arguments passed by the function are copied
into the newly created variables.
(3) Values of the variables in the calling functions remain unaffected
when the arguments are passed using call by value technique.
(4) Arguments are called by value when the function does not need
to modify the values of the original variables in the calling
program.
Therefore, call by value method of passing arguments to a function
must be used only in two cases:
(5) When the called function does not modify the value of the actual
parameter. It simply uses the value of the parameters to perform
its task.
(6) When you want that the called function should only temporarily
modify the value of the variables and not permanently. So
although the called function may modify the value of the
variables, but these variables remain unchanged in the calling
program.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 10.4 : Passing Parameter by Using Call by Reference Method
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void main()
{
int num1, num2;
clrscr();
printf(“\nThis program swap the two given number.”);
printf(“\nThis is example of Passing Parameter by Using Call by Reference.”);
printf(“\nEnter First Number : ”);
scanf(“%d”, &num1);
printf(“Enter Second Number : ”);
scanf(“%d”, &num2);
printf(“\nValue of num1 before function invocation: %d”, num1);
printf(“\nValue of num2 before function invocation: %d”, num2);
swap(&num1,&num2);
printf(“\n\n\nValue of num1 after function invocation: %d”, num1);
printf(“\nValue of num2 after function invocation: %d”, num2);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
This program swap the two given number.
This is example of Passing Parameter by Using Call by Reference.
Enter First Number : 10
Enter Second Number : 20
EXPLANATION :
The swap() function is created in Program 10.4 and parameter to this method are
passed by using the call by reference method. You notice that the changes made to the
formal parameters inside the function definition is also reflected in main() function.
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include <stdio.h>
void triple(int [], int); /* declaration of function */
int main()
{
int myArray[100], size, i;
clrscr();
printf(“This program is example of passing array to function.”);
printf(“\nEnter size of array : “)
scanf(“%d”, &size);
printf(“Enter element of Arrays :\n”);
for(i = 0; i < size; i++)
scanf(“%d”, &myArray[i]);
triple(myArray, size);
printf(“After function invocation array is :\n”);
for(i = 0; i < size; i++)
printf(“%d\t”, myArray[i]);
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
This program is example of passing array to function.
Enter size of array : 8
Enter element of Arrays :
8 12 6 15 33 28 19
After function invocation array is :
24 36 18 45 99 84 57
/*****************************************************************************/
/* Program 10.6 : To find the average age of students of a class */
/*****************************************************************************/
#include <stdio.h>
#define SIZE 100
float avg_age(int [],int);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
int main(void)
{
int i,b[SIZE],n;
float average;
printf(“This program calculate the average age of students of a class.”);
printf(“\nEnter Number of Students: ”);
scanf(“%d”,&n);
printf(“\nEnter the age of all students :\n”);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
average = avg_age(b,n);
printf(“\nAverage age of students = %0.2f”, average);
return 0;
getch();
}
float avg_age(int a[], int n)
{
int j;
float sum = 0.0;
for(j=0;j<n;j++)
sum = sum+a[j];
return sum/n;
}
/*****************************************************************************/
OUTPUT :
This program calculate the average age of students of a class.
Enter Number of Students : 5
Enter the age of all students :
14 16 15 18 19
Average age of students = 16.40
/*****************************************************************************/
/* Program 10.7 : Function to find the maximum value in an array. */
/*****************************************************************************/
#include <stdio.h>
int maximum(int [],int); /* function prototype */
int main(void)
{
int values[50], size, i, max;
clrscr();
printf(“This program find the maximum value in given array.”);
printf(“\nEnter the size of Array : ”);
scanf(“%d”, &size);
printf(“\nEnter elements of Array :\n ”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
This program find the maximum value in given array.
Enter the size of Array : 5
Enter elements of Array :
91 104 121 214 58 221
Maximum value is 221.
/*****************************************************************************/
/* Program 10.8 : Function to copy one string into another */
/*****************************************************************************/
#include <stdio.h>
void string_copy(char [], char []); /* function prototype */
int main()
{
char source[100]; /* source string */
char destin[100]; /* destination string */
clrscr();
printf(“This program copy one string to another using function.”);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
This program copy one string to another using function.
Enter Source String : Jhunjhunuwala
Source string : Jhunjhunuwala
Destination string : Jhunjhunuwala
/*****************************************************************************/
/* Program 10.9 : Using Recursive Function */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
long factorial(long n)
{
if(n==1)
return n;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
else
return(n*factorial(n - 1));
}
void main()
{
long n, fact;
clrscr();
printf(“This program calculate the factorial of given number using recursion.”);
printf(“\nEnter a number : ”);
scanf(“%d”, &n);
fact = factorial(n);
printf(“\nFactorial of %d is %l.”, n, fact);
getch();
}
/*****************************************************************************/
OUTPUT :
This program calculate the factorial of given number using recursion.
Enter a number : 5
Factorial of 5 is 120.
EXPLANATION :
In this program, the factorial() function is created to calculate the factorial of a
number using recursive function.
/*****************************************************************************/
/* Program 10.10 : Recursive Function to get nth Term of Fibonacci Series */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int fibo(m)
{
if(m==1 || m == 2)
return(1);
else
return(fibo(m-1)+fibo(m-2));
}
void main()
{
int i,n;
clrscr();
printf(“This program calculate the Fibonacci number using recursion.”);
printf(“\nEnter term number : ”);
scanf(“%d”,&n);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
i = fibo(n);
printf(“\nThe %dth Fibonacci number is %d.”, n, i);
getch();
}
/*****************************************************************************/
OUTPUT :
This program calculate the Fibonacci number using recursion.
Enter term number : 12
The 12TH Fibonacci number is 144.
EXPLANATION :
The fibo() function created in program 10.10 is a recursive function that calculates
the nth term of the Fibonacci series. The variables used in a program behave differently
according to the type and scope.
ʇ NOTE
10.8 RECURSION VS ITERATION Recursion is more of a top-
down approach to problem
Recursion is a very powerful tool for solving complex problem, solving in which the original
problem is divided into smaller
particularly when the underlaying problem or data to be treated
sub-problems. On the contrary,
defined in recursive terms. For such problems, recursion can lead to iteration follows a bottom-up
solutions that are much clearer and easier to modify than their iterative approach that begins with what
is known and then constructing
counterparts. the solution step by step
However, recursive solutions are not always the best solutions.
In some cases, recursive programs may require substantial amount of
run-time overhead. Therefore, when implementing a recursive solution,
there is a trade off involved between the time spent in constructing and
maintaining the program and the cost incurred in running time and
memory space required for the execution of the programs.
Advantage of Recursion :
The advantage of using a recursive program are as following:
• Code is clearer and easier to use.
• Recursive solutions often tend to be shorter and simpler non-
recursive ones.
• Recursion work similar to the original formula to solve a problem.
• In some (limited) instance, recursion may be more efficient.
• Follows a divide and conquer technique to solve problems.
Disadvantage of Recursion :
The disadvantages of using a recursive programs includes the following:
• Using a recursive function takes more memory and time to
execute a compared top its non-recursive counter part.
• For many programmers and readers, recursion is a difficult
concept.
• Recursion is implemented using system stack. If the stack space
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Different types of variables are used in the C program, which have their
associated scope or visibility. The variables declared within a function
or a block of codes are known as local variables. These are visible only
within the function or block of code in which it is declared. However,
the variables declared outside the function are called global variables
and are visible in all the block of codes or functions in the program.
Moreover, the variables that are declared with the static and register
keywords and are called static and register variables, respectively.
Let’s discuss the behavior of these variables with a function under the
following broad level headings:
(1) Local and Global Variables
(2) Static and Register Variables
Local and Global Variables
The functions created in the program including the main() function
of the program, declare variables to store temporary values. These
variables are local variable and are accessible only within the function
it is declared. If any attempt is made to access the variable outside the
function, a compilation error occurs. Following code shows an example
in which the local variable is accessed outside the function and cause
compilation error:
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<stdio.h>
#include<conio.h>
void function1()
{
printf(“%d”, n);
}
void main()
{
int n;
clrscr();
printf(“\nEnter the number”);
scanf(“%d”,&n);
printf(“The number you entered is %d”,n);
function();
getch();
}
/*****************************************************************************/
/* Program 10.11 : Using Local Variable Inside a Function it is Declared */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void functn1()
{
int n=20;
printf(”\nInside Function the value of n is %d.”, n);
}
void main()
{
int n;
clrscr();
printf(“\nEnter the number : ”);
scanf(“%d”,&n);
printf(“\nThe number you entered is %d.”,n);
functn1();
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the number : 25
The number you entered is 25.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 10.12 : Using Global Variable */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
int n;
void functn1()
{
printf(“\nInside Function the value of n is %d.”, n);
}
void main()
{
clrscr();
printf(“\nEnter the number : ”);
scanf(“%d”,&n);
printf(“\nThe number you entered is %d.”,n);
functn1();
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the number : 35
The number you entered is 35.
Inside Function the value of n is 35.
EXPLANATION :
The n variable is declared as a global variable in program 12, and it is accessible from
all the functions in the program.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 10.13 : Using Internal Static Variable */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void functn1()
{
static int result = 1;
result = result*2;
printf(“%d \n”, result);
}
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
functn1();
getch();
}
/*****************************************************************************/
OUTPUT :
2
4
8
16
EXPLANATION :
The result variable in program 13 is declared as the internal static variable inside the
function1 function and is used to calculate the product of numbers up to 4.
/*****************************************************************************/
/* Program 10.14 : Using External Static Variable */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
static int result=5;
void functn1()
{
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
result = result*2;
printf(“%d\n”, result);
}
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
functn1();
getch();
}
/*****************************************************************************/
OUTPUT :
10
20
40
80
EXPLANATION :
The result variable in program 10.14 is declared as an external static variable and is
used to calculate the product of numbers.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
10.13 What do you understand by scope of a variable? 10.3 What is the output of the following code?
Explain in detail with suitable examples. #include<stdio.h>
10.14 What will happen when the actual parameters are #include<conio.h>
main()
less than formal parameters in a function?
{
10.15 How is call by value method of function calling int x, y, sum;
different from call by reference method? Give printf(“\nEnter the numbers: “);
sacanf(“%d”, &x);
suitable examples to support your answer.
scanf(“%d”,&y);
10.16 What is recursion? While writing any recursive sum =add(x,y);
function what thing(s) must be taken care of? printf(“\nThe sum is %d”, sum);
getch();
10.17 What are different categories of functions in C? }
Give examples. int add(int p, int r)
{
10.18 How are the local variables of any recursive int a;
subprogram are interpreted in C? a=p+r;
10.19 Differentiate between local and global variables. return();
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
printf(“%c”,a+65);
10.22 What would be the output of the following program?
}
else #include<stdio.h>
{ #include<conio.h>
printf(“%c”,a+65); fun(int x)
fun(a,f); {
} static int i=2;
} return(x+i++);
main() }
{ void main()
clrscr(); {
fun(10,1); int i, sum=0;
printf(“\n”); int arr[6]={1, 2, 3, 4, 5, 6};
fun(10,0); clrscr();
} for(i=0;i<4,i++)
sum+=fun(arr[i]);
10.19 What would be the output of the following program printf(“SUM=%d”,sum);
}
?
#include<stdio.h> 10.23 What would be the output of the following program
#include<conio.h>
?
char *fun()
{ #include<stdio.h>
char *str; #include<conio.h>
return str=((str=”NITIN”,“AMIT”,“MUKESH”,“ANK fun(int *ptr)
IT”)); {
} int i;
void main(void) for(i=1;i<3;i++)
{ printf(“%d\n”, *(ptr+i));
clrscr(); }
printf(“%s”,fun()); void main()
} {
int arr[]={1, 2, 3, 4, 5, 6, 7, 8, 9};
10.20 What would be the output of the following program clrscr();
fun(arr+1);
?
}
#include<stdio.h>
char fun() 10.24 What would be the output of the following program?
{
static char* str=”ABC\0”; #include<stdio.h>
printf(“%s\n”,str); #include<conio.h>
if(*str++!-=NULL) fun(char *str)
return(main()) {
} return(printf(“%s\n”, str));
main(void) }
{ main()
fun(); {
} char *str=”ABCDEFG”;
clrscr();
printf(“The string size is %d”,fun(str));
10.21 What would be the output of the following program
}
?
#include<stdio.h>
#include<conio.h>
int fun(int *p, int *q) LAB PROGRAMS
{
*p ^= *q, *q ^= *p, *p ^=*q;
} 10.1. Write a program to calculate square of a number
void main(void)
{
using a function.
int a=30, b=40; 10.2. Write a program to illustrate the use of auto
clrscr(); variables.
printf(“before swap=>a=%d\t b=%d\n”,a,b);
fun(&s,&t); 10.3. Write a program to calculate the area and perimeter
printf(“after swap =>a=%d\t b=%d”,a,b); of a circle using function call by reference method.
}
10.4. Write a program to illustrate the use of static
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
11
STRUCTURE AND UNION
11.1 INTRODUCTION
Now you are familiar with basic data types, such as int, float, double,
char etc available in C. You also know that when multiple elements of
same data type are logically grouped together then that group is called
array. For example, int array1[20] is a group of 20 elements. Each
member in this group is of int data type. Now the question is, can
multiple elements of different data types (say one integer element, two
float element) also be combined logically to form a group? Well, this is,
what structure is all about.
All the structures that you use in the program need to be defined first.
General format for defining the structure is given below.
struct structure_name
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
{ data_type_member_1 member_1;
data_type_member_2 member_2;
...................................
...................................
data_type_member_n member_n;
};
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
e.g.
struct student
{
int roll-no;
int age;
char religion;
float fees;
}ram, shyam, geeta;
Like variables of basic data types (int, float, char, etc.), variable of
structure type can also be initialized at the time defined them. The
general format for initializing the variables of structure type, at the
time of their creation, is given below.
storage class struct struc_name variable_name = {value_1, value_2...value_n};
In this format, value_1 is assigned to the first member, value_2
is assigned to the second member and so on. Following is a valid
initialization statement:
struct student ram = {110,20,‘h’, 375.50};
When this statement will get executed, structure member
initialization for variable ram, will take place as follows:
roll_no = 110
age = 20
religiion = ‘h’
fees = 37.5.50
Once the structure has been defined and variable have been created.
Individual members for that variable can be accessed through dot
operator(.). Following is the general format for accessing any member
of structure variable:
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
variable_name.member_name
e.g.
ram.roll_no shyam.roll_no
ram.age or shyam.age
ram.religion shyam.religion
ram.fees shyam.fees
You are now familiar with structures, their definition and methods
of declaring variables of structure type. So let’s write a simple program
to define a structure named employee. The structure have the following
elements in it:
1. employee number (int type)
2. name (character array of 50 elements)
3. age (int type)
4. expression (int type)
5. salary (float type)
Program should create a variable alok of this data type accept
member’s values from keyboard and print them.
/*****************************************************************************/
/* Program 11.1 : Illustrating Structure */
/*****************************************************************************/
#include <stdio.h>
struct employee
{
int empno;
char name[30];
int age;
int experience;
float salary;
}alok;
main()
{
printf(“This program use structure to record the employee details.”);
printf(“\nEnter Employee Number : ”);
scanf(“%i”,&alok.empno);
printf(“Enter Name : ”);
scanf(“%s”,&alok.name);
printf(“Enter age : ”);
scanf(“%d”,&alok.age);
printf(“Enter experience : ”);
scanf(“%i”,&alok.experience);
printf(“Enter salary : ”);
scanf(“%f”,&alok.salary);
printf(“\nEntered data are as below :”);
printf(“\nEmployee No : %i”,alok.empno);
printf(“\nName : %s”,alok.name);
printf(“\nAge : %i years”,alok.age);
printf(“\nExperience : %i years”,alok.experience);
printf(“\nSalary : %g”,alok.salary);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
getch();
}
/*****************************************************************************/
OUTPUT :
This program use structure to record the employee details.
Enter Employee Number : 1204
Enter Name : tarun
Enter age : 29
Enter experience : 4
Enter salary : 15000
Each variable that you operate upon in your C program, occupies some
space in memory. On most of the computers, integer occupies 2 bytes,
character occupies 1 byte, float occupies 4 bytes and double occupies
8 bytes. Often this occupied space is called the size of the variable of
length of the variable. Now the question is, what will be the size or
length of a structure variable? Well, its size can be calculated by adding
up the size of all its members. For example, any variable of employee
type (mentioned in program 1), will be of following size:
size of empno member (2 bytes) + size of name member (30 bytes)
+ size of age member(2 bytes) + size of experience member (2 bytes)
+ size of salary member (4 bytes). Thus the size of the variables, which
are of employee type, will be 2 + 30 + 2 + 2 + 4 i.e. 40 bytes.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Now you are familiar with array of structures, so let’s apply this
concept for handling multiple data items of structure data type in a
program.
Say account department has to keep track of savings done by 30
employees of the organization. For this it maintains following record of
these employees.
1. employee_number
2. Name
3. Earnings
4. Expenditure
Let’s write a program that accepts the data of all the employees
and prints saving amount for them.
/*****************************************************************************/
/* Program 11.2 : Illustrating array of structure */
/*****************************************************************************/
#include <stdio.h>
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
struct employee
{
int empno;
char name[30];
int earning;
int spend;
} emp[25];
void main()
{
int n;
clrscr();
printf(“This program keeps the record of saving of employee.”);
printf(“\nHow many employees are there ? ”);
scanf(“%d”,&n);
readdata(n);
calculate(n);
getch();
}
void readdata(int n)
{
int i;
printf(“Enter data of employee one by one.\n”);
for(i = 0; i < n; i++)
{
printf(“\nEnter employee Number : ”);
scanf(“%i”,&emp[i].empno);
printf(“Enter employee name : ”);
scanf(“%s”,emp[i].name);
printf(“Enter earning amount : ”);
scanf(“%i”,&emp[i].earning);
printf(“Enter Expenditure amount : ”);
scanf(“%i”,&emp[i].spend);
}
return;
}
void calculate(int n)
{
int i, diff;
printf(“\n\n\nSaving of each employee are as follows.”);
for (i = 0; i < n; i++)
{
diff = emp[i].earning - emp[i].spend;
printf(“\n\nEmployee Number : %i”,emp[i].empno);
printf(“\nName : %s”,emp[i].name);
printf(“\nEarning : %i”,emp[i].earning);
printf(“\nExpenditure : %i”,emp[i].spend);
printf(“\nSaving : %i”,diff);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
return;
}
/*****************************************************************************/
OUTPUT :
This program keeps the record of saving of employee.
How many employees are there ? 3
Enter data of employee one by one.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
person1.salary
person1.join_date.day
person1.join_date.month
person1.join_date.year
Since you can now access the members of nested structures hence
you can process them also. Now let’s write a program that accepts
data for 10 employees and prints the details of all those employees,
who joined the organization after 10/10/2002. Code of this program is
shown below.
/*****************************************************************************/
/* Program 11.3 : Nested Structure */
/*****************************************************************************/
#include <stdio.h>
#define size 3
struct ddmmyy
{
int day;
int month;
int year;
};
struct emp
{
int emp_no;
char name[50];
int salary;
struct ddmmyy doj;
} em[size];
void main()
{
int i;
clrscr();
for(i=0; i<size; i++)
{
printf(“\n\nEnter Employee Number : ”);
scanf(“%i”,&em[i].emp_no);
printf(“Enter Name of Employee ID %i : ”, em[i].emp_no);
scanf(“%s”,&em[i].name);
printf(“Enter salary of %s : ”, em[i].name);
scanf(“%i”,&em[i].salary);
printf(“Enter date of joining of %s : ”, em[i].name);
scanf(“%i”,&em[i].doj.day);
printf(“Enter month of joining of %s : ”, em[i].name);
scanf(“%i”,&em[i].doj.month);
printf(“Enter year of joining of %s : ”, em[i].name);
scanf(“%i”,&em[i].doj.year);
}
for(i=0; i<size; i++)
{
if(em[i].doj.year > 02)
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
goto prt;
else if(em[i].doj.year==2 && em[i].doj.month> 10)
goto prt;
else if (em[i].doj.year==2&&em[i].doj.month==10&&em[i].doj.day> 10)
goto prt;
else continue;
prt:
printf(“\n\nEmployee Number : %i”, em[i].emp_no);
printf(“\nName : %s”, em[i].name);
printf(“\nSalary : %i”, em[i].salary);
printf(“\nDate of joining : %i”,em[i].doj.day);
printf(“\nMonth of joining : %i”,em[i].doj.month);
printf(“\nYear of joining : %i”, em[i].doj.year);
}
getch();
}
/*****************************************************************************/
11.11 UNION
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
that union, which has already been defined in the program and the
following variables in the statement have be created, of this union type.
variable_1, variable_2 etc. are the names of variables, which have to
be created of mentioned union type. For example, if shirt and trouser
and the two variables, which have to be defined as detail (earlier defined
as union) type then following statement will have to be written:
union detail
{
int size;
char color[10];
float amount;
} shirt,trouser;
/*****************************************************************************/
/* Program 11.4 : Illustration of Union */
/*****************************************************************************/
#include<stdio.h>
#include<stdlib.h>
union detail
{ int size;
int color[10];
float amount;
};
main()
{
union detail shirt;
/* Section-1: Last accessed member in following section is amount so you will
get the right value of amount. Other two values will be wrong when displayed*/
shirt.size = 42;
strcpy(shirt.color,”Blue”);
shirt.amount = 500.55;
printf(“\n\nShirt size is %d”,shirt.size);
printf(“\nShirt color is %s”,shirt.color);
printf(“\nShirt Amount is %f”,shirt.amount);
/* Section-2: Last accessed member in following section is color so you will
get the right value of color. Other two values will be wrong, when displayed*/
shirt.size = 42;
shirt.amount = 500.55;
strcpy(shirt.color,”Blue”);
printf(“\n\nShirt size is %d”,shirt.size);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Shirt size is 1800256
Shirt color is fF2
Shirt Amount is 500.55
Shirt size is 2771468
Shirt color is Blue
Shirt Amount is 42368989.07234
Shirt size is 42
Shirt color is fX4b
Shirt Amount is 42368080989.07234
EXPLANATION :
If you observe, above program and its result closely, you will analyze the following
points:
1. Out of three given values, program displays only one correct value at a time. For
example, in the first three lines of the result, only the amount value is correct. Rest
of the values (i.e. size and color) are absurd.
2. You may note that the amount value is displayed correctly because the last
member of the union that you accessed before displaying the result was amount.
3. When the last member accessed was color then correct color was displayed, other
two values (i.e. size and amount) were absurd.
4. The same logic was true for size also.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
11.1 Following program is to print the detail of an 11.5 What is the output of the following code ?
employee. What is the output of the program?
#include<stdio.h>
#include<stdio.h> main()
#include<conio.h> {
void main() struct student
{ {
struct employee char name[25];
{ struct date dob;
int emp_no; }stud;
char name[15];
char last_name[15]; struct date
}; {
employee a={115, “ABC”, “XYZ” }; int day, month, year;
printf(“\nThe details of employee: %d %s %s”, };
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
} #include<stdio.h>
main()
11.6 Is the following code legal ? {
struct student
typedef struct srt
{
{
char name[20];
int num;
int age;
type *var;
};
}type
struct student stul={“Param”, 23};
struct student stu2=stul;
11.7 Is the following code legal? if(stul == stu2)
#include<stdio.h> printf(“The structures are equal”);
void main() else
{ printf(“The structures are not equal”);
typedef struct srt type; }
type variable;
struct srt 11.11 What is the output of the program?
{
#include<stdio.h>
int num;
struct student
type *b;
{
};
char class;
}
int age;
long int a;
11.8 Point out the error, if any, in the following code? };
#include<stdio.h> main()
void modify(struct emp*); {
struct student printf(“%d”, sizeof(struct student));
{ }
char name[20];
int age; 11.12 What would be the output of the following code ?
};
#include<stdio.h>
main()
main()
{
{
struct student stu={“Computer”, 35};
union student
modify(&e);
{
printf(“\n%s %d”, e.name, e.age);
int i;
}
char name[9];
void func(struct student *p)
};
{
union student s1={342, Ram};
strupr(p->name);
union student s2={0, Rahim};
p->age=p->age + 2;
}
}
11.13 What is the output of the following code?
11.9 What is output of the program?
#include<stdio.h>
#include<alloc.h>
main()
#include<string.h>
{
#include<stdio.h>
struct student
struct student
{
{
char name[30];
int len;
int age;
char name[1];
float percentage;
};
}
main()
{
struct student xyz;
char newname[]=“Computer”;
xyz.name=“Jhunjhunuwala”;
struct student *p=(struct student*)
xyz.age=25;
malloc(sizeof(struct student)-1 +
printf(“%s %d”, xyz.name, xyz.age);
strlen(newname)+1);
}
p->len=strlen(newname);
strcpy(p -> name, newname);
printf(“\n%d %s”, p -> len, p -> name);
11.14 What is the output of the following code?
} #include<stdio.h>
main()
11.10 What would be the output of the following program {
? struct
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
{
11.18 What is the output of the following code ?
char name[20];
int age=30; #include<stdio.h>
}xyz; #include<conio.h>
static struct xyz={“Rahim”,‘C’}; typedef struct ST
printf(“%s %s”, xyz.name, xyz.age); {
} int sp, ST, sr;
}ST;
11.15 What is the output of the following code?
main()
#include<stdio.h> {
#include<conio.h> ST s;
main() s.ST=l000;
{ s.sp=2000;
struct s s.sr=3000;
{ clrscr();
int u; printf(“%d\n”, s.ST);
int v; printf(“%d\n”, s.sp);
}arr[4]={‘A’,‘M’,‘F’,‘R’,‘J’,‘W’,‘U’,‘H’}; printf(“%d\n”, s.sr);
struct s *p=arr; }
int i;
clrscr();
11.19 What is the output of the following code ?
for(i=0; i<4; i++)
{ #include<stdio.h>
p->u=p->v, ++p++->v; #include<conio.h>
printf(“%c %c\t”, arr[i].u, arr[i].v); struct ST
} {
} int i;
char *s;
11.16 What is the output of the following code ? };
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
11.9. Write a program to illustrate the passing individual
11.21 What is the output of the following code ? structure to a function.
#include<stdio.h> 11.10. Write a program for passing structure to function
typedef enum e{a, b, c, a}d; by value. Here two times are entered in hh mm ss
void main() format and then added up
{
d f; 11.11. Write a program which check a valid date using
f=200; structure.
printf(“%d”, f);
11.12. Write a program to illustrate the use of a structure
}
pointer.
11.22 What is the output of the following code? 11.13. Write a program to illustrate the accessing structure
#include<stdio.h> using pointers.
#include<conio.h>
11.14. Write a program illustrating passing address of a
typedef int fun;
typedef struct fun structure variable.
{ 11.15. Write a program to illustrate passing structure to
fun a;
function by reference. Here seconds are entered as
fun b;
struct fun *c; input and converted to hh mm ss format
}st; 11.16. Write a program to add days to a valid date using
void main()
structure and function.
{
struct fun fl; 11.17. Write a program to which accept time in hh mm ss
struct fun f2; format and then add. Use returning structure from
clrscr();
a function.
printf(“%d %d %d %d”, sizeof(fl), sizeof(struct
fun), sizeof(st), sizeof(f2)); 11.18. Write a program to read employee records using
} array of pointers to structures and display them.
11.19. returning reference to a structure from a function
here rwo times are entered in hh mm ss format and
LAB PROGRAMS then added up
11.20. Write a program to prepare salary chart of daily
11.1. Write a program to maintain employee record and wages employees using array of structures.
print it. 11.21. Write a program to print names and numbers of
11.2. Write a program to determine size of a structure. employees who have 5 years or more experience and
salary less than Rs. 10,000 using array of structures
11.3. Write a program which copy a structure to another
(name, number, experience and salary)
and print these structures.
11.22. Write a program to sort an array of student records
11.4. Write a program which read an employee record
(containing name, rollno, marks, feepaid) based on
using nested structures and print it.
alphabetical ordering of name.
11.5. Write a program which accept student data and
11.23. passing an array of structures as argument to a
evaluate the performance.
function array of structures of students print the
11.6. Write a program to calculate the area of circle, name and roll number of the students who has
rectangle or triangle depending upon the user’s secured highest marks in each subject print the
choice using structures. name and roll number of the student who has
11.7. Write a program which read employee records using secured highest total marks
array of structures and display them. 11.24. Write a program to read 10 players records using
11.8. Write a program which search for a particular array of structures and print a team wise list
employee name and display the record using array containing names of players with their batting
of structures. Assuming identical names do not average.
exist. 11.25. Write a program to maintain record of countries
and capitals using structures
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
12
POINTERS
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
8086 machine (20 bit address bus) would be (in hexadecimal notation)
as follows:
Shift segment value 4 bits to Left.
108D:FFFE -----------> 108D0 + FFFE = 208CE
seg:Off (seg + Off = Absolute address)
ʇ NOTE
12.2 UNDERSTANDING POINTERS One of the disadvantages of
using pointers is that a program
A pointer is a variable that holds the address of another variable stored may crash if sufficient memory
is not available at runtime to
elsewhere in the computer memory. The pointer variable contains only
store pointers.
the address of the referenced variable not the value stored at that
address. Pointers are generally used to point to the variables, such as
array, functions, structures, unions, and the variables of any basic data
type. Some of the advantages of using pointers are as follows:
ʇ Pointers pass information back and forth between a function and
its reference point.
ʇ Pointer provide an alternate way to access individual elements
of the array
ʇ Pointers enable to pass arrays and strings as function arguments.
ʇ Pointers enable the programmers to return multiple data items
from a function via function arguments.
ʇ It enables references to functions. So with pointers, the
programmer can even pass functions as argument to another
function
ʇ Pointers is used to create complex data structures such as trees,
linked list, linked stack, linked queue, and graphs
ʇ Pointer are used for dynamic memory allocation of a variable.
The two basic operators used with pointers are the the address
of operator (&) and the indirection operator (*). The unary operator
& gives the address of an object whereas the unary operator * accesses
the object that the pointer points to.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 12.1 : Declaring a Pointer Variable */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int *ptr, b; /* Pointer declaration */
clrscr();
printf(“Enter any integer : ”);
scanf(“%d”, &b);
ptr = &b;
printf(“\nValue of b is %d.”, *ptr); /* Statement A */
printf(“\nPointer address of b is %d.”, ptr); /* Statement B */
getch();
}
/*****************************************************************************/
OUTPUT :
Enter any integer : 40
Value of a is 40.
Pointer address of a is -12.
EXPLANATION :
In this program, the statement ptr=&b; specifies that the address of the b variable is
assigned to the pointer variable, ptr. Statement A displays the value of the b variable,
and the statement B displays the address of the ptr variable, which is -12 in our case.
This value can differ from computer to computer and time to time.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
collection of storage cells, each cell has an address. When you declare a
variable, the operating system allocates memory according to the size
of the data type of that variable. In this memory location, the value of
the variable is stored. Consider the following statement:
int x = 230;
In the above example, the x variable contains the value, 149. The
printf() function prints the memory location of the x variable because
the x variable is preceded by the address of operator (&). Let’s create a
C program to understand the concept of the & operator. Program 12.2
shows the code of this program:
/*****************************************************************************/
/* Program 12.2 : Using the & Operator */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int var1, *ptr1;
float var2, *ptr2;
clrscr();
printf(“Enter the value for var1 : ”);
scanf(“%d”, &var1);
printf(“\nEnter the value for var2 : ”);
scanf(“%f”, &var2);
ptr1 = &var1;
ptr2 = &var2;
printf(“\nPointer address of var1 is %d and its value is %d.”, ptr1, *ptr1);
printf(“\nPointer address of var2 is %d and its value is %f.”, ptr2, *ptr2);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Enter the value for var1 : 30
Enter the value for var2 : 42.45
The pointer address of var1 is -12 and its value is 30
The pointer address of var2 is -16 and its value is 45.000000
EXPLANATION :
In this program, we have assigned values to an integer and a float variable and print
their addresses and values by using pointers. The ptr1=&var1; statement specifies that
the address of the var1 variable is assigned to the ptr1 pointer variable. Similarly, the
ptr2=var2; statement specifies that the address of the var2 variable is assigned to the
pointer variable, ptr2.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 12.3 : Initializing a Pointer Variable */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int b, *ptr1;
clrscr();
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
ptr1 = &b;
*ptr1=100; /* Pointer Initialization*/
printf(“\nValue of *ptr1 after initializing the pointer variable is %d.”, *ptr1);
printf(“\nValue of b after initializing the pointer variable is %d.”, b);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the value of a : 30
Value of a after initializing the pointer variable is
EXPLANATION :
In program 12.3, the ptr1=&b; statement specifies that the address of the b variable
is assigned to the pointer variable, ptr1. When ptr1 is initialized with the value 100,
the value of the b variable is changed in the memory location.
Now, if you want to use the value that the p pointer variable
points to, you can use the dereference operator * as follows:
printf(“value at p=”, *p);
In this statement, p itself is a variable (it holds the address of an
integer), so a pointer to it can be defined as:
int **q = &p;
You can directly access the value stored in the variable which it
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Figure 12.1 :
In figure 12.1, you can see that the ptr variable is stored at the
address, 10051, and references the address (10056) of the a variable
that contains the value, 100. Let’s create a C program to understand
the concept of dereferencing more clearly. Program 12.4 shows the code
of this program:
/*****************************************************************************/
/* Program 12.4 : Dereferencing a Pointer */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int b, *ptr1;
clrscr();
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
ptr1=&b;
*ptr1=b;
printf(“\nAddress of %d is %d.”, b, ptr1);
printf(“\nValue of %d is %d.”, ptr1, *ptr1);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the value of b : 100
Address of 100 is -12.
Value of -12 is 100.
EXPLANATION :
In program 12.4, the statement ptr1=&b; specifies that the address of the b variable is
assigned to ptr1 and the statement *ptr1=b; specifies that the ptr1 pointer variable
points to the memory location of the b variable to access its value.
/*****************************************************************************/
/* Program 12.5 : Multiplying and Dividing Values within the Pointer */
/* Variables */
/*****************************************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b, mul;
int *ptr1, *ptr2;
float div;
clrscr();
printf(“Enter the value of a : ”);
scanf(“%d”, &a);
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
*ptr1 = a;
*ptr2 = b;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
mul=(*ptr1)*(*ptr2);
div=((float)*ptr1)/(*ptr2);
printf(“\nResult of multiplication is %d.”, mul);
printf(“\nResult of division is %0.2f.”, div);
getch();
}
/*****************************************************************************/
OUTPUT :
Enter the value of a : 8
Enter the value of b : 3
Result of multiplication is 24.
Result of division is 2.67.
EXPLANATION :
In program 12.5, you can see that the value of a is assigned to ptr1 and the value
of b is assigned to ptr2. Then, we have performed the multiplication and division
operations on these values.
12.7.1 Assignment
The assignment operation can be performed on pointer variables in
different ways, such as assignment the address of other variables to a
pointer variable. For example:
int *ptr, a;
ptr = &a;
You can also assign one pointer variable to another only when
both variables point to the object of the same data type. For example:
float *ptr1, *ptr2;
ptr1=ptr2;
You can also assign a Null value to a pointer variable. For example:
int *ptr;
ptr = NULL;
12.7.2 Arithmetic
C allows you to add integers to pointers as well as subtract one pointer
from another. Arithmetic operation on pointers is somewhat different
from the arithmetic operations on regular integer data types. The
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
12.7.3 Comparison
You can compare pointer variables by using relational operators, such
as <, >, <=, >=, and !=. You can compare two variables p1 and p2 by
using expressions, such as p1 > p2, p1 == p2, and p1 !=p2. Such
comparisons are useful when both pointer variables points to elements
of the same array.
Let’s create a C program to understand the different operations
that can be performed on pointer variables. Program 12.6 shows the
code of this application:
/*****************************************************************************/
/* Program 12.6 : Performing Operations on Pointer Variables */
/*****************************************************************************/
# include <stdio.h>
# include <conio.h>
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
void main()
{
int *ptr1, *ptr2;
static int arr[6] = {12, 14, 16, 18, 20, 22};
clrscr();
ptr1 = &arr[2];
ptr2 = &arr[4];
printf(“\nAddress of arr[2] is %d.”, ptr1);
printf(“\nValue of arr[2] is %d.”, *ptr1);
ptr1 = ptr1+3;
printf(“\nAfter addition of 3, address of ptr1 is %d.”, ptr1);
printf(“\nNow value pointed by ptr1 is %d.”, *ptr1);
if(ptr1<ptr2)
printf(“\nAddress %d is less than the address %d.”, ptr1, ptr2);
else
printf(“\nAddress %d is greater than or equals to the address %d.”, ptr1, ptr2);
getch();
}
/*****************************************************************************/
OUTPUT :
Address of arr[2] is 174.
Value of arr{2} is 16.
After addition of 3, address of ptr1 is 180.
Now value pointed by ptr1 is 22.
Address 180 is greater than or equals to the address 178.
EXPLANATION :
In this program, we have declared two pointer variables, ptr1 and ptr2, and an array
of integer data type. The elements of this array are assigned to the pointer variables.
ptr1 and ptr2. After printing the address and value of arr[2], we have incremented
ptr1 by 3 and again printed the address and value of ptr1. Finally, we compare the
address of ptr1 with the address of ptr2.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Void Pointer
A void pointer is a special type of pointer. It can point to any data
type, from an integer value or a float to a string of characters. Its sole
limitation is that the pointed data cannot be referenced directly (the
asterisk * operator cannot be used on them) since its length is always
undetermined. Therefore, type casting or assignment must be used to
turn the void pointer to a pointer of a concrete data type to which we
can refer.
/*****************************************************************************/
/* Program 12.7 : Void Pointer */
/*****************************************************************************/
#include <stdio.h>
int main()
{
int a = 8;
double pi = 3.1415;
void *vp;
vp = &a;
printf(“\nThis program demonstrate the use of VOID pointer.”);
printf(“\na = %d”, *((int *)vp));
vp = π
printf(“\npi = %f”, *((double *)vp));
getch();
return 0;
}
/*****************************************************************************/
OUTPUT :
This program demonstrate the use of VOID pointer.
a = 8
pi = 3.141500
Null Pointer
Null pointers are used in situations where one of the pointers in
ʇ NOTE
the program points to different locations at different times. In such A NULL pointer does not point
situations it is always better to set it to a null pointer when it doesn’t to any valid memory address.
point anywhere valid, and to test to see if it’s a null pointer before
using it.
Null pointer may be declare using the predefined constant NULL,
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 12.8 : Passing a Value by using Call by Reference */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Enter the Two numbers : 45 78
You Entered :
x = 45, y = 78
After swapping :
x = 78, y = 45
EXPLANATION :
In program 12.8, you can see that the values of x and y are exchanged by using their
addresses stored in i and j.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 12.9 : Finding Largest of One-dimensional Array using Pointers */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
main() {
int a[20], i, n, large, p=0;
int *b;
clrscr();
printf(“\nInput array size : ”);
scanf(“%d”,&n);
printf(“\nInput %d array elements :\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
b=a;
large = 0;
printf(“\nEntered array is :\n”);
for(i=0;i<n;i++,b++)
{
printf(“%d\t”,*b);
if(*b>large)
{
large = *b;
p=i+1;
}
}
printf(“\nLargest element is %d at position %d.”,large,p);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Input array size : 10
Input 10 array elements :
123 654 789 741 258 963 147 852 369 520
Entered array is
123 654 789 741 258 963 147 852 369 520
Largest element is 963 at position 6.
EXPLANATION :
In program 10, you can se that we have declared an array of size 20 and a pointer
variable, b. When you enter the values of the array elements, all the values are passed
through the for loop to check for the largest value.
/*****************************************************************************/
/* Program 12.10 : Creating Pointer to Char Array */
/*****************************************************************************/
#include<stdio.h>
main()
{
char a[50];
char *p = a;
int i;
clrscr();
printf(“Enter any string : ”);
gets(a);
printf(“Address of character array and pointer variable are :\n”);
printf(“a = %u and p = %u\n”, a, p);
printf(“\na[i]\t&a[i]\n”);
for(i=0;*p!=’\0’;i++,p++)
printf(“\n%c\t%u”,a[i],p);
getch();
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
Enter any string : kitabwala
a = 65476 and b = 65476
a[i] &a[i]
k 65476
i 65477
t 65478
a 65479
b 65480
w 65481
a 65482
l 65483
a 65484
From the output, it is clear that one byte is needed to store one
character. The for loop in program 12.10 is same as the following code:
for(i=0;*p!=’\0’;i++)
{
printf(“\n%c\t%u”,a[i],p);
p++;
}
/*****************************************************************************/
/* Program 12.11 : Calculating Length of a String using Pointers */
/*****************************************************************************/
#include<stdio.h>
stlength(char *s);
main()
{
char st[100];
clrscr();
printf(“Enter any string : ”);
gets(st);
printf(“\n\nGiven string : %s”, st);
printf(“\nIts length is %d.”, stlength(st));
getch();
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
stlength(char *s)
{
int len = 0;
while(*s != ‘\0’)
{
len++;
s++ ;
}
return(len);
}
/*****************************************************************************/
OUTPUT :
Enter any String : encyclopedia
EXPLANATION :
In program 12.11, we have calculated the length of the string by using pointers.
However, the result is similar to the strlen() function that is used to find out the
length of a string.
/*****************************************************************************/
/* Program 12.12 : Comparing Two Strings using Pointers */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
char a[50],b[50];
char *p,*q;
int i,j,status=0;
p = a;
q = b;
clrscr();
printf(“\nInput two strings : \n”);
gets(a);
gets(b);
for(;*p!=’\0’ || *q!=’\0’;*p++,*q++)
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
if(*p!=*q)
{
printf(“\nGiven strings are different”);
status = 1;
break;
}
if(status==0)
printf(“\nGiven strings are same.”);
getch();
}
/*****************************************************************************/
OUTPUT :
Run1
Input two strings :
computer
computer
Given strings are same.
Run2
Input two strings:
Keyboard
KeyBoard
Given strings are different.
EXPLANATION :
In case if you want to ignore the lower case and the upper case distinction, the
difference between the corresponding uppercase and lowercase values is 32; therefore,
A+32=a or a-A=32.
/*****************************************************************************/
/* Program 12.13 : Converting a String in Uppercase */
/*****************************************************************************/
#include<stdio.h>
void main()
{
char a[50];
char *p;
int i;
p = a;
clrscr();
printf(“\nInput a string : ”);
gets(a);
printf(“\nEntered string : %s”, a);
printf(“\nEntered string in UPPERCASE is : ”);
for(;*p!=’0’;*p++)
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
{
if(*p>=’a’ && *p<=’z’)
*p-=32;
}
puts(a);
getch();
}
/*****************************************************************************/
OUTPUT :
Input a string : computer engineering
/*****************************************************************************/
/* Program 12.14 : Combining Strings using Pointers */
/*****************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
char a[50],b[50],c[100];
char *p,*q;
int i,j;
p = a;
q = b;
clrscr();
printf(“Input two strings :\n”);
gets(a);
gets(b);
for(i=0;*p!=‘\0’;*p++,i++)
c[i]=*p;
for(j=0;*q!=‘\0’;*q++,j++,i++)
c[i]=*q;
c[i]=‘\0’;
puts(“Entered strings are :”);
puts(a);
puts(b);
printf(“Entered strings are :”);
puts(a);
puts(b);
printf(“\nAfter combining : ”);
puts(c)
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Input two strings :
computer
science
Entered strings are :
computer
science
After combining : computerscience
/*****************************************************************************/
/* Program 12.15 : Finding Occurrences of White Spaces in a String */
/*****************************************************************************/
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
char *ch;
int i=0;
clrscr();
printf(“\Enter a string : “);
gets(ch);
while(*ch!=’\0)
{
if(*ch==’ ‘)
i++;
*ch++;
}
printf(“\The total number of white spaces are : %d”,i);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
Enter a string : hello user, how r u?
The total number of white spaces are : 4
EXPLANATION :
In program 12.15, you can observe that the while loop executes until the escape
symbol is found in the string to terminate the string.
When memory is allocated for an array, its base address is fixed and it
cannot be changed during program execution. In other words, an array
ʇ NOTE
name is an address constant. Therefore, its value cannot be changed. An lvalue is an expression to
To ensure that the address of the array does not get changed even which a value can be assigned.
An rvalue can be defined as an
inadvertently, C does not allow array names to be used as an lvalue. expression that can be assign to
Hence, array names cannot appear on the left side of the assignment an lvalue. The lvalue expression
operator. is located on the left side of an
assignment operator, whereas
However, you may declare a pointer variable of appropriate type an rvalue is located on the right
that points to the first element of the array and use it as lvalue. The side of an assignment statement.
following code gives an error as the array name is being used as an
lvalue for the ++ operator.
main()
{
int array1[10], i;
for(i=0;i<10;i++)
{
*array1 = 0;
array1++; /* Error */
}
for(i = 0; i < 10;i++)
printf(“\n %d”, *(array1+i));
}
The following code shows the correct way of doing the same thing.
main()
{
int array1[10], i, *parray1;
parray1 = array1;
for(i = 0; i < 10;i++)
{
*parray1 = 0;
parray1++;
}
for(i = 0; i < 10;i++)
printf(“\n%d”, *(array1+i));
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
lvalue.
int array1[] = {31, 42, 53, 41, 98};
int array2[5];
array2 = array1; /* Error */
When we write ptr2 = ptr1, we are not copying the data pointed
to. Rather, we are just making two pointers point to the same location.
This is shown in following figure.
Figure 12.2 :
Third point of difference lies with the return value of the address
operator. The address operator returns the address of the operand.
But when an address operator is applied to an array name, it gives the
same value as the array reference without the operator. Therefore, arr
and &arr gives the same value. However, this is not true for a pointer
variable.
Last but not the least, the sizeof operator when applied to an
array name returns the number of bytes allocated for the array. But
in case of a pointer variable, the sizeof operator returns the number of
bytes used for the pointer variable (machine dependent). Consider the
the following code which illustrates this concept.
/*****************************************************************************/
/* Program 12.16 : Use of sizeof function with pointer
/*****************************************************************************/
main()
{
int arr[]={1,2,3,4,5};
int *ptr;
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
ptr=arr;
printf(“\n Size of array = %d”, sizeof(arr));
printf(“\nSize of pointer variable = %d”,sizeof(ptr));
}
/*****************************************************************************/
OUTPUT :
Size of array = 10
Size of pointer variable = 2
You are already familiar with the concept of pointers and their
relationship with one dimensional array. You know that the name of
one dimensional array (say b) always points to the first element of the
array. Applying pointer arithmetic i.e. adding 1 to it (i.e. b+1) yields
the address of the second element of the array and so on.
Now the question is, can a relationship between pointers and two
dimensional array be established? Well, the answer is yes. Since two
dimensional array is a group of multiple single dimensional array hence
pointer arithmetic can be devised to point to the second row, third row
etc. of the two dimensional array and all the elements in them. Once
you have correct pointers in hand, you can apply indirection operator
on them to get the values stored in them.
To understand the relationship between pointers and two
dimensional arrays, consider the following definition of two dimensional
array.
int p[3][4];
Using pointers, this definition can be rewritten as follows:
int (*p)[4];
In this declaration, following things will hold good:
(1) p will point to the first row of four elements.
(2) (p+1) will point to the second row of four elements.
(3) (p+2) will point to the third row of four elements.
Now the question is, what points to the elements of the rows?
Well, to understand this, recall that p is a pointer to the first array.
Thus *(p) will be an address. Add 0 to this and you get *(p)+0 i.e.
*(p). This will give the address of the first element of the first row.
Similarly if you add 1 to *(p) i.e. (*(p)+1) will give the address of the
second element of the first row. Thus pointers to the elements of the
first row can be obtained as follow.
(1) (*(p)) points to be first element of the first row.
(2) (*(p)+1) points to be second element of the first row.
(3) (*(p)+2) points to be third element of the first row.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Figure 12.3 :
Now for the elements of second row: The pointer (p+1) points to
the second row of 4 elements. Thus *(p+1) will be an address. Using
pointer arithmetic, add 1 to this i.e. (*(p+1)+1) will point to the second
element of the first row. Thus pointers to the elements of second row
can be obtained as follow:
(1) (*(p+1)) will point to the first element of the second row.
(2) (*(p+1)+1) will point to the second element of the second row.
(3) (*(p+1)+2) will point to the third element of the second row.
(4) (*(p+1)+3) will point to the forth element of the second row.
Similarly performing pointer arithmetic on (p+2) i.e. pointer to
the third row, will yield the pointers to the elements of third row:
(1) (*(p+2)) will point to the first element of the third row.
(2) (*(p+2)+1) will point to the second element of the third row.
(3) (*(p+2)+2) will point to the third element of the third row.
(4) (*(p+2)+3) will point to the fourth element of the third row.
Now, since you have the pointers, Indirection operator can be
applied on them to get the value contained in the element, to which,
they point to. This is illustrated and summarized below.
(1) *(*(p)) will give the value contained in first element of the first
row.
(2) *(*(p)+1) will give the value contained in second element of the
first row.
(3) *(*(p)+2) will give the value contained in third element of the
first row.
(4) *(*(p)+3) will give the value contained in fourth element of the
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
first row.
(5) *(*(p+1)) will give the value contained in first element of the
second row.
(6) *(*(p+1)+1) will give the value contained in second element of
the second row.
(7) *(*(p+1)+2) will give the value contained in third element of the
second row.
(8) *(*(p+1)+3) will give the value contained in fourth element of
the second row.
(9) *(*(p+2)) will give the value contained in first element of the
third row.
(10) *(*(p+2)+1) will give the value contained in second element of
third row.
(11) *(*(p+2)+2) will give the value contained in third element of
the third row.
(12) *(*(p+2)+3) will give the value contained in fourth element of
the third row.
This pointer arithmetic has been applied in the following program.
This program, declares an array of three row and four columns using
pointer. The elements of this array are initialized using pointer first
later their address and contents are printed, using pointers only.
/*****************************************************************************/
/* Program 12.17 : Illustrating Pointer arithmetic in 2 dimensional Array /
/*****************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define row 3
#define col 4
main()
{
int(*p)[4];
int i,j;
int sum = 10;
clrscr();
p = (int*)malloc(row * col * sizeof(int));
for(i=0;i<3;i++)
for(j=0;j<4;j++)
{
*(*(p+i)+j)=sum;
sum = sum + 10;
}
for(i=0;i<3;i++)
{
printf(“\n\nAddress and the contents of the elements of row %d :”, i);
for(j=0;j<4;j++)
{
printf(“\nAddress of element %d is %x. “,j,(*(p+i)+j));
printf(“Value of the element %i is %d.”,j,*(*(p+i)+j));
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
}
}
getch();
}
/*****************************************************************************/
OUTPUT :
Address and the contents of the elements of row 0 :
Address of element 0 is 612. Value of the element 0 is 10.
Address of element 1 is 614. Value of the element 1 is 20.
Address of element 2 is 616. Value of the element 2 is 30.
Address of element 3 is 618. Value of the element 3 is 40.
To get more familiar with the usage of pointer for accessing two
dimensional array let’s consider another program. Let there be an array
of 3 rows and 3 columns. Accept the values of its elements from the
keyboard. Copy its rows into columns of another array (transpose)
Print the new array. Make use of pointers for declaring the processing
functions. Code of this programme is given below :
/*****************************************************************************/
/* Program 12.18 : Illustrating Pointer arithmetic in 2 dimensional Array */
/*****************************************************************************/
#include<stdio.h>
main()
{
int (*mat1)[3];
int (*mat2)[3];
int i,j;
clrscr();
puts(“This program calculate the transpose of 3x3 Matrix.”);
mat1=(int*) malloc(3*4*sizeof(int));
for(i=0;i<3;i++)
{
printf(“Enter 3 elements for row %d : ”,i+1);
for(j = 0; j < 3; j++)
scanf(“%d”,(*(mat1+i)+j));
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
This program calculate the transpose of 3x3 Matrix.
Enter 3 elements for row 1 : 23 56 78
Enter 3 elements for row 2 : 12 45 89
Enter 3 elements for row 3 : 39 61 92
Given 3 X 3 Matrix is :
23 56 78
12 45 89
39 61 92
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
TABLE 12.1 : Comparison between Pointer variable and pointer array Method
/*****************************************************************************/
/* Program 12.19 : Illustrating Pointer Array */
/*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define size 5
void printarr(char *x[]);
void sortarr(char *x[]);
main()
{
int i;
char *x[size];
clrscr();
puts(“This program sort the 5 given name. Name should not contain space.\n”);
for(i =0;i<size;i++)
{
x[i] = (char *)malloc(15*sizeof(char));
printf(“Enter %ith Name : ”,i+1);
scanf(“%s”,x[i]);
}
printf(“\n\nUnsorted name list is as follows :”);
printarr(x);
printf(“\n\nSorted name list is as follows :”);
sortarr(x);
printarr(x);
getch();
}
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
OUTPUT :
This program sort the 5 given name. Name should not contain space.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
this pointer could point to any thing such as variable, array, function
etc.
ʇ NOTE
When a pointer to a function (let’s call this function as guest The advantage of passing
function) is passed to another function (let’s call this function as pointer to function, to another
host function) then the guest function becomes fully available in host function is that using different
pointers (say *p1 to x1 function
function, as if it was a part of it. Concept of passing one function to *p2 to y2 function), different
another, using pointers is illustrated in following figure. guest functions can be made
available in host function to do
multiple type of tasks.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 12.20 : Illustrating Pointer to Function */
/*****************************************************************************/
#include<stdio.h>
float circle_area(int r);
float square_area(int r);
float cost_constrn(float(*ptr)(int r1),float r1,float r2,float r3);
void main()
{
int len;
float amt=0;
char shape;
clrscr();
printf(“This program calculate the cost of construction.”);
printf(“\nArea must be circular or square.”);
printf(“\n\nEnter c for circular area and s for square : ”);
scanf(“%c”, &shape);
if(shape==’c’ || shape==’C’)
amt=cost_constrn(circle_area, 10.00,20.00,30.00);
if(shape==’s’ || shape==’S’)
amt=cost_constrn(square_area, 5.00,10.00,15.00);
if(amt==0)
{
printf(“Wrong input”);
getch();
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
return;
}
printf(“\nTotal cost of construction : %0.2f”,amt);
getch();
}
OUTPUT :
Run 1
This program calculate the cost of construction.
Area must be circular or square.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Run 2
This program calculate the cost of construction.
Area must be circular or square.
Run 3
This program calculate the cost of construction.
Area must be circular or square.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 12.21 : Illustrating Pointer to Structure */
/*****************************************************************************/
#include<stdio.h>
void main()
{
int i, count=0;
int big=0;
struct data
{
int roll_no;
char name[50];
int marks;
};
struct data student[5];
struct data *pstudent[5];
clrscr();
printf(“This program find the topper among a five student list\n.”);
for(i=0;i<5;i++)
{
pstudent[i]=&student[i];
printf(“\nEnter Roll Number : ”);
scanf(“%d”,&pstudent[i]->roll_no);
printf(“Enter Name : ”);
scanf(“%s”,pstudent[i]->name);
printf(“Enter Marks : ”);
scanf(“%d”,&pstudent[i]->marks);
}
for(i=0;i<5;i++)
{ if(pstudent[i]->marks>big)
{
big=pstudent[i]->marks;
count = i;
}
}
printf(“\nTopper Student :”);
printf(“\nRoll No : %d”,pstudent[count]->roll_no);
printf(“\nName : %s”,pstudent[count]->name);
printf(“\nMarks :%d”, pstudent[count]->marks);
getch();
}
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
OUTPUT :
This program find the topper among five student list.
Topper Student:
Roll Number : 104
Name : rajkumar
Marks : 95
Direct access to memory means you can do things that perhaps you
should not. Depending on the language, the compiler and the computer
platform, you could unintentionally (or intentionally) access memory
that is not yours to access. As a result, you could overwrite critical
memory, modify the code of a running application, or cause your
application or another application to behave or exit unexpectedly. One
common error is to run past the end of an array, accessing the memory
beyond the end of the space allocated for that array.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Function Task
malloc() Allocates memory from a pool and returns a pointer to a block of contiguous
memory of the specified size
calloc() Allocates memory for array elements, initializes them to 0, and returns a pointer
to the memory
free() Frees the memory block that are previously allocated by malloc() and calloc()
realloc() Modifies the size of a previously allocated memory block
12.18.1 malloc()
When a C compiler executes a function, the memory is allocated to
local variables. This memory is taken from a free pool. Free pool refers
to a memory that is not used by a program. After completing the
execution, allocated memory is returned to the free pool for subsequent
use. The syntax of malloc() is as follows:
malloc (nob);
where, nob (number of bytes) represents the contiguous memory
locations to be allocated. The malloc() function allocates memory
from a pool. The malloc() function takes integer value as a parameter
that specifies the number of bytes to be allocated. It returns a pointer
to a block of contiguous memory of the specified size. The pointer is
actually of char * type, but it can be cast into any other type as per
requirement. The memory once allocated can be returned to the free
pool by passing the pointer to the free() function. For example,
ptr=(cast-type *), malloc(byte-size);
char *string,
string = malloc(n);
free(string);
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
12.18.2 calloc()
The calloc() function is used for both, to allocate memory for
the array elements and to initialize them to 0. The parameters of the
calloc() function are different from the parameters of the malloc()
function. The syntax of the calloc() function is as follows:
ptr = (cast-type *) calloc(n,element-size);
The receding statement allocates space for n blocks in bytes
where each block is of the size specified by element-size. The calloc()
function initializes all bytes to zero and returns a pointer to the first
byte of the allocated region.
12.18.3 free()
The free() function is used to free the memory blocks that are
allocated by malloc() and calloc(). In a program, if some string or
array of some memory block is no more required, the memory can
be freed using this function. The syntax of the free() function is as
follows:
free (ptr);
where ptr is a pointer created by malloc() or calloc().
12.18.4 realloc()
The realloc() function is used to modify the size of a previously
allocated memory block. The syntax of the realloc() function is as
follows:
ptr = realloc(ptr,newsize);
The above statement allocates a new memory space of size newsize
to the ptr pointer variable and returns a pointer to the first byte of
the new memory block. The newsize may be smaller or larger than the
former size. The new memory block may or may not be allocated at the
same location as the old one. If the function is unsuccessful in locating
additional memory block, it returns a NULL value and the original
block is lost.
Let’s create a C program to learn how these functions are used for
memory management. Program 12.22 shows the code of this program:
/*****************************************************************************/
/* Program 12.22 : Allocating Memory at Runtime */
/*****************************************************************************/
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
main() {
int *x, *y, *z;
int i, num;
clrscr();
printf(“\nThis program add the elements of two array.”);
printf(“\nEnter the number of elements that you want in each array : ”);
scanf(“%d”,&num);
x=(int *) malloc(num *sizeof (int));
y=(int *) malloc(num *sizeof (int));
z=(int *) malloc(num *sizeof (int));
printf(“\nEnter the elements of first array : ”);
for(i=0; i<num; i++)
scanf(“%d”, x+i);
printf(“\nEnter the elements of second array : ”);
for(i=0; i<num; i++)
scanf(“%d”, y+i);
for(i=0; i<num; i++)
*(z+i)= *(x+i) + *(y+i);
printf(“\nNew array after addition : \n”);
for(i=0; i<num; i++)
printf(“%d\t”, *(z+i));
getch();
}
/*****************************************************************************/
OUTPUT :
This program add the elements of two array.
Enter the number of elements that you want in each array : 5
Enter the elements of first array : 2 4 6 8 10
Enter the elements of second array : 1 3 5 7 9
New array after addition :
3 7 11 15 19
EXPLANATION :
In program 17, we have created three one-dimensional arrays, x, y, and z, in which
the first two arrays accept the array elements which are added to create a new array.
The elements resulted from adding the elements of the first two array are stored in
the third array.
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
} int **i;
int *j=0;
12.6 What is the output of the following code? i=&j;
clrscr();
#include<stdio.h>
if(NULL != i && NULL != *i)
main()
printf(“hello”);
{
getch();
void *vod_ptr;
}
int integer=2;
int *ii = &integer;
vod_ptr = ii;
12.12 What is the output of the program?
printf(“%d”, (int*)*vod_ptr); #include<stdio.h>
} #include<conio.h>
void main()
12.7 What would be the output of the following program? {
register i=161;
#include<stdio.h>
register *j=161;
main()
clrscr();
{
printf(“\n%d%d”, &i, &j);
int num=3, *ptr1, *ptr2;
getch();
ptr1=ptr2=#
}
*ptr2+=*ptr2+=num+=4;
printf(“\n%d\t%d\t%d”, num, *ptr1, *ptr2);
}
12.13 What is the output of the program?
#include<stdio.h>
12.8 What would be the output of the following program? void main(); void main (x)
{
#include<stdio.h>
void *v;
main()
v=&x;
{
printf(“%d”, ++*(int *)v);
char *str=”RTUK”;
}
char *ptr=str;
char least=127;
while (*ptr++)
12.14 What is the output of the program ?
least=(*ptr<least)?*ptr:least; #include<stdio.h>
printf(“%d”, least); #include<conio.h>
} main()
{
12.9 What would be the output of the following program? const int *p=5;
int *q;
#include<stdio.h>
clrscr();
void main ()
printf(“\n%d”, p);
{
q=&p;
int num=10, num1=2;
printf(“\n%d”, ++*q);
int *nump= &num, *numlp=&num1;
printf(“\n%d”, p);
int k=*nump/*num1p;
getch();
printf(“%d”, k);
}
}
12.15 What is the output of the program ?
12.10 What is the output of the program?
#include<stdio.h>
#include<stdio.h>
void main()
#include<conio.h>
{
void main()
int const *p=2;
{
*(int *)&p=94;
int a[5]={13, 14, 15, 16, 17};
printf(“\np = %d”, p);
clrscr();
}
printf(“%d\t%d\t\n”, a[a[0|1]-10],3[(a+1)]);
printf(“%d\t%d”,a[1[a]-10]>(*a+2)?(*a<<1)+1:*a,
4[a]);
12.16 What would be the output of the following program?
getch(); #include<stdio.h>
} #include<conio.h>
void main()
12.11 What is the output of the program? {
char str[]=”Peacefull for all”;
#include<stdio.h>
clrscr();
#include<conio.h>
printf(“\n%c”, *(&str[2]));
void main()
printf(“\n%s”, str+5);
{
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
printf(“\n%s”, str); }
printf(“\n%c”, *(str+2));
getch(); 12.21 What would be the output of the following program?
}
#include<stdio.h>
#include<conio.h>
12.17 What would be the output of the following program? main()
#include<stdio.h> {
#include<conio.h> char str[]={‘a’, ‘b’, ‘c’, ‘\0’, ‘d’, ‘e’, ‘f’};
int len(char *p) char *ptr=“Hello”;
{ clrscr();
static int i; printf(“\nstr = %s”, str);
if(i++, *p++!=‘\0’) *++ptr;
len(p); printf(“\nptr = %s”, ptr);
return i; *++ptr;
} printf(“\nptr = %s”, ptr);
main() }
{
char *srcstr=”hihello”; 12.22 What is the output of the program ?
clrscr();
#include<conio.h>
printf(“\nLength = %d”, len(srcstr)-1);
#include<stdio.h>
getch();
main()
}
{
char ch, chl, *p=”abcdef”;
12.18 What would be the output of the following program? clrscr();
#include<stdio.h> ch=*++p;
#include<conio.h> printf(“\nch = %c,\tp = %s”, ch, p);
main() chl=*(++p);
{ printf(“\nch = %c,\tchl = %c,\tp = %s”,ch,chl,p);
char *ptr= ‘2’; }
int i=100, *j=&ptr;
clrscr(); 12.23 What is the output of the program ?
printf(“\n%d”, i/(*j));
#include<conio.h>
getch();
#include<stdio.h>
}
main()
{
12.19 What would be the output of the following program? char ch, ch1, *p=”abcdef”;
#include<stdio.h> clrscr();
#include<conio.h> ch=++*p;
main() printf(“\nch = %c,\tp = %s”, ch, p);
{ chl=++(*p);
char a[2] = “go”, *p= ‘h’; printf(“\nch = %c,\tch1 = %c,\tp = %s”,ch,ch1, p);
clrscr(); ch=(++*p);
p=&a[0]; printf(“\nch = %c,\tch1 = %c,\tp = %s”,ch,ch1,p);
p=a; }
p++;
a=p; 12.24 What is the output of the program ?
a++;
#include<conio.h>
printf(“%c%c\n”, *p, *a);
#include<stdio.h>
getch();
main()
}
{
int **ptr=45;
12.20 What would be the output of the following program? clrscr();
#include<stdio.h> if(**ptr==*ptr[0])
#include<conio.h> printf(“%d”, ptr);
main() }
{
int *p, j;
clrscr();
for(j=0;j<5;j++) LAB PROGRAMS
{
p=(int *) “0”;
printf (“\np=%c”, ++*p);
12.1. Write a program to illustrate the concept of
}
getch(); pointers.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
12.2. Write a program to traversing an array using a in an array using an array of pointers.
pointer. 12.13. Write a program to search for a given character in
12.3. Write a program to illustrate address of ( & ) a string and print the string from start to the point
operator. match.
12.4. Write a program to illustrate the concept of pointer 12.14. Write a program to illustrate the return of pointer
expressions. from a function.
12.5. Write a program to illustrate different types of 12.15. Write a program to reversing an array using
pointers. pointers.
12.6. Write a program to illustrate use of void pointer for 12.16. Write a program to sort the strings (weekdays)
int and float types. alphabetically using array of pointers. Sort the
12.7. Write a program to illustrate pointer to a pointer. pointers to the string, not the actual string.
12.8. Write a program to illustrate dynamic memory 12.17. Write a program for binary search recursively
allocation. on a sorted array given in ascending order using
pointers.
12.9. Write a program for manipulation of an array using
a pointer. 12.18. Write a program for bubble sort using pointers.
12.10. Write a program to find sum of N elements of an 12.19. Write a program for binary search on a sorted array
array A using pointer. given in ascending order using pointers.
12.11. Write a program to print array elements being to 12.20. Write a program for insertion in a sorted array
by an array of pointers. given in ascending order array remains sorted after
insertion.
12.12. Write a program to exchange the position of string
***********
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
13
FILE HANDLING
13.1 INTRODUCTION
Till now we had been dealing with the programs, which held the input-
data temporarily. As soon as the program came to end, the data got
lost. For example, if you enter student’s roll number, name and marks,
using scanf statement, the data will remain available till the time
program is running. As soon as the program will end, these values
will not be available. While writing programs for real life situations,
you will often come across situations, when you will have to hold the
data permanently. For holding the data permanently, you have to read
the data from the keyboard (as we used to do), write it in a file and
later, whenever required, read the data from file. C language supports
different types of file handling operations for using files. Their details
are described in this chapter.
C supports three different types of data files, using which you can
ʇ NOTE
hold the data permanently on media and make use of it as and when Since text files are ASCII files
required. These files are: hence you can view them on
your computer screen.
(1) Text Files
(2) Variable Record length files
(3) Constant record length files
Text files are also called stream oriented data files. In there files the
data is written as stream of characters and it is read as stream of
characters. A typical Text file many look like as follows:
Jhunjhunuwala is a text book publishing organization. It has high turnover with high growth
rate. It is committed to deliver good quality content books and promote good books India.
Recall the nature of the files that you create through text editors
and note that the text file mentioned above is just equivalent to any
text editor file. You can create a text file through your system text
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
editor and read them through a C program also or you can create a text
file through a C program and read it through your system text editor.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
Mode Meaning
“w” Opens the file for writing only. If the mentioned file already exists then it will destroy
that and create a fresh a fresh file for writing.
“w+” Opens the file for both reading and writing. If the mentioned file already exists then it
will destroy that file and create a fresh file for writing.
“a” Opens the file for appending. If the file with mentioned file name does not exist then a
fresh file will be created.
“a+” Opens the file for reading and appending. If the file with mentioned file name does not
exist then it creates a fresh file for operations.
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')
$GGLQ<RXU&ODVV*URXSWRJHWDOO3')RIQG6HPHVWHU7H[%RRNVDQG6ROYHG3DSHUV
/*****************************************************************************/
/* Program 13.1 : Illustration of fopen and writing to file */
/*****************************************************************************/
#include <stdio.h>
'RQW3XUFDKVHDQ\7H[W%RRNRU6ROYHG3DSHUIRUQG6HPHVWHU6WXG\IURP%HVW%RRNV3')