Vous êtes sur la page 1sur 21

ARADHYA’s

C Programming
&
Data Structures
A simplified approach
ARADHYA’s

C Programming
&
Data Structures
A simplified approach

Manjunath Aradhya M.
Former Faculty,
Department of Computer Science and Engineering,
RNS Institute of Technology, Bangalore

Srinivas Subramanya
Formerly Consultant,
Siemens India Private Limited

Ravi Shankar Aradhya


Former Faculty,
Department of Information Science and Engineering,
RNS Institute of Technology, Bangalore

Sanguine Technical Publishers, Bangalore.


2014
Price: ` 290.00

ARADHYA’S C Programming & Data Structures A simplified approach


Manjunath Aradhya M.
Srinivas Subramanya
Ravi Shankar Aradhya
This book contains information obtained from authentic and highly regarded sources. Reprinted material is
quoted with permission, and sources are indicated. Reasonable efforts have been made to publish reliable data
and information, but the author and the publisher cannot assume responsibility for the validity of all materials or
for the consequences of their use.
Neither this book nor any part may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, microfilming and recording, or by any information storage or retrieval
system, without prior remission in writing from the publishers.
The consent of SANGUINE TECHNICAL PUBLISHERS does not extend to copying for general distribution,
for promotion, for creating new works, or for resale. Specific permission must be obtained in writing from
SANGUINE for such copying.

Direct inquiries: E-mail info@sanguineindia.com.

Visit our website at www.sanguineindia.com


© 2014 by Sanguine Technical Publishers, Bangalore – 560 016.

Published by Lal Prasad for Sanguine


Production Editor: R.Subramanian
Typeset by Sharvani Inc., Bangalore
Dedicated to

- Guru Shree Agastya Maharshi -

and

Our Students
Preface

Came the year 1972 and Dennis Ritchie released his amazing language to the
programming world ‘The C language’ which is the brightest star even today in the world
of programming.
Despite the presence of numerous other programming languages, C has retained its
identity and shines bright even till date.
Since the invention of C, many authors have written numerous books on C and tried
simplifying the concepts for learners. It was a long time dream of ‘Team Aradhya’ to give
the student community a book which is simple, readable and at the same time enjoyable.
We strongly believe that we have done no compromise on this dream and we have worked
to our fullest potential to convert this dream to reality.

ABOUT THE BOOK AND THE INTENDED AUDIENCE


The book has been presented in such a way that any student with no knowledge of
programming will find it very easy to comprehend. The approach has been to simplify and
convey all the concepts. To augment this, sufficient diagrams, and class-tested programs
along with the outputs are provided. Similar to how the raw materials enter at one end of
the machine, and comes out at the other end as finished product, any beginner reading this
book would come out as strong programmer by the time the last page of the book is reached.
The book also serves as a base material for students who are preparing for placements (in
campus/off campus).
The organization of chapters and presentation of the matter reflects our rich practical
as well as teaching experience on C. During the development of this manuscript, even
the minute details were given the utmost importance. Inputs have also been taken from
professors, students and working professionals during the preparation of this book which
makes the book ‘very unique, elite and student-friendly’.
All the programs given in the chapters are tested for proper working along with
screen shot outputs. Visual studio 2005, a standard and widely popular compiler is used to
execute and test all the programs of this book. Here, we present this very special book for
our beloved students and hope they enjoy reading the book.
Happy learning
      Team Aradhya
Acknowledgements
Writing this book has been one of the unforgetable experiences of our life. It has
been a journey of unravelling our inner strengths and potential. We can just say that we had
experienced the truth in saying that ‘Where there is a will, there is a way’. But this journey
would not have been easy as it was without the help of many people who were instrumental
in transforming our dreams into reality.
We cannot forget the contributions of our students who reviewed our manuscripts and
gave us valuable suggestions for making this book a reality. We also thank the eff orts and
constant support of our colleagues Rudresh, Subramanya Raj, Sridhar K.R. , Vijay Kumar,
Vijay, Vishal Patekar, Nitesh and ABC for Java and Testing staff.
We take this opportunity to thank the editorial, sales and the production editorial
teams at Sanguine, for their painstaking work in bringing out this book in record time with
excellent formaing. A special and heart filled thanks to Mr. Gajanan Bhat and Mrs. Sumathi
Bhat for making this book look beautiful. Anyone who has written a book would know
about the amount of time and effort that goes into such a task. Anyone related to the authors
would tell at whose expense that time was spent. We thank our parents and all our loved
ones for standing by us and giving us unbounded love and unconditional support. Here we
fall short of words while expressing our acknowledgements. Probably some feelings are
better expressed in silence than in words.
About the Authors

Manjunath Aradhya M. has served in the Department of


Computer Science and Engineering, RNS Institute of Technology,
Bangalore. He worked as business associate with Wipro Technologies
and also a corporate trainer to many other leading soft ware firms.
He is the founder and chairman of Aradhya Tutorials, Aradhya Consultancy
and Training Services. He is the founder of ABC for Java and Testing,
which is the finishing school that bridges the gap between Engineering
curriculum and IT industry needs. He has been providing technical
assistance to placement cells of various engineering colleges. His areas of
interest in the field of computer science include system software, data structures, microprocessors,
analysis and design of algorithms, finite automata and formal languages, compiler design, DBMS,
Java and C++.

Srinivas Subramanya has served as a consultant at Siemens


India Private Limited. He has been awarded the best programmer for
his skills in programming and debugging. He has been a part of various
C++ Medical Imaging projects at Siemens. He is a part of Aradhya
Tutorials, Aradhya Consultancy and Training Services. He is the
co-founder of ABC for Java and Testing, which is the finishing school
that bridges the gap between Engineering curriculum and IT industry
needs . His areas of interest in the field of computer science include
system software, C++, computer networks, operating systems, system
programming, web programming, computer organization and design patterns.

Ravi Shankar Aradhya has served in the Department of


Information Science and Engineering, RNS Institute of Technology
and SJB Institute of Technology, Bangalore. He has been awarded
‘The best teacher of the year 2008’ at RNSIT. He is a part of Aradhya
Tutorials, Aradhya Consultancy and Training Services. He is the
co-founder of ABC for Java and Testing, which is the finishing
school that bridges the gap between Engineering curriculum and IT
industry needs. His areas of interest in the field of computer science
include C, C++, UNIX, logic design, file structures, microcontroller,
C# and Java.
FEEDBACK
It is extremely difficult to digest the criticism of one’s manuscript. But it is also a fact that
no manuscript can be totally perfect in itself. ‘To err is human’ so we would always be looking
forth for positive criticism from our teaching fraternity, students and anybody referring to this
book. Please do email your views, suggestions and comments about the book to this email
teamaradhya@gmail.com
or
info@sanguineindia.com
Table of Contents

1 Introduction to C language
_______________________________
ALGORITHM..........................................................................................1-3
HOW TO WRITE AN ALGORITHM? (OR) ALGORITHMIC NOTATION.....................1-3
PURPOSE (NEED) FOR WRITING AN ALGORITHM.....................................................1-9
FLOWCHARTS......................................................................................................................1-9
Geometric figures (Notations) used in a flowchart...............................................1-9
Advantages of flowcharts ...................................................................................1-14
Disadvantages of flowcharts................................................................................1-15
DIVIDE AND CONQUER Strategy ..................................................................................1-15
Constants, variables and data types.....................................................................1-16
Character set of C language (or) alphabets of C language.................................1-18
C-tokens................................................................................................................1-19
KEYWORDS........................................................................................................................1-19
Identifiers..............................................................................................................1-20
RULES FOR CONSTRUCTING IDENTIFIERS (VARIABLE NAMES)........................1-21
CONSTANTS.......................................................................................................................1-22
Data type...............................................................................................................1-24
DECLARATION OF A VARIABLE ..................................................................................1-25
SOME SIMPLE C PROGRAMS.........................................................................................1-26
THE FIRST C PROGRAM..................................................................................................1-27
OPERATORS AND EXPRESSIONS..................................................................................1-29
Arithmetic operators.............................................................................................1-31
CONVERSION OF MATHEMATICAL (ALGEBRAIC) EXPRESSIONS TO
     C LANGUAGE EXPRESSIONS.........................................................................1-33
RELATIONAL OPERATORS..............................................................................................1-33
Logical operators..................................................................................................1-35
ASSIGNMENT OPERATOR...............................................................................................1-37
xii Programming In C and Data Structures

Increment operator (++)....................................................................................... 1-40


Decrementation operator...................................................................................... 1-43
Conditional operator (?:)...................................................................................... 1-46
Bitwise operators.................................................................................................. 1-47
SPECIAL OPERATORS IN C.............................................................................................1-51
TYPE CONVERSION IN EXPRESSIONS........................................................................1-52
ARITHMETIC EXPRESSIONS..........................................................................................1-55
ARITHMETIC OPERATORS PRECEDENCE...................................................................1-55
EVALUATION OF EXPRESSION CONTAINING ONLY RELATIONAL
     OPERATORS........................................................................................................1-58
EVALUATION OF EXPRESSION CONTAINING ARITHMETIC
      AND RELATIONAL OPERATORS....................................................................1-59
ARITHMETIC AND RELATIONAL OPERATORS..........................................................1-60
THE PRECEDENCE OF OPERATORS AND THEIR ASSOCIATIVITY.......................1-61
MATHEMATICAL FUNCTIONS.......................................................................................1-62
ADDITIONAL PROBLEMS ON OPERATOR EVALUATION........................................1-63
PREVIOUS EXAMINATION QUESTIONS......................................................................1-65
Other Review Questions...................................................................................... 1-67

2 Branching and Looping


_______________________________
READING AND WRITING A CHARACTER.....................................................................2-3
TO READ A CHARACTER FROM THE KEYBOARD.....................................................2-5
TO DISPLAY A CHARACTER ON THE MONITOR........................................................2-5
FORMATTED INPUT AND FORMATED OUTPUT..........................................................2-5
THE printf( ) FUNCTION..................................................................................... 2-5
THE scanf( ) FUNCTION................................................................................... 2-10
ADVANTAGES OF FORMATED I/O FUNCTIONS........................................................2-11
DECISION CONTROL CONSTRUCTS............................................................................2-11
SIMPLE CALCULATION PROGRAM  . ........................................................................2-29
UNCONDITIONAL CONTROL CONSTRUCTS . ...........................................................2-32
Table of Contents xiii

ROOTS OF QUADRATIC EQUATION.............................................................................. 2-35


LCM AND GCD PROGRAM.............................................................................................. 2-52
Program to check whether the number is prime or not....................................... 2-55
FIBONACCI NUMBERS PROGRAM ............................................................................... 2-58
PALINDROME PROGRAM................................................................................................. 2-62
BREAK AND CONTINUE.................................................................................................. 2-70
PREVIOUS EXAMINATION QUESTIONS....................................................................... 2-74
Other Review Questions....................................................................................... 2-75

3 Arrays
_______________________________
Let us proceed further............................................................................................. 3-3
Declaration of one dimensional array..................................................................... 3-4
Initialization of a one dimensional array................................................................ 3-4
Programs on Arrays................................................................................................... 3-6
SEARCHING TECHNIQUES.............................................................................................. 3-11
BINARY SEARCH PROGRAM.......................................................................................... 3-14
POLYNOMIAL PROGRAM................................................................................................. 3-17
BUBBLESORT PROGRAM................................................................................................. 3-21
Two dimensional arrays........................................................................................ 3-24
DECLARATION OF A TWO - DIMENSIONAL ARRAY................................................. 3-27
INITIALIZATION OF TWO DIMENSIONAL ARRAYS-................................................. 3-27
PROGRAMS ON 2-D ARRAYS.......................................................................................... 3-29
MATRIX MULTIPLICATION PROGRAM......................................................................... 3-35
Strings.................................................................................................................... 3-39
I/O functions ........................................................................................................ 3-41
strlen( ).................................................................................................................. 3-44
strcpy( ).................................................................................................................. 3-44
strncpy( )................................................................................................................ 3-45
strcmp().................................................................................................................. 3-45
stricmp()................................................................................................................. 3-46
xiv Programming In C and Data Structures

strncmp( )............................................................................................................... 3-47


strnicmp( ).............................................................................................................. 3-48
strlwr( )................................................................................................................... 3-49
strupr( )................................................................................................................... 3-50
strcat( ).................................................................................................................... 3-50
strrev( )................................................................................................................... 3-51
strset( ).................................................................................................................... 3-52
strnset( ).................................................................................................................. 3-53
Programs on strings................................................................................................ 3-54
Program to reverse a string without using strrev.................................................. 3-54
Program to check whether string is palindrome or not........................................ 3-55
Program to copy one string to another without using strcpy .............................. 3-57
Program to compare two string without using strcmp.......................................... 3-58
FUNCTIONS..........................................................................................................................3-59
A MULTI- FUNCTION PROGRAM....................................................................................3-61
Outputs of above given structured and non structured programs......................... 3-62
FUNCTION CALL OR FUNCTION SIGNATURE.............................................................3-65
FUNCTION DEFINITION OR FUNCTION BODY...........................................................3-66
FUNCTION DECLARATION OR FUNCTION PROTOTYPE..........................................3-66
CATEGORY OF FUNCTIONS.............................................................................................3-69
Function with no arguments and no return value................................................. 3-70
Functions with arguments but no return value...................................................... 3-71
Functions with arguments and with return value.................................................. 3-72
Functions with no arguments (parameters) but returns a value............................ 3-73
SELECTION SORT PROGRAM..........................................................................................3-87
MEAN, VARIANCE, DEVIATION PROGRAM.................................................................3-90
MATRIX MULTIPLICATION PROGRAM..........................................................................3-95
ROW SUM, COLUMN SUM PROGRAM.........................................................................3-100
BENEFITS OF FUNCTIONS..............................................................................................3-105
Recursion.............................................................................................................. 3-105
The efficiency of recursion ................................................................................. 3-129
Table of Contents xv

Differentiate between recursion and iteration.....................................................3-130


Previous Exam Questions....................................................................................3-130
Other Review Questions......................................................................................3-132

4 Structure and File Management


_______________________________
Files Operations . ................................................................................................4-15
fopen().....................................................................................................................4-16
fclose()....................................................................................................................4-17
fscanf()....................................................................................................................4-17
fprintf()...................................................................................................................4-18
getc().......................................................................................................................4-19
putc().......................................................................................................................4-20
fgets()......................................................................................................................4-21
fputs()......................................................................................................................4-22
Write a C program to copy contents of one file into another..............................4-22
Write a program to count the number of characters, number of lines and
          number of white spaces from a file.....................................................4-24
Questioins...............................................................................................................4-25

5 Pointers and Preprocessors


_______________________________
How can we obtain the contents a memory location and the address
          of a memory location ? . .......................................................................5-4
Write the program to print the contents and address of a memory location-........5-4
What is a POINTER and how to use it? ...............................................................5-5
Some common mistakes created while working with pointers- . ..........................5-7
Pointer declaration and definition............................................................................5-7
Initialization of pointer variables-............................................................................5-8
What is the difference between a pointer variable and a normal variable .........5-13
xvi Programming In C and Data Structures

Pointers and functions (call by reference)........................................................... 5-13


Passing structures by reference............................................................................ 5-15
Malloc( )............................................................................................................... 5-39
Calloc( )................................................................................................................ 5-40
Realloc( ).............................................................................................................. 5-42
Free( )................................................................................................................... 5-45
Datatypes.............................................................................................................. 5-48
Stacks.................................................................................................................... 5-48
Stack program....................................................................................................... 5-50
Queues.................................................................................................................. 5-53
Display operation................................................................................................. 5-60
Advantages of ordinary queue:............................................................................ 5-62
Disadvantages of ordinary queue:........................................................................ 5-62
Delete at rear........................................................................................................ 5-74
Tree....................................................................................................................... 5-79
Questions.............................................................................................................. 5-80

Lab Programs................................................................................................................ L-1

ASCII Tables......................................................................................................................T-1

Model Question Paper.............................................................................................. M-1

Index.....................................................................................................................................I-1
1 Introduction to C language

Chapter Objectives
 Algorithms
 Flowchart
 Divide and conquer strategy
 Writing Algorithms and Drawing
 Flowcharts for
(( Swapping contents of 2 variables
(( Largest of given 3 numbers
(( Solving a given quadratic equation

(( Factorial of a given integer


 Characters set, Keywords and Identifiers
 Constants
 Variables
 Data types
 Declaration of variables
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and Decrement operators
 Conditional operators
 Bitwise operators
 Special operators
 Arithmetic expressions
 Evaluation of expressions
 Precedence of arithmetic operator
 Type conversions in expressions
 Operators, precedence and associativity

Pr in C and Data Structure.indd 1 23/09/2014 03:47:49 PM


1-2 Programming In C and Data Structures

There have been numerous examples in the past where human beings have used either living
Module 1

or non-living objects as tools to overcome their inherent disabilities. Computers are just one of the
latest tools being designed and used by us to overcome our inherent disability.
The main disability of we human beings is that most of us cannot perform large and
complicated computations accurately and quickly. So we have designed a tool called the computer
which can perform computations with a very high accuracy and speed. However computers will have
to be given instructions to perform computations. These set of instructions given to the computer to
perform computations is technically called a program.
However, the programmer cannot start to write a program directly. He has to meticulously
plan before writing a program. This is some what similar to the fact that if a person decides to
construct a house, the very next day, he would not start to construct the house directly. He has to
meticulously plan each and every minor detail before proceeding to construct the house. Once the
entire plan (sketch) of the house is ready, then he can proceed and construct the house.
Similarly before writing a program, the programmer has to plan the steps and the sequence in
which these steps must be performed to obtain the correct results. If the programmer skips (forgets)
a few steps or performs the steps in a wrong sequence, then the computer would produce a wrong
result.
Hence, programs must be planned before they are written. During this process of planning,
the programmer must first try to write an algorithm, then a flowchart, then try to convert the
flow-chart to a program.
So, the sequence of steps involved in problem solving are as given below:

Understand the problem

Express the solution to the problem in the form of an algorithm

Express the algorithm pictorially in the form of a flow chart

Express the flow chart in the form of a program

Feed the program to a computer

Obtain the results

Pr in C and Data Structure.indd 2 23/09/2014 03:47:49 PM


Introduction to C language 1-3

Hence in one-word, algorithms and flowcharts are the initial preparatory steps taken by the

Module 1
programmer before writing the actual program. First writing an algorithm then a flowchart to a
problem and then writing a program to that problem makes programming easier, rather than directly
writing a program.

ALGORITHM
Is defined as a sequence of unambiguous instructions designed in such a way that if the
instructions are performed in the specified sequence, the desired results would be obtained.

However it is important to note that an algorithm cannot be directly fed into the computer for
its execution. An algorithm just represents the logic to solve a problem in step by step manner.

Characteristics (Properties) of an algorithm


An algorithm must possess the following properties.
1. Each an every instruction must be precise and unambiguous.
2. There should not be any uncertainty about which instruction is to be executed next.
3. Each instruction should be such that, its execution time is finite.
4. One or more instruction should not be repeated infinitely. In other words, the
algorithm must finally terminate (conclude).
5. An algorithm may accept zero or more input but must compulsorily produce an output finally.
6. An algorithm must be general enough to accept any type of input and produce a
corresponding output.

HOW TO WRITE AN ALGORITHM? (OR) ALGORITHMIC NOTATION


Every algorithm has to follow the following notation - (general form) :
1. The name of the algorithm must be specified.
2. Step number must be given to each step for the sake of identification of the step.
3. Each step must have an explanatory note provided within the square brackets followed by the
corresponding operation.
4. The completion of an algorithm must be specified towards the end, using a stop statement
The above steps would become clear with the following example

Example 1 : to compute the area of a circle.


Logic: T
 he area of a circle with radius r can be computed using the formula area = πr2.
Where π value is 3.141.

Pr in C and Data Structure.indd 3 23/09/2014 03:47:49 PM


1-4 Programming In C and Data Structures

Algorithm
Module 1

Algorithm: Area of circle


Step 1: [input the radius]
      read r
Step 2: [compute the area]
      area = 3.141 * r * r:
Step 3: [output the result]
      print area
Step 4: [finished] stop

Thus, you can notice that an algorithm is a sequence of unambiguous steps which if executed
in the specified sequence will produce the desired results.

Example 2: Write an algorithm to compute the simple interest.


ptr
Logic: Simple interest can be computed using the formula si = .
100
Algorithm

Algorithm: Simple interest


Step 1: [
input principle, time and rate
of interest]
Read p, t and r
Step 2: [
compute the simple interest]
si=(p*t*r)/100
Step 3: [
output the result]
print si
Step 4: [
finished]
stop

Example 3: Write an algorithm to swap (exchange) the contents of


2 variables.
Logic: Assume that the given 2 numbers are a and b, their values can be exchanged using

temp = a, a = b, b = temp.

Pr in C and Data Structure.indd 4 23/09/2014 03:47:49 PM


C Programming & Data Structures

50%
OFF

Author : Manjunath
Aradhya, Srinivas
Publisher : Sanguine Publishers ISBN : 978938350624 8
Subramanya & Ravi
Shankar Aradhya

Type the URL : http://www.kopykitab.com/product/5995

Get this eBook