Ebook Programming in C Third Edition Kamthane Online PDF All Chapter
Ebook Programming in C Third Edition Kamthane Online PDF All Chapter
Ebook Programming in C Third Edition Kamthane Online PDF All Chapter
Kamthane
Visit to download the full and correct content document:
https://ebookmeta.com/product/programming-in-c-third-edition-kamthane/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...
https://ebookmeta.com/product/programming-scala-scalability-
functional-programming-objects-third-edition-wampler-dean/
https://ebookmeta.com/product/functional-programming-in-c-2nd-
edition-enrico-buonanno/
https://ebookmeta.com/product/functional-programming-in-c-second-
edition-enrico-buonanno/
https://ebookmeta.com/product/c-programming-in-linux-2nd-edition-
david-haskins/
Programming in ANSI C 8th Edition E Balagurusamy
https://ebookmeta.com/product/programming-in-ansi-c-8th-edition-
e-balagurusamy/
https://ebookmeta.com/product/selenium-webdriver-recipes-in-c-
third-edition-courtney-zhan/
https://ebookmeta.com/product/functional-programming-in-c-with-
categories-dimitris-papadimitriou/
https://ebookmeta.com/product/c-programming-in-easy-steps-fifth-
edition-mike-mcgrath/
https://ebookmeta.com/product/c-programming-in-easy-steps-6th-
edition-mike-mcgrath/
PROGRAMMING IN C
third Edition
Ashok N. Kamthane
Associate Professor
Shri Guru Gobind Singhji Institute of Engineering
and Technology, Nanded, Maharashtra, India
ISBN 978-93-325-4355-3
First Impression
Published by Pearson India Education Services Pvt. Ltd, CIN: U72200TN2005PTC057128, formerly
known as TutorVista Global Pvt. Ltd, licensee of Pearson Education in South Asia.
Head Office: A-8(A), 7th Floor, Knowledge Boulevard, Sector 62, Noida 201 309, Uttar Pradesh, India.
Registered Office: Module G4, Ground Floor, Elnet Software City, TS-140, Block 2 & 9,
Rajiv Gandhi Salai, Taramani, Chennai 600 113, Tamil Nadu, India.
Fax: 080-30461003, Phone: 080-30461060
www.pearson.co.in, Email: companysecretary.india@pearson.com
Preface xi
Acknowledgements xiv
About the Author xv
2.8 Variables 39
2.9 Rules for Defining Variables 39
2.10 Data Types 40
2.11 C Data Types 41
2.12 Integer and Float Number Representations 43
2.12.1 Integer Representation 43
2.12.2 Floating-Point Representation 44
Summary 51
Exercises 52
Summary 636
Exercises 637
I am indeed very delighted to present the third edition of Programming in C with elaborated c oncepts
supported with more solved and unsolved problems. I have tried to make the book friendly using
simple and lucid language. In this edition, a chapter on Graphics with thought provoking questions
and programming examples are added.
This book is proposed for beginners, intermediate level students, and for all those who are
pursing education in computers. It would be extremely useful for the students who enroll for
diploma, degree in science and engineering, certificate courses in computer languages in training
institutes or those who appear for the C aptitude tests/interviews on C Language conducted by
various software companies and enhance their C knowledge. It can be used as a reference book for
those who want to learn or enrich their knowledge in C.
All the programs given in this book are compiled and run on Turbo C compiler. A few applications
are provided in this book which are fully tested and run on Turbo C compiler. The programmer can
develop advanced applications based on real-life problems using basics of C language. It contains
numerous examples which include solved and unsolved programming exercises that make the book
most interesting. Multiple choice questions are also provided at the end of each chapter for testing the
skills of a programmer.
An attempt has been made to cover the C syllabi of different branches of various universities.
Hence this book can be adopted as a text or a reference book in engineering/degree/diploma and other
courses.
In order to bridge the gap between theory and practical, each concept is explained at length in an
easy-to-understand manner supported with numerous worked-out examples and programs. The book
contains solved illustrative problems and exercises. The programmer can run the solved programs, can
see the output and enjoy the concepts of C.
BOOK ORGANIZATION
The first chapter describes the fundamental concepts of a computer, components of a computer, an
overview of compilers and interpreters, structure of a ‘C’ program, programming rules, how to execute
the program, and flowchart for execution of a program. This chapter also presents the techniques of
solving a problem using algorithm and flowchart.
Chapter 2 explains the fundamentals of ‘C’. These concepts are essential for writing programs
and contain character set supported by C language. Various delimiters used with ‘C’ statements,
keywords and identifiers are also provided. Different constants, variables and data types supported
by C are also given. This chapter covers the rules for defining variables and methods to initialize
them. Dynamic initialization is also presented in this chapter. Type conversion of a variable, type
modifiers and wrapping around, constant and volatile variables are also explained.
Chapter 3 covers various C operators and their priorities. This chapter presents arithmetic,
relational and logical operators. It also embodies increment, decrement (unary operators) and
assignment operators. Other operators such as comma, conditional operator and bitwise operators are
presented with programming examples.
Chapter 4 deals with formatted input and output functions such as scanf()and printf()
functions. The unformatted functions such as putchar(), getche() and gets() are described
in this chapter. Different data types and conversion symbols to be used in the C programs have also
been elaborated. The special symbols such as escape sequences together with their applications are
also discussed. Few of the commonly used library functions to be used in the programs such as
clrscr() and exit() are also described.
Chapter 5 is essential for knowing the decision-making statements in C language. This chapter
presents how to transfer the control from one part to the other part of the program. The programmer
can make the program powerful by using control statements such as if, if-else, nested if-else
statements and switch case. To change the flow of the program, the programmer can use keywords
such as break, continue and goto.
Chapter 6 is devoted to control loop structures in which how statements are executed several times
until a condition is satisfied. In this chapter, the reader follows program loop which is also known as
iterative structure or repetitive structure. Three types of loop control statements are illustrated with
for, while and do-while programming examples. Syntaxes of these control statements are briefed
together with programming examples. The other statements such as the break,continue and goto
statements are also narrated.
Chapter 7 deals with the array in which the reader can follow how to initialize array in different
ways. The theme of this chapter is to understand the array declaration, initialization, accessing array
elements and operations on array elements. How to specify the elements of one-, two- and three- or
multi-dimensional arrays are explained in detail together with ample examples. The functions such
as sscanf() and sprintf()are demonstrated through programming examples. The reader can
develop programs after learning this chapter on arrays. This chapter also gives an overview of the
string. It covers operations on array such as deletion, insertion and searching an element in the array
and how to traverse all the array elements.
Chapter 8 is focused on strings. This chapter teaches you how to learn declaration and initialization
of a string. It is also very important to identify the end of the string. This is followed by NULL
(‘\0’) character. The various formats for display of the strings are demonstrated through numerous
examples.
String handling has strong impact in real-life string problems such as conversion of lower to upper
case, reversing, concatenation, comparing, searching and replacing of string elements. It is also discussed
how to perform these operations with and without standard library functions. Memory functions such
as memcpy(), memove() and memchr()are also illustrated together with programming examples.
Chapter 9 deals with the most important feature of the C language, i.e. pointer, it is important but
difficult to understand easily. The reader is made familiar with pointers with numerous examples. The
reader is brought to light about declaration and initialization of pointers, and how to access variables
using pointers. How pointers are used to allocate memory dynamically at run time is also illustrated
using memory allocation functions such as malloc() and calloc() functions. How memory is
handled efficiently with pointers is also explained. This chapter consists of arithmetic operations on
pointers, pointers and arrays, pointers to pointers and pointers to strings. Memory models are also
explained.
Chapter 10 is one more important chapter on functions. How a large size program is divided in
smaller ones and how a modular program should be developed is learnt in this chapter. Programmer
learns the definition and declaration of function. What are the return statements, types of functions
and functions with passing arguments are described in detail. What do you mean by “call by value”
and “call by reference”? — Their answers are given with many programming examples. This chapter
also incorporates functions and loop statements, function and arrays and association of functions and
pointers.
The reader should know that the function always returns an integer value. Besides a function can
also return a non-integer data type but function prototype needs to be initialized at the beginning of the
program. The recursive nature of function is also explained with suitable example. Direct and indirect
recursive functions have been explained with programming examples.
Chapter 11 enlightens on the variables used in C in different situations. It also covers types of
variables such as local and global variables. The various storage classes of a variable are also covered
in this chapter. Explanations on auto, extern, static and register variables are also presented
in this chapter.
Chapter 12 narrates how to make use of preprocessor directives and how various macros are to
be used. This chapter enlightens preprocessor directives such as #define, #undef, #include,
#line, token pasting and stringizing operations and conditional compilation through C are illustrated.
It covers #define directive, undef macro, include directive, predefined macros in ANSI and
Turbo C. A reader learns how to display programmer’s own error messages using #error directive
and making various warnings on/off displayed by compiler using #pragma directive. You are exposed
to predefined macors in ctype.h in this chapter.
Chapter 13 is on structures and unions. A reader can get derived data type using structures and
unions. User can decide the heterogeneous data types to be included in the body of a structure. Use
of dot operator (.) and pointer (->) are explained for accessing members of structure. Declaration and
initialization of structure and union are also explained. The typedef facility can be used for creating
user-defined data types and illustrated with many examples. Enumerated data type and union are the
important subtitles of this chapter. Enumerated data type provides user-defined data types. Union is a
principal method by which the programmer can derive dissimilar data types. The last but not the least
the DOS and ROM-BIOS functions and their applications are also explained.
Chapter 14 is on files. This chapter explains the procedure for opening a file, storing information
and reading. How to read a file and how to append information are explained in this chapter. Many file
handling commands are also discussed. Text and binary files are explained. Command line arguments
to accept arguments from command prompt are described. Simulation of various DOS commands
with examples is also narrated. A reader is also made familiar with I/O redirections in which MSDOS
redirects to send the result to disk instead of seeing information on monitor.
Chapter 15 is on graphics. How to draw various figures/images using C library graphics functions
are to be studied from graphics chapter. This chapter enlightens the reader about the initialization of
graphics with library graphics functions and number of programming examples. Few programs have
been provided on mouse programming.
Chapter 16 enlightens the reader on dynamic memory allocations, memory models and linked
lists. Dynamic memory allocation deals with memory functions such as malloc(), calloc(),
coreleft() and realloc() and release the allocated memory using free() function. The
linked list is described in brief in this chapter. In the linked list, creation of linked list, traversing,
searching, inserting and deleting an element are described with figures and programming examples.
Utmost care has been taken to write third edition of the book in order to make it error free. The
suggestions and feedback for the improvement of the book are always welcome, the readers can
directly mail me at ankamthane@gmail.com.
Ashok N. Kamthane
I would like to thank all those who have encouraged me, especially Professor B.M. Naik, former
principal of Shri Guru Gobind Singhji Institute of Engineering and Technology, who has been
always a source of inspiration.
Special thanks are due to members of board of governors of SGGS institute who motivated
me for writing this book, Baba Kalyani, Chairman and Managing Director of Bharat Forge Ltd
Pune, Ram Bhogle, C.Y. Gavhane, Mr Kamlesh Pande, Sanjay Kumar, Dr Nirmal Singh Sehra, and
Director of our Institute Dr L.M. Waghmare.
My sincere thanks to Professor S.D. Mahajan, Director of Technical Education, Maharashtra
State, and ex-Board of Governors of this college, Dr M.B. Kinhalkar, Former Home Minister and
ex-Principal, Dr T.R. Sontakke for inspiring me to write this book.
I am grateful to all my colleagues, friends and students, who extended morale support,
Dr Y.V. Joshi, Dr R.R. Manthalkar, Dr S.S. Gajre, Dr S.V. Bonde, Dr P.G. Jadhav, Professor N.G.
Megde, Professor P.S. Nalawade, Dr A.R. Patil, Dr A.B. Gonde, Dr M.B. Kokre, Dr U.V. Kulkarni,
Dr P. Pramanik, Dr V.M. Nandedkar, Dr A.V. Nandedkar, Dr B.M. Patre, Dr S.T. Hamde, Dr R.C.
Thool, Dr V.R. Thool, Mrs U.R. Kamble, Dr D.D. Doye, Dr V.G. Asutkar, Professor R.K. Chavan,
Professor Ghanwat Vijay, Dr V.K. Joshi, Dr S.G. Kahalekar, Dr A. Chakraborty, Dr P. Kar, Dr P.G.
Solankar, Dr B.M. Dabde, Dr M.L. Waikar, Dr R.S. Holambe, Dr J.V.L. Venkatesh, Mrs S.S.
Kandhare, Professor S.S. Hatkar, Narayan Patil, Dr P.D. Dahe, Dr P.D. Ullagadi, Dr P.B. Londhe,
Dr A.S. Sontakke, Professor A.M. Bainwad, Professor Deepak Bacchewar, Professor R.P. Parvekar,
Professor N.M. Khandare, Dr V.B.Tungikar, Dr R.N. Joshi, Dr L.G. Patil, Professor A.I. Tamboli,
Mr Bhalerao M.V. and Professor S.B. Dethe.
I am also thankful to my friends, Professor S.L. Kotgire, Maruti Damkondawar, G.M. Narlawar,
Anil Joshi, D.V. Deshpande, Professor Balaji Bacchewar, M.M. Jahagirdar, L.M. Buddhewar,
K.M. Buddhewar, S.R. Kokane, Ganpat Shinde, M.G. Yeramwar, S.R. Tumma, S.P. Tokalwad,
P.R. Navghare, Somajawar H.S. and Annes for their morale support.
I am thankful to the wonderful editorial team of Pearson Education for specific invaluable inputs
and bringing this book out in a record time.
I also express my thanks to my son Lecturer Amit, students Jadhav Gopal and Wanjare Sainath
for their critical review and suggesting improvements.
Last but not the least, my thanks are due to my wife Surekha for her patience and support. My son
Amol, daughter Sangita and daughter-in-law Swaroopa were of great help and supported me all the
times.
Ashok N. Kamthane
1 Basics and
Introduction to C
Chapter Outline
1.1 Why to use Computers?
1.2 Basics of a Computer
1.3 Latest Computers
1.4 Introduction to C
1.5 About ANSI C Standard
1.6 Machine, Assembly and High-Level Language
1.7 Assembler, Compiler and Interpreter
1.8 Structure of a C Program
1.9 Programming Rules
1.10 Executing the C Program
1.11 Standard Directories
1.12 The First C Program
1.13 Advantages of C
1.14 Header Files
1.15 Algorithm
1.16 Classification of Algorithms
1.17 Flowcharts
1.18 Pseudocode
computer and quite often it called as microprocessor chip. Since it is a tiny chip hence called as mi-
croprocessor chip. This chip is produced from silicon vapor over which millions of transistors are
mounted with modern fabrication techniques.
The brain of the computer is CPU. This chip is responsible to interpret and execute the instruc-
tions. It comprises arithmetic and logical unit, registers and control unit. The arithmetic and logical
unit performs various arithmetic and logical operations on the data based upon the instructions. The
control unit generates the timing and control signals for carrying out operations within the processor.
Registers are used for holding the instructions and storing the results temporarily. Instructions are
stored in the memory and they are fetched one by one and executed by the processor.
Output Device: The output device is used to display the results on the screen or to send the data to
an output device. The processed data is ultimately sent to the output device by the computer. The out-
put device can be a monitor, a printer, an LED, seven-segment display, D to A converter, plotter, and
so on. Figure 1.4 shows different output devices of a computer.
Memory: Memory is used to store the program. There are two types of semi-conductor memories.
They are as follows:
(i) RAM (Random access memory)
(ii) ROM (Read only memory)
semi-conductor memory is used for storing the instructions and data in the form of ones and zeros.
The memory can be called user’s memory or read–write memory. Processor first reads the instructions
and data from the primary memory (semi-conductor memory). Then, it executes the instructions.
One more memory device used by a computer is called read only memory (ROM). This contains
a fixed software program for providing certain operations. This is non-volatile memory. Its contents
cannot be eliminated when power supply goes off. The basic input–output system (BIOS) is a soft-
ware used to control various peripheral devices such as a keyboard, a monitor, a printer, a mouse,
ports including serial and parallel ports. In fact, this is an operating system. It is possible to access the
users’ written programs, i.e. by loading a file, saving it and doing modifications to it in the later stage.
As soon as a personal computer is switched on, the software gets booted from ROM. Thus, various
functions are assigned to all supporting peripherals of a central processing unit (CPU) and easy inter-
actions are provided to the user by BIOS while booting the system.
For storing volumous data, secondery storage devices can be used. They are optical disk, magnetic
disc, tapes, etc.
1.4 Introduction to C BCPL B
C is one of the most popular general-purpose programming languages.
C language has been designed and developed by Dennis Ritchie at
Bell Laboratories, USA, in 1972. Several important concepts of C C
are drawn from ‘Basic combined programming language’ and ‘B’
language. Figure 1.6 shows the development of C language from the Figure 1.6 Evolution of C
two languages. Martin Richards developed BCPL in 1967. The impact
of BCPL on C is observed indirectly through the language B, which
was developed by Ken Thompson in 1970. C is also called an offspring of the BCPL. Table 1.1
illustrates the evolution of languages and their inventors of programming language.
C is also called a system-programming language because it is greatly helpful for writing operat-
ing systems, interpreters, editors, compilers, database programs and network drivers.
BCPL and B are data type-less languages. However, C language has a variety of data types. The
standard data types in C are integers, floating point, characters. Also, derived data types can be cre-
ated such as pointers, arrays, structures and unions. Expressions are built from operands and opera-
tors. Any expression or an assignment or a call to function can be a statement. The pointers provide
machine-independent address arithmetic.
C also provides control-flow statements such as decision-making statements (if–else)
and (switch-case) multi-choice statement. C supports for, while and do-while looping
statements.
C does not have any operator to perform operation on composite object. There does not exist any
function or operator that handles entire array or string. For example, to assign elements of one array
to another array simply with single assignment statement is not enough, but an element-to-element
assignment is to be done. However, structure objects can be copied as a unit.
C is not a strongly typed language. But typed statements are checked thoroughly by C compilers.
The compiler will issue errors and warning messages when syntax rules are violated. There is no au-
tomatic conversion of incompatible data types. A programmer has to perform explicit type conversion.
UNIX: The UNIX is an interactive operating system. It is useful in microcomputers, minicomputers
and main frame computers. This operating system is very portable and supports multi-user process-
ing, multi-tasking and networking. Several users can use UNIX at once for performing the same task.
This operating system was developed to connect various machines together. UNIX is primarily used
for workstations and minicomputers.
Mnemonic Machine
Assembler
language codes
languages are called low-level languages. The assembler programs translate the low-level language
to the machine code. The translation job is performed either manually or with a program called as-
sembler. In hand assembly, the programmer uses the set of instructions supplied by the manufacturer.
In this case, the hexadecimal code for the mnemonic instruction is searched from the code sheet. This
procedure is tedious and time-consuming. Alternate solution to this is the use of assemblers. The pro-
gram called assembler provides the codes of the mnemonics. This process is fast and facilitates the
user in developing the program speedily.
Compiler: Compilers are the translators, which
translate all the instructions of the program into Mnemonic Compilers and Machine
language interpreters codes
machine codes, which can be used again and
again (see Figure 1.10). The program, which is
to be translated, is called the source program Figure 1.10 Compiler/interpreter
and after translation the object code is gener-
ated. The source program is input to the compiler. The object code is output for the secondary storage
device. The entire program will be read by the compiler first and generates the object code. However,
in interpreter each line is executed and object code is provided. M-BASIC is an example of an inter-
preter. High-level languages such as C, C++ and Java compilers are employed. The compiler displays
the list of errors and warnings for the statements violating the syntax rules of the language. Compilers
also have the ability of linking subroutines of the program.
Interpreter: Interpreters also come in the group of translators. It helps the user to execute the source
program with a few differences as compared to compilers. The source program is just like English
statements in both interpreters and compilers. The interpreter generates object codes for the source
program. Interpreter reads the program line by line, whereas in compiler the entire program is read by
the compiler, which then generates the object codes. Interpreter directly executes the program from
its source code. Due to this, every time the source code should be inputted to the interpreter. In other
words, each line is converted into the object codes. It takes very less time for execution because no
intermediate object code is generated.
Linking: C language provides a very large library, which contains numerous functions. In some
applications of C the library may be a very large file. Linker is a program that combines source
code and codes from the library. Linking is the process of bringing together source program and
library code.
The library functions are relocatable. The addresses of various machine codes are defined abso-
lutely and only the offset information is kept. When the source program links with the standard library
functions, offset of the memory addresses is used to create the actual address.
Alternately, one can also write the first line of C program from where program execution be-
gins is as follows.
void main(void)
Here, this function takes no arguments and returns nothing. Alternately, one can also write the
same function as follows.
void main(): This functions returns nothing and takes no arguments.
In all chapters, in maximum programming examples the main function is written as void
main(). This procedure is followed in this book only to avoid writing return statement at
the end of each program. This step helps to minimize source code lines. At few places in this
book, main function is initialized with int main(void). In such a case, return state-
ment is used at the end of program (before closing brace). The programmer can either write
the function main with int main(void) or void main(). Only in the formal case,
return statement should be used before the end of function for terminating the execution of
the main function.
The program contains statements that are enclosed within the braces. The opening brace ({)
and closing brace (}) are used in C. Between these two braces, the program should declare
declaration and executable part. The opening curly brace specifies the start of the definition of
the main function. The closing curly brace specifies the end of the code for the main function.
(iv) Declaration Part: The declaration part declares the entire local variables that are used in
executable part. Local variable scope is limited to that function where the local variables are
declared. The initializations of variables can also be done in this section. The initialization
means providing initial value to the variables.
(v) Executable Part: This part contains the statements following the declaration of the variables.
This part contains a set of statements or a single statement.
(vi) Function Call: From the main() a user defined function can be invoked by the user as per
need/application.
(vii) User-defined Function: The functions defined by the user are called user-defined functions.
These functions are defined outside the main() function.
(viii) Body of the Function: The statements enclosed within the body of the function (between
opening and closing brace) are called body of the function.
(ix) Comments: Comments are not necessary in a program. However, to understand the flow of
programs a programmer can insert comments in the program. Comments are to be inserted by
the programmer. It is useful for documentation. The clarity of the program can be followed if
it is properly documented.
Comments are statements that give us information about the program which are to be placed
between the delimiters /* and */. The programmers in the programs for enhancing the
lucidity frequently use comments. The compiler does not execute comments. Thus, we can say
that comments are not a part of executable programs.
A user can frequently use any number of comments that can be placed anywhere in a
program. Please note that comment statements can be nested. The user should select the
OPTION MENU of the editor and select the COMPILER-SOURCE - NESTED COMMENTS
ON/OFF. The comments can be inserted with single statement or in nested statements.
Example:
/* This is single comment */
/* This is an example of /* nested comments */*/
/* This is an example of
of comments in
multiple lines */ /* It can be nested */
1.9 Programming Rules
A programmer while writing a program should follow the following rules:
(i) Every program should have main() function.
(ii) C statements should be terminated by a semi-colon. At some places, a comma operator is per-
mitted. If only a semi-colon is placed it is treated as a statement. For example:
while(condition)
;
The above statement generates infinite loop. Without semi-colon the loop will not execute.
(iii) An unessential semi-colon if placed by the programmer is treated as an empty statement.
(iv) All statements should be written in lowercase letters. Generally, uppercase letters are used
only for symbolic constants.
(v) Blank spaces may be inserted between the words. This leads to improvement in the readability
of the statements. However, this is not applicable while declaring a variable, keyword, constant
and function.
(vi) It is not necessary to fix the position of statement in the program; i.e. a programmer can write
the statement anywhere between the two braces following the declaration part. The user can
also write one or more statements in one line separating them with a semi-colon (;). Hence, it
is often called a free-form language. The following statements are valid:
a=b+c;
d=b*c;
or
a=b+c; d=b*c;
(vii) The opening and closing braces should be balanced, i.e. if opening braces are four; closing
braces should also be four.
first automatically before the compilation of the program. A programmer can include other files
in the current file. Inclusion of other files is done initially in the preprocessor section.
(iii) Compilation and Linking of a Program: The source program contains statements that are to be
translated into object codes. These object codes are suitable for execution by the computer. If a
program contains errors the programmer should correct them. If there is no error in the program,
compilation proceeds and translated program is stored in another file with the same file name with
extension ‘.obj’. This object file is stored on the secondary storage device such as a disc.
Linking is also an essential process. It puts together all other program files and functions 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. After linking, the program is stored on the disc.
(iv) Executing the Program: After the compilation the executable object code will be loaded in the
computer’s main memory and the program is executed. The loader performs this function. All the
above steps/phases of C program can be performed using menu options of the editor.
As shown in Figure 1.12, pre-processor directories/program is executed before compilation
of the main program. The compiler checks the program and if any syntax error is found, the same
Pre-processor
Is syntax
error? Yes
No
No
Run time error Compile time error
Output
is displayed. The user is again forced to go to edit window. After removing an error, the compiler
compiles the program. Here, at this stage object code is generated. During the program execution, if
user makes mistakes in inputting data, the result would not be appropriate. Therefore, the user again
has to enter the data. The output is generated when a program is error free.
Editing, compiling and executing a program file with an editor (Figure 1.13):
The programmer can use the Turbo C editor/compiler. The Turbo C editor is a software, in which the
programmer can write the program in C source code. The window to Turbo C editor appears when we
invoke shortcut to TC icon, which can be placed on desktop. This window is used for editing, compil-
ing and running the program.
Its menu bar comprises eight menus: File, Edit, Run, Compile, Project, Options, Debug and
Break/watch.
File: This menu is used for creating a new program file, loading an existing C file, writing the file
with appropriate path, invoking DOS (OS Shell), changing directory and quitting the program.
Edit: The Edit menu provides editing options.
Run: The Run menu provides options such as Run, Program reset, Go to cursor, Trace into, Step
over and User screen.
On pressing Alt+F keys, one can go to the File menu and select either New for creating a new
file or in case file is already existing then use Load option and load the file by giving the appropriate
path. Extension of the file with .c is automatically provided by the editor. The programmer can put
extension .c or by default .c is provided by the editor. The programmer can now write a program with
C syntax.
It is better to create and save programs in a separate folder/subdirectory in the home directory of
the disk. The folder/subdirectory is the working directory. This is due to the association of the program
file with several files created during compiling and running. Files created are your own files (source
code file and data files) and besides, some other files created are after compilation and running the
program.
For example if C:\Turboc2 is home directory, a subdirectory can be created with the Command
prompt. Assume that the created subdirectory is Vishal, then working directory path would be
C:\Turboc2\Vishal. So, create and save all programs in the working directory Vishal (Figure 1.14).
After editing the program file, the same should be saved either with F2 key or Alt+F & Save from File
menu and compiled from compile menu. Now programmer can use the keys Alt+C in the editor as shown
below (Figure 1.15).
1.11 Standard Directories
The turbo-C has three standard directories; they are include, sys and lib. The Sys is the
sub-directory of include. The include directory contains all the header files and lib con-
tains all the library files. Before executing the program the path setting should be done. In turbo-
c edit, select Option menu Directories option. Here, set the path of include, library and
turbo-c-directories.
void main()
{
printf(“Hello! C Programmers”);
}
OUTPUT:
Hello! C Programmers
Explanation:
This program displays the message ‘Hello! C Programmers’ using the printf()
statement. Follow the following steps to execute the program through Turbo-c editor.
After typing a program by pressing F2, a program can be saved. If you are saving for the first
time, a name will be asked. Type the file and the extension (.c) will automatically be added.
By pressing ALT+C you can reach the compile option. Also by pressing F9, you can compile
the program. To execute the program you can press CTRL + F9. To see the output of the
program, press ALT+F5. User can make exe file by pressing F9 key twice.
1.2 Write a program to know about the use of comments (how to use comments?).
void main()
{
clrscr(); /* clears the screen */
printf(“\This program explains comments”);
/* How to use comment? */
}
OUTPUT:
This program explains comments
Explanation:
In the above program, we can observe how comments are inserted in a program. The
comments are not an executable part. It is only useful for the programmer to understand
the flow of a program. This program prints the message as shown in the output.
The function clrscr() clears the screen, defined in header file <conio.h>.
Although the file is not included, some compilers allow execution and some will flag
an error message.
main()
{
return 0;
}
Explanation:
The above program produces no output. The main() should return a value of either 0 or 1.
Some operating systems check the return value of main(). If main() returns 0, i.e. pro-
gram executed successfully; else for other value OS assumes the opposite. If user fails to put
the return statement, the compiler would not complain.
1.13 Advantages of C
(i) It contains a powerful data definition. The data type supported are characters, alphanumeric,
integers, long integer, floats and double. It also supports string manipulation in the form of
character array.
(ii) C supports a powerful set of operators.
(iii) It also supports powerful graphics programming and directly operates with hardware. Execu-
tion of program is faster.
(iv) An assembly code is also inserted into C programs.
(v) C programs are highly portable on any type of OS platforms.
(vi) System programs such as compilers, operating systems can be developed in C. For example,
the popular operating system UNIX is developed in C.
(vii) The C language has 32 keywords and about 145 library functions and near about 30 header
files.
(viii) C works closely with machines and matches assembly language in many ways.
1.14 Header Files
stdio.h: Standard input and output files. All formatted and unformatted functions include file
operation functions defined in this file. The most useful formatted printf() and scanf() are
defined in this file. This file must be included at the top of the program. Most useful functions from
this header files are printf(), scanf(), getchar(), gets(), putc() and putchar().
conio.h: Console input and output. This file contains input and output functions along with a few
graphic-supporting functions. The getch(), getche() and clrscr() functions are defined in
this file.
math.h: This file contains all mathematical and other useful functions. The commonly useful func-
tions from this files are floor(), abs(), ceil(), pow(), sin(), cos() and tan(). The list
of commonly used header files are given in Table 1.2
There are different ways of representing the logical steps for finding a solution of a given problem.
They are as follows:
(i) Algorithm
(ii) Flowchart
(iii) Pseudo-code
In the algorithm, a description of the steps for solving a given problem is provided. Here, stress is given on the
text. Flowchart represents the solution of a given problem graphically. Pictorial representation of the logical
steps is a flowchart. Another way to express the solution of a given problem is by means of a pseudo-code.
1.15 Algorithm
Algorithm is a very popular technique used to obtain a solution for a given problem. The algorithm
is defined as ‘the finite set of steps, which provide a chain of actions for solving a definite nature of
problem’. Each step in the algorithm should be well defined. This step will enable the reader to trans-
late each step into a program. Gradual procedure for solving a problem is illustrated in this section.
An algorithm is a well-organized, pre-arranged and defined textual computational module that
receives some value or set of values as input and provides a single value or a set of values as output.
These well-defined computational steps are arranged in a sequence, which processes the given input
into an output. Writing precise description of the algorithm using an easy language is most essential
for understanding the algorithm. An algorithm is said to be accurate and truthful only when it provides
the exact required output. Lengthy procedure is sub-divided into small parts and thus steps are made
easy to solve a given problem. Every step is known as an instruction.
In our daily life, we come across numerous algorithms for solving problems. We perform several
routine tasks, for example riding a bike, lifting a phone, making a telephone call, switching on a televi-
sion set and so on.
For example, to establish a telephonic communication between two subscribers, following steps
are to be followed:
(i) Dial a phone number
(ii) Phone rings at the called party
(iii) Caller waits for the response
(iv) Called party picks up the phone
Algorithm: Flowchart:
STEP 1: Start.
STEP 2: Declare two variables a & b. START
STEP 3: Addition of a & b and place result in a.
STEP 4: Subtraction of a & b and place result in b.
STEP 5: Subtraction of a & b and place result in a. Declare variables &
assign values to a & b.
STEP 6: Print values of a & b.
STEP 7: End.
Program: a = a + b;
void main() b = a − b;
{ a = a − b;
int a=4,b=6;
clrscr();
a=a+b;
b=a-b; Print values
a=a-b; of a & b
printf(“\nthe value of a=%d & b=%d”,a,b);
getch();
} END
OUTPUT:
The value of a=6 & b=4
Explanation:
In the above cited program, first two variables a & b are declared and initialized.
Values of a & b are added in the statement a = a + b. In the next statement, b is subtracted from
a and result is stored in b. Finally, the value of a is obtained by subtracting b from a.
The printf( ) statement prints the values of a & b.
Coding Programs: Coding a program is the second step. Once you have understood the program,
now you can implement through the code. If a program is short, start coding from the beginning to
top in a sequence. Identify the different variables and selection or control structures required. Also
write comments so that you can follow them in future. While coding, appropriate messages for user’s
direction should be prompted.
Testing Programs: After completing the coding of a program, the next step is to test the program.
Confirm that the required source files and data files are at the specified location in the system.
Algorithms
On the basis of repetitive steps, an algorithm can further be classified into two types.
(i) Direct Algorithm: In this type of algorithm, the number of iterations is known in advance.
For example, for displaying numerical numbers from 1 to 10, the loop variable should be ini-
tialized from 1 to 10. The statement would be as follows:
for (j=1;j<=10;j++)
In the above statement, it is predicted that the loop will iterate 10 times.
(ii) Indirect Algorithm: In this type of algorithm, repetitively steps are executed. Exactly how
many repetitions are to be made is unknown.
For example, the repetitive steps are as follows:
(i) T o find the first five Armstrong numbers from 1 to n, where n is the fifth Armstrong
number.
(ii) To find the first three palindrome numbers.
Based on the control transfer, the algorithms are categorized in the following three types.
(i) Deterministic: Deterministic algorithm is based on either to follow a ‘yes’ path or ‘no’ path
based on the condition. In this type of algorithm when control comes across a decision logic,
two paths ‘yes and ‘no’ are shown. Program control follows one of the routes depending upon
the condition.
Example:
Testing whether a number is even or odd. Testing whether a number is positive or negative.
Non-deterministic: In this type of algorithm to reach to the solution, we have one of the mul-
(ii)
tiple paths.
Example:
To find a day of a week.
Random algorithm: After executing a few steps, the control of the program transfers to
(iii)
another step randomly, which is known as a random algorithm.
Example:
A random search
Another kind of an algorithm is the infinite algorithm.
Infinite algorithms: This algorithm is based on better estimates of the results. The number
of steps required would not be known in advance. The process will be continued until the best
results emerged. For final convergence more iterations would be required.
Example:
To find shortest paths from a given source to all destinations in the network.
1.17 FLOWCHARTS
A flowchart is a visual representation of the sequence of steps for solving a problem. It enlightens
what comes first, second, third, and so on. A completed flowchart enables you to organize your prob-
lem into a plan of actions. Even for designing a product a designer many times has to draw a flowchart.
It is a working map of the final product. This is an easy way to solve the complex designing problems.
The reader follows the process quickly from the flowchart instead of going through the text.
A flowchart is an alternative technique for solving a problem. Instead of descriptive steps, we use
pictorial representation for every step. It shows a sequence of operations. A flowchart is a set of symbols,
which indicates various operations in the program. For every process, there is a corresponding symbol
in the flowchart. Once an algorithm is written, its pictorial representation can be done using flowchart
symbols. In other words, a pictorial representation of a textual algorithm is done using a flowchart.
We give below some commonly used symbols in flowcharts.
Start and end: The start and end symbols indicate both the beginning and the end of the flowchart.
This symbol looks like a flat oval or is egg shaped. Figure 1.18 shows the symbol of Start/stop. Only
one flow line is combined with this kind of symbol. We write START, STOP or END in the symbols
of this kind. Usually this symbol is used twice in a flowchart, that is, at the beginning and at the end.
Start
Stop
Decision or test symbol: The decision symbol is diamond shaped. This symbol is used to take one
of the decisions. Depending on the condition the decision block selects one of the alternatives. While
solving a problem, one can take a single, two or multiple alternatives depending upon the situation. All
these alternatives are illustrated in this section. A decision symbol with a single alternative is shown in
Figure 1.18. In case the condition is satisfied /TRUE a set of statement(s) will be executed otherwise
for false the control transfers to exit.
Single alternative decision: Here more than one flow line can be used depending upon the condi-
tion. It is usually in the form of a ‘yes’ or ‘no’ question, with branching flow line depending upon the
answer. With a single alternative, the flow diagram will be as per Figure 1.19.
Entry
Condition?
True False
Execution of statement(s)
Exit
Two alternative decisions: In Figure 1.20 two alternative paths have been shown. On satisfying the
condition statement(s) pertaining to 1 action will be executed, otherwise the other statement(s) for
action 2 will be executed.
Entry
Condition?
True False
Exit
Multiple alternative decisions: In Figure 1.21 multiple decision blocks are shown. Every decision
block has two branches. In case the condition is satisfied, execution of statements of appropriate
blocks take place, otherwise next condition will be verified. If condition 1 is satisfied then block 1
statements are executed. In the same way, other decision blocks are executed.
Entry
True
Condition 1 Execution of block 1
False
True
Condition 2 Execution of block 2
False
True
Condition 3 Execution of block 3
False
Exit
Connector symbol: A connector symbol has to be shown in the form of a circle. It is used to establish
the connection, whenever it is impossible to directly join two parts in a flowchart. Quite often, two
parts of the flowcharts may be on two separate pages. In such a case, connector can be used for joining
the two parts. Only one flow line is shown with the symbol. Only connector names are written inside
the symbol, that is, alphabets or numbers. Figure 1.22 shows the connector symbol.
Process symbol: The symbol of process block should be shown by a rectangle. It is usually used for
data handling, and values are assigned to the variables in this symbol. Figure 1.23 shows the process
symbol. The operations mentioned within the rectangular block will be executed when this kind of
block is entered in the flowchart. Sometimes an arrow can be used to assign the value of a variable to
another. The value indicated at its head is replaced by the tail values. There are two flow lines con-
nected with the process symbol. One line is incoming and the other line goes out.
Z=X+Y
P=X*Y
Loop symbol: This symbol looks like a hexagon. This symbol is used for implementation of for
loops only. Four flow lines are associated with this symbol. Two lines are used to indicate the
sequence of the program and remaining two are used to show the looping area, that is, from the
beginning to the end.
For the sake of understanding, Figure 1.24. illustrates the working of for loop. The variable J is
initialized to 0 and it is to be incremented by a step of 2 until it reaches the final value 10. For every
increased value of J, body of the loop is executed. This process will be continued until the value of J
reaches 10. Here the next block is shown for the repetitive operation.
Entry
For J = 0 to 10 by
step 2
Body of the
for loop
To continue the
for loop
Exit
Input/output symbol: Input/output symbol looks like a parallelogram, as shown in Figure 1.25. The
input/output symbol is used to input and output the data. When the data is provided to the program for
processing, then this symbol is used. There are two flow lines connected with the input/output symbol.
One line comes to this symbol and the other line goes from this symbol.
As per Figure 1.25 compiler reads the values of X, Y and in the second figure the result is dis-
played on the monitor or the printer.
Read X, Y Print X, Y
Delay symbol: Symbol of delay is just like ‘AND’ gate. It is used for adding delay to the process. It is
associated with two lines. One is incoming and the other is outgoing, as shown in Figure 1.26.
Manual input symbol: This is used for assigning the variable values through the keyboard, whereas
in data symbol the values are assigned directly without manual intervention. Figure 1.27 represents
the symbol of manual input.
In addition, the following symbols (Figure 1.28) can be used in the flowchart and they are parts
of flowcharts.
1.18 PSEUDOCODE
In pseudocodes english-like words are used to represent the various logical steps. It is a prefix repre-
sentation. Here solution of each step is described logically. The pseudocode is just the raw idea about
the problem. By using this tip, one can try to solve the problem. The meaning of pseudocode is ‘false
code.’ The syntax rule of any programming language cannot be applied to pseudocode.
Example (a): Assume a and b are two numbers and find the larger out of them. In such a case, com-
parison is made between them.
Algorithm Pseudocode
Input a and b. get numbers a & b
Is a>b. Compare a & b
If yes a is larger than b. if a is large max=a
If no b is larger than a. if b is large max=b
Print the larger number. Larger number is max
Few skilled programmers prefer to write pseudocode for drawing the flowchart. This is because using
pseudocode is analogous to writing the final code in the programming language. Few programmers
prefer to write the steps in algorithm. Few programmers favour flowchart to represent the logical flow
because with visualization things are clear for writing program statements. For beginners a flowchart
is a straightforward tool for writing a program.
Example (b): The example (b) illustrates how the pseudo code is used to draw the flowchart for squar-
ing a number.
(i) Accept number
(ii) Calculate square of the number
(iii) Display number
All the steps of the program are written down in steps. Some programs follow pseudocode to draw
flowcharts. Using pseudocode, final program can be written. Majority of programs have common
tasks such as input, processing and output. These are fundamental tasks of any program.
Using pseudocode a flowchart can be drawn as per the following steps.
For the statement, that is, ‘Accept number’ the flowchart symbol is as per Figure 1.29.
Accept
number
The statements including arithmetic operations are examples of processing statements. The repre-
sentation of second statement ‘Calculate square of the number’ can be represented as in Figure 1.30.
Calculate square
of the number
The output statement, that is, ‘Display number’ can be represented as per Figure 1.31.
Display
number
In addition,the flowchart has two more symbols to indicate the beginning and the end of the program
as per Figure 1.32 The standard terminator symbol is racetrack.
Begin
Begin
Accept
number 1. Accept number
Calculate square
of the number 2. Calculate square of
the number
End End
sUmmary
This chapter presents the evolution and basics of C. C is a structural language. It has many similari-
ties like other structural languages such as Pascal and Fortran. C is also called a system-programming
language. The ANSI C standard was adopted in December 1989 and the first copy of C language was
introduced in the market in 1990.
The reader is exposed to an assembler that translates the symbolic code of programs of an
assembly language into machine language instructions. Similarly, compilers are the translators, which
translate all the instructions of the program into machine codes and can be used again and again. An
interpreter comes in the group of translators. It helps the user to execute the source program with few
differences as compared to compilers.
In this chapter, an overview of algorithms was given. An algorithm is defined as ‘the finite set of
the steps, which provide a chain of actions for solving a definite nature of problem’. Algorithms are of
two types, direct algorithm and indirect algorithm.
exerCises
I True or false:
1. C Language is developed by Ken Thompson. 8. Every C Program should have the main()
function.
2. C Language was developed in the year 1972.
9. In C, all the statements should be written in small
3. C Language is closely associated with Linux.
letters only.
4. C Programs are not portable.
10. After compilation, the object file of a source pro-
5. The ANSI C standard was developed in 1989. gram is created.
6. C Programs are translated into object code by a 11. It is not possible to crate .exe file in C.
compiler.
12. Compiler executes a program even if the program
7. An interpreter reads one line at a time. contains warning messages.
13. In Turbo-C editor Alt+C is used to execute the 18. Assembler translates low-level language to ma-
program. chine code.
14. A comment can be split in more than one line. 19. The compiler reads firstly entire program and
generates the object code.
15. The source code for the UNIX operating system
is in C. 20. C does not have automatic conversion of compat-
ible variable.
16. The assembly language program is in alphanu-
meric symbols. 21. Every processor has its own assembly language.
17. Linking software is used to bring together the 22. Assembly language program is portable.
source program and library code.
II Select the appropriate option from the multiple choices given below:
1. The C language has been developed by 7. The C program should be written only in
(a) Patrick Naughton (a) lower case
(b) Dennis Ritche (b) upper case
(c) Ken Thompson (c) title case
(d) Martin Richards (d) sentence case
2. The C programming is a 8. The role of a compiler is to translate source
program statements to
(a) high-level language
(b) low-level language (a) object codes
(c) middle-level language (b) octal codes
(d) assembly language (c) decimal codes
(d) None of the above
3. The C programs are converted into machine lan-
guage using 9. The extension for C program files by default is
(a) an assembler (a) ‘.c’
(b) a compiler (b) ‘.d’
(c) an interpreter (c) ‘.obj’
(d) an operating system (d) ‘.exe’
4. The C language was developed in the year 10. The C can be used with
5. The C language has been developed at 11. The C language is closely associated with
6. The C language is an offspring of the 12. The C programs are highly portable means
CHAPITRE PREMIER
GRANDEUR EXTÉRIEURE DE LA FRANCE SOUS LE