Programming in C
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: [email protected]
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 [email protected].
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
ansWers
I True or false:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. F 2. T 3. F 4. F 5. T
6. T 7. T 8. T 9. T 10. T
11. F 12. T 13. F 14. T 15. T
16. T 17. T 18. T 19. T 20. T
21. T 22. F
II Select the appropriate option from the multiple choices given below:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. b 2. c 3. b 4. a 5. a
6. a 7. a 8. a 9. a 10. d
11. c 12. a 13. c 14. c 15. a
16. a 17. a 18. a 19. a 20. a
21. b 22. a 23. a 24. d 25. d
26. d 27. d 28. d 29. d 30. d
2 The C
Declarations
Chapter Outline
2.1 Introduction
2.2 The C Character Set
2.3 Delimiters
2.4 Types of Tokens
2.5 The C Keywords
2.6 Identifiers
2.7 Constants
2.8 Variables
2.9 Rules for Defining Variables
2.10 Data Types
2.11 C Data Types
2.12 Integer and Float Number Representations
2.13 Declaring Variables
2.14 Initializing Variables
2.15 Dynamic Initialization
2.16 Type Modifiers
2.17 Type Conversion
2.18 Wrapping Around
2.19 Constant and Volatile Variables
2.1 Introduction
The programming languages are designed to support certain kind of data, such as numbers, characters,
strings, etc., to get useful output known as result/information. Data consists of digits, alphabets and symbols.
A program should support these data types for getting the required output known as information.
A program is a set of statements, which performs a specific task, executed by users in a sequential
form. These statements/instructions are formed using certain words and symbols according to the
rules known as syntax rules or grammar of the language. Every program must accurately follow the
syntax rules supported by the language.
In this chapter, C character set, the type of variables, types of tokens, delimiters, data types,
variable initialization and dynamic initialization are described.
The special characters listed in Table 2.2 are represented in the computer by numeric values. The C
characters are assigned unique codes. There are many character codes used in the computer system.
The widely and standard codes used in computer are ASCII and EBCDIC (Extended Binary Coded
Decimal Interchange Code).
ASCII Code: ASCII stands for American Standard Code for Information Interchange, is the
code of two types. One uses 7 bits and other uses 8 bits. The 7-bit code represents 128 different
characters and the 8-bit code represents 256 characters. For example, the character A is represented
in 7-bit code as 10000012(decimal 65). Refer to Appendix A for the list of characters and their
equivalent number.
2.3 Delimiters
The language pattern of C uses special kind of symbols, which are called delimiters. They are depicted
in Table 2.3.
2.4 Types of Tokens
A compiler designer prescribes rules for making a program using statements. The smallest unit in a
program/statement is called a token. The compiler identifies them as tokens. Tokens are classified in
the following types. Figure 2.2 shows the types of tokens supported by C.
The tokens are as follows:
(i) Keywords: Key words are reserved by
the compiler. There are 32 keywords Keywords
(ANSI Standard).
Variables
(ii) Variables: These are user defined. Any
number of variables can be defined. Tokens Operators
2.5 The C Keywords
The C keywords are reserved words by the compiler. All the C keywords have been assigned fixed
meanings and they cannot be used as variable names. However, few C compilers allow constructing
variable names, which exactly coincide with the keywords. It is suggested that the keywords should
not be mixed up with variable names. For utilizing the keywords in a program, no header file is
required to be included. The descriptions of the keywords are explained in the different programs/
chapters. The 32 C keywords provided in ANSI C are listed in Table 2.4.
2.6 Identifiers
A symbolic name is used to refer to a variable, constant, function, structure, union etc. This process
is done with identifiers. In other words, identifiers are the names of variables, functions, arrays, etc.
They refer to a variety of entities such as structures, unions, enumerations, constants, typedef names,
functions and objects (see Figure 2.3). An identifier always starts with an alphabet, and it is a plain
sequence of alphabets and/or digits. C identifier does not allow blank spaces, punctuations and signs.
Identifiers are user-defined names. They are generally defined in lowercase letters. However, the
uppercase letters are also permitted. The underscore (_) symbol can be used as an identifier. In general, an
underscore is used by a programmer as a link between two words for the long identifiers.
The programmer can refer to programming example 2.3 in which the identifiers are not defined
in lowercase but with a combination of lowercase and uppercase letters.
Valid identifiers are as follows:
length, area, volume, sUM, Average Variable
Here, ‘N’ and ‘a’ are user-defined identifiers. Figure 2.3 Identifiers
2.7 Constants
The constants in C are applicable to the values, which do not change during the execution of a pro-
gram. There are several types of constants in C. They are classified into following groups as given in
Figure 2.4 (e.g. Table 2.5).
C Constants
(b) Real Constants: Real constants are often known as floating point constants. Real constants
can be represented in exponential or fractional form. Integer constants are unfit to represent
many quantities. Many parameters or quantities are defined not only in integers but also in real
numbers. For example, length, height, price, distance, etc. are also measured in real numbers.
The following concepts are essential to follow the real numbers:
(a) The decimal point is permitted.
(b) Neither blank spaces nor commas are permitted.
(c) Real numbers could be either positive or negative.
(d) The number without a sign is assumed as positive.
The following points must be noted while constructing a real number in exponential form:
(a) The real number should contain a mantissa and an exponent.
(b) The letter ‘e’ separates the mantissa and the exponent and it can be written in lower or
upper case.
(c) The mantissa should be either a real number represented in decimal or integer form.
(d) The mantissa may be either positive or negative.
(e) The exponent should be an integer that may be positive or negative.
In double type also the real numbers can be expressed with mantissa and exponent parts.
void main()
{
int x;
float y;
char z;
double p;
clrscr();
x=20;
y=2e1;
z=‘a’;
p=3.2e20;
printf(“\n%d %10.2f %c %.2lf”,x,y,z,p);
getche();
}
OUTPUT:
20 20.00 a 320000000000000000000.00
2.8 Variables
Variables are the basic objects manipulated in a program. Declaration gives an introduction of variable
to compiler and its properties like scope, range of values and memory required for storage. A variable
is used to store values. It has memory location and can store single value at a time.
When a program is executed, many operations are carried out on the data. The data types are
integers, real or character constants. The data is stored in the memory, and at the time of execution it
is fetched for carrying out different operations on it.
A variable is a data name used for storing a data value. Its value may be changed during the pro-
gram execution. The variable value keeps on changing during the execution of the program. In other
words, a variable can be assigned different values at different times during the program execution.
A variable name may be declared based on the meaning of the operation. Variable names are made up
of letters and digits. Some meaningful variable names are as follows.
Example:
height, average, sum, avg12
2.2 Write a program to declare and initialize variables and display them.
void main()
{
int age=20;
float height=5.4;
char sex=‘M’;
clrscr();
printf(“Age :%d \nHeight : %g \nSex : %c”,age,height,sex);
}
OUTPUT:
Age: 20
Height: 5.4
Sex: M
Explanation:
In the above program, int, height and char variables are declared and values are as-
signed. Using printf() statement values are displayed.
2.3 Write a program to declare variables with different names and data types.
void main()
{
int Num=12;
int WEIGHT = 25;
float HeIgHt=4.5;
char name[10]=“AMIT”;
clrscr();
printf(“Num :%d \nWEIGHT : %d \nHeight : %g \nName
=%s”,Num,WEIGHT,HeIgHt,name);
}
OUTPUT:
Num: 12
WEIGHT: 25
Height: 4.5
Name = AMIT
Explanation:
In this program, you might have noticed that variables of different data types with different
naming styles are defined. For example Num, WEIGHT, HeIgHt and name are variables.
Values are assigned to variables and displayed in the same way as usual.
2.10 Data Types
All C compilers support a variety of data types. This enables the programmer to select the appro-
priate data type as per the need of the application. Generally, data is represented using numbers or
characters. The numbers may be integers or real. The basic data types are char, int, float and
double.
The C supports a number of qualifiers that can be applied to these basic data type. The short and
long qualifiers provide different length to int. The short is always 16 bits and long is 32 bits, i.e. int
is either 16 or 32 bits. The compiler is free to choose a suitable size depending upon the hardware.
However, the restriction is that short or int is at least of 2 bytes and long is at least of 4 bytes.
The short should not be longer than int and int should not be longer than long.
The unsigned and signed qualifiers can be applied to char, int and long. The unsigned data
types are always zero or positive. They follow the law of arithmetic modulo 2n, where n is the number of
bits in the type. For example, char are 8 bits with combination of negative and positive values (−128
to 127) (two’s complement). The unsigned char supports values 0 to 255. The characters are signed or
unsigned, the printable char are always positive (see Figure 2.5 for a detailed classification).
C Data Types
Derived Data Type Basic Data Type User Defined Data Type
Structure
Pointers
union
Functions
Enumeration
Arrays
typedef
Integer void
Floating point
char
int float
double
long double
(Continued)
(2) char, signed and unsigned: Brief description on these data types is given in Table 2.8
(3) Floats and Doubles: Table 2.9 shows the description of floats and double floats.
(4) Entire data types in C: The entire data types supported by the C as illustrated above are given
in Table 2.10 for the convenience of the reader for understanding.
The size may vary according to the number of variables used with enum data type.
The signed negative integers can be represented in any one of the following forms:
(a) signed—magnitude form
(b) signed—1’s complement form
(c) signed—2’s complement form
In the signed magnitude form, the sign of the number is represented as 1 and the magnitude by equiva-
lent binary form.
Example:
−7 is represented as 1 0000111
In the signed 1’s complement form, the sign of the integer is indicated by 1 and the magnitude is
shown in 1’s complement form as follows,
−7 is represented as 1 1111000
In the above signed − 2’s complement form, the sign is indicated by 1 and magnitude by 2’s comple-
ment form as follows,
−7 is represented by 1 1111001
Example in C:
1.2 E + 12, 2.5E − 2
2.13 Declaring Variables
The declaration of variables should be done in declaration part of the program. The variable must be de-
clared before they are used in the program. Declaration ensures the following two things: (i) compiler
obtains the variable name and (ii) it tells to the compiler data type of the variable being declared and
helps in allocating the memory. The variable can also be declared before main() such variables are
called external variables. The syntax of declaring a variable is as follows.
Syntax:
Data_type variable_name;
Example:
int age;
char m;
float s;
double k;
int a,b,c;
The int, char, float and double are keywords to represent data types. Commas separate the
variables, in case variables are more than one.
Table 2.11 shows various data types and their keywords.
Example:
x=5; where x is an integer variable.
Example:
int y=4;
Example:
int x,y,z; / Declaration of variables /
The third example as cited above for dec- Data-type Variable-Name Operator Value
laration of variables is also a valid state-
ment. Illustration of the initialization of a
variable is shown in Figures 2.6 and 2.7. int y = 2
In Figure 2.7, the variable z is assigned
a value 1, and z then assigns its value to Figure 2.6 Value assignment
y and again y to x. Thus, initialization in
chain system is done. However, note that x y z 1
following declarations are invalid:
int x=y=z=3; / invalid statement /
Figure 2.7 Multiple assignment
2.15 Dynamic Initialization
The initialization of variable at run time is called dynamic initialization. Dynamic refers to the process
during execution. In C initialization can be done at any place in the program; however the declaration
should be done at the declaration part only. Consider the following program.
2.4 Write a program to demonstrate dynamic initialization.
void main()
{
int r=2;
float area=3.14*r*r;
clrscr();
printf(“Area=%g”,area);
}
OUTPUT:
Area=12.56
Explanation:
In the above program, area is calculated and assigned to variable area. The expression is solved
at a run time and assigned to area at a run time. Hence, it is called dynamic initialization.
2.16 Type Modifiers
The keywords signed, unsigned, short and long are type modifiers. A type modifier changes
the meaning of basic data type and produces a new data type. Each of these type modifiers is appli-
cable to the basic data type int. The modifiers signed and unsigned are also applicable to the type
char. The long type modifier can be applicable to double type.
Example:
long l; / int data type is applied /
int s; / signed is default /
unsigned long int; / int keyword is optional /
2.5 Write a program to declare different variables with type modifiers and display them.
void main()
{
short t=1;
long k=54111;
unsigned u=10;
signed j=-10;
clrscr();
printf(“\n t=%d”,t);
printf(“\n k=%ld”,k);
printf(“\n u=%u”,u);
printf(“\n j=%d”,j);
}
OUTPUT:
t=1
k=54111
u=10
j=-10
Explanation:
Here in the above program, all the variables are of integer type. The variable t and k are
short and long type, whereas u and j are unsigned and signed integers, respectively.
2.17 Type Conversion
In C, it is possible to convert one data type to another. This process can be done either explicitly or
implicitly. The following section describes explicit type conversion.
(i) Explicit type conversion
a) Sometimes a programmer needs the result in certain data type, for example division of
5 with 2 should return float value. Practically the compiler always returns integer values
because both the arguments are of integer data type.
(ii) Implicit type conversion
In C automatically ‘lower’ data type is promoted to ‘upper’ data type. For example, data type
char or short is converted to int. This type of conversion is called as automatic unary
conversion. Even when binary operator has different data types, ‘lower’ data type is converted
to ‘upper’ data type.
In case an expression contains one of the operands as unsigned operands and another non-
unsigned, the latter operand is converted to unsigned.
Similarly, in case an expression contains one of the operands as float operands and another
non-float, the latter operand is converted to float.
Similarly, in case an expression contains one of the operands as double operand and another
non-double, the latter operand is converted to double.
Similarly, in case an expression contains one of the operands as long int and the other un-
signed int operands, the latter operand is converted to long int.
For the sake of understanding, the following table describes automatic data type conversion
from one data type to another while evaluating an expression.
#include <stdio.h>
#include <conio.h>
int main()
{
short a=5;
long int b=123456;
float c=234.56;
double d=234567.78695;
clrscr();
printf(“%lf”,((a+b)*c)/d);
return 0;
}
OUTPUT:
123.456900
Explanation:
In the above program, we have taken the variable ‘a’ as short int, ‘b’ as long, c as float and
‘d’ as double. The expression ((a + b) c)/d) gives the result as double float.
Sometimes a programmer needs the result in a certain data type, for example division of 5 with 2
should return float value. Practically, the compiler always returns integer values because both the
arguments are of integer data type. This can be followed by the execution of the following program.
2.7 Write a program to change data type of results obtained by division operations.
void main()
{
clrscr();
printf(“\n Division operation Result”);
printf(“\n Two Integers (5 & 2) : %d”,5/2);
OUTPUT:
Division operation Result
Two Integers (5 & 2): 2
One int & one float (5.5 & 2): 2.75
Two Integers (5 & 2): 2.5
Explanation:
In the first division, operation data types are chosen as integer. Hence, the result turns out to
be an integer. Actually, the result should be a float value but the compiler returns an integer
value. In the second division operation, a float value is divided by an integer. The result of divi-
sion in this case, yields a float. The limitation of the first operation is removed in the third
division operation using type conversion. Here, both the values are of integer type. The result
obtained is converted into float. The program uses type casting which is nothing but putting
data type in a pair parenthesis before operation. The programmer can specify any data type.
(i) Suppose you assign a float value to an integer variable.
Example:
int x=3.5;
Here, the fraction part will not be assigned to integer variable and the part will be lost. The
integer is 2 byes length data type without fractional part and float is 4 bytes data type with
fractional part.
(ii) In another example, suppose you assign 35425 to int x; you will not get expected result
because 35425 is larger than short integer range.
The following assignments are invalid:
int=long;
int=float;
long=float
float=double
The following assignments are valid:
long=int
double=float
int=char
2.18 Wrapping Around
When the value of variable goes beyond its limit, the compiler would not flag any error message. It
just wraps around the value of a variable. For example, the range of unsigned integer is 0 to 65535. In
this type, negative values and values greater than 65535 are compatible.
unsigned int x=65536;
The value assigned is greater by 1 than the range. Here, the compiler starts again from beginning after
reaching the end of the range.
Consider the following example.
2.8 Write a program to demonstrate wrapping around.
void main()
{
unsigned u=65537;
clrscr();
printf(“\n u=%u”,u);
}
OUTPUT:
u=1
Explanation:
In this program, the unsigned integer u = 65537; after reaching the last range 65535, the compiler
starts from beginning. Hence, 1 is displayed. The value 65536 refers to 0 and 65537 to 1.
void main()
{
const int num=12;
++num;
}
The above program code will not be executed and end with error message. Here, a constant variable
attempted to modify its value.
2.19.2 | Volatile Variable
The volatile variables are those variables that can be changed at any time by other external program
or the same program. The syntax is as follows:
volatile int d;
void main()
{
volatile int x;
volatile const int y=10;
clrscr();
printf(“Enter an integer:”);
scanf(“%d”,&x);
printf(“Entered integer is :%d”,x);
x=3;
printf(“\nChanged value of x is :%d”,x);
printf(“\nValue of y:%d”,y);
/* y=8;*/
getche();
}
OUTPUT:
Enter an integer:5
Entered integer is :5
Changed value of x is :3
Value of y:10
Explanation:
In the above example, the variable x is initialized with keyword volatile and y is with
volatile constant. Value of x can be changed but volatile const can not be changed.
Make an attempt to include the comment statement in the program and see the response
of the compiler. The error would be thrown by the compiler and message displayed on the
screen would be ‘cannot modify a const value’.
Summary
After having studied the basics in the first chapter, the reader is now exposed to, in this second chapter,
the additional fundamentals of C. These concepts are absolutely essential for writing programs. Read-
ers are suggested go in depth of this chapter as it contains the fundamentals and basics. The reader is
made aware of the following points:
(i) Different types of characters like letters, digits, white space and special characters. Various
delimiters used with C statements, keywords and identifies.
(ii) Different constants, variables and data types.
(iii) Rules for defining variables and initializing them. Also initialization of variables at run time
(dynamic initialization) is studied.
(iv) Type conversion of variable, type modifiers, wrapping around. Constant and volatile variables.
eXercISeS
I True or false:
1. Data means the combination of letters, digits, 11. A value of variable can be changed during the
symbols. program execution.
2. In C, A to Z and a to z are treated as the same. 12. A variable name can start with a digit.
3. The signed is a C keyword. 13. The keyword can act as a variable name.
4. The new is a C keyword. 14. In C the variable name sum & Sum are the same.
5. 10.120 is a integer constant. 15. short int and int are different from each
6. Identifiers are the name of variables, arrays, other.
functions, and so on. 16. int, short int and long int belong to
7. The constant in C is applicable to values one category with different size and range of
which do not change during program execution. values.
II Select the appropriate option from the multiple choices given below:
1. A character variable can store only 5. The declaration of C variable can be done
(a) one character (a) anywhere in the program
(b) 20 character (b) in declaration part
(c) 254 character (c) in executable part
(d) None of the above (d) at the end of a program
2. A C variable cannot start with 6. In C one statement can declare
(a) a number (a) only one variables
(b) an alphabet (b) two variables
(c) a character (c) 10 variables
(d) None of the above (d) any number of variables
3. A short integer variable occupies memory of 7. The word ‘int’ is a
(a) 1 bytes (a) keyword
(b) 2 byes (b) password
(c) 4 bytes (c) header file
(d) 8 bytes (d) None of the above
4. C keywords are reserved words by 8. The variables are initialized using
(a) a compiler (a) greater than (>)
(b) an interpreter (b) equal to (=)
(c) header file (c) twice equal to (==)
(d) Both (b) and (c) (d) an increment operator (++)
1. clrscr();
void main() printf(“\n u=%u l=%ld”,
{ u,l);
char c=90; }
clrscr();
4.
printf(“%c”,c);
void main()
}
{
2. float a=3e-1,b=2e-2;
void main() clrscr();
{ printf(“a=%g b=%g”,a,b);
unsigned char c=65; }
clrscr();
5.
printf(“%d %c %d “,c,c,c);
void main()
}
{
3. int x,a=1e1, b=0;
void main() clrscr();
{ b+=1e1;
unsigned u=2147483647; printf(“a= %d b=%d”,a,b);
long l=2147483647; }
1. 4.
void main() void main()
{ {
clrscr(); float d=65535.43;
printf(“\n %d”, 7/2); double p=65789.987654;
printf(“\n%g”,7.0/2); clrscr();
printf(“\n%g”, float7/2); printf(“%d %d”,d,p);
getche(); getche();
} }
5.
void main()
2. {
void main() float d=1234567.43;
{ double p=987654321.1234567;
volatile d=15; clrscr();
const p=25; printf(“\n%f %lf”,d,p);
clrscr(); printf(“\n%d %d”,size
printf(“%d %d”d+10,p+1); of(d),size of(p));
getche(); getche();
} }
6.
3. #define
#define N= 90
void main() main()
{ {
unsigned int d=65535; int x=10,p;
unsigned char p=65; clrscr();
clrscr(); p=x*N;
printf(“%c %c”,d,p); printf(“\n%d “, p);
getche(); getche();
} }
10. Write about space requirement for variables of 18. What is dynamic initialization?
different data types.
anSwerS
I True or false:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. T 2. F 3. T 4. F 5. F
6. T 7. T 8. T 9. T 10. T
11. T 12. F 13. F 14. F 15. F
16. T 17. F 18. T 19. T
II Select the appropriate option from the multiple choices given below:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. a 2. a 3. b 4. a 5. b
6. d 7. a 8. b 9. a 10. a
11. a 12. b 13. a 14. a 15. d
16. b 17. a 18. b 19. a 20. a
21. a 22. c 23. a 24. a 25. c
26. a 27. a 28. b 29. d 30. a
31. b
4. ontrol string provided is wrong. %f and %lf are needed. Answer would be
C
65535.429688 65789.987654. However, with %d & %d answers obtained would
be wrong.
5. Space between size and of should be removed. The answer will be
1234567.375000 987654321.123457
48
6. Syntex error in first line #define. Remove = . Answer will be 900
3 Operators and
Expressions
Chapter Outline
3.1 Introduction
3.2 Operator Precedence
3.3 Associativity
3.4 Comma and Conditional Operator
3.5 Arithmetic Operators
3.6 Relational Operators
3.7 Assignment Operators and Expressions
3.8 Logical Operators
3.9 Bitwise Operators
3.1 Introduction
In our day-to-day life, we perform numerous operations on data with different operators. In order to
perform different kinds of operations, C uses different operators. An operator indicates an operation to
be performed on data that yields a new value. Using various operators in C, one can link the variable
and constants. An operand is a data item on which operators perform operations. C is rich in use of
different operators. C provides four classes of operators which are: (i) arithmetic, (ii) relational, (iii)
logical and (iv) bitwise. Apart from these basic operators, C also supports additional operators. Basic
operators and others along with their symbolic representation are shown in Table 3.1.
3.2 OPERATOR PRECEDENCE
Precedence means priority. Every operator in C has assigned precedence (priority). An expression
may contain a lot of operators. The operations on the operands are carried out according to the prior-
ity of the operators. The operators having higher priority are evaluated first and then lower priority.
(i) For example, in arithmetic operators, the operators , / and % have assigned highest priority
and of similar precedence. The operators + and – have the lowest priority as compared to the
above operators.
Example:
8+9 2–10
The operator is the highest priority. Hence, the multiplication operation is performed first.
The above expression becomes
8+18 –10
In the above expression, + and – have the same priority. In such a situation, the left most
operation is evaluated first. With this the above expression becomes
26−10
At last the subtraction operation is performed and answer of the expression will be as follows:
16
(ii) When the operators of the same priority are found in the expression, precedence is given to
the left most operators.
Example:
x x=
= 5 *5*4
4 ++ 88/2;
/ 2;
1 2
Here, 5 4 is evaluated first, though and / have the same priorities. The operator occurs
before / and hence evaluation starts from left. The answer for the above equation after evalu-
ation becomes 24.
(iii) If there is more number of parentheses in the expression, the innermost parenthesis will be
solved first, followed by the second and lastly the outermost.
Example:
(8 / ( 2 * (2*2)));
(8 / ( 2 * ( 2 * 2 ) ) );
1
Here,
(a) Innermost bracket is evaluated first (i.e. 2 2=4).
(b) Second innermost bracket is evaluated. 2 is multiplied with result of innermost bracket. The
answer of 2 4=8.
(c) The outer most bracket expression is evaluated at last. 8 is divided by 8 and gives result 1.
Example:
Show the steps for evaluation of the following equation.
x − y + z / k == a / b − h +u % t
4 1 2 3
5 6
8 7
# include <stdio.h>
# include <conio.h>
main ()
{
int a=1,b=2,c=3,j;
clrscr();
j=a+b*c;
printf (“\n j=%d”,j);
j=(a+b)*c;
printf (“\n j=%d”,j);
}
OUTPUT:
j=7
j=9
Explanation:
In this program, in the expression j = a + b c, first multiplication operation is performed followed
by addition operation; hence, value of j is 7. In the second expression, the parentheses give first
priority to the addition operation. Hence, addition of a and b is performed first and followed by
multiplication is performed.
(Continued)
3.3 ASSOCIATIVITY
When an expression contains operators with equal precedence then the associativity property decides
which operation to be performed first. Associativity means the direction of execution. Associativity
is of two types.
(i) Left to right: In this type, expression, evaluation starts from left to right direction.
Example:
12 4 / 8 % 2
In the above expression, all operators are having the same precedence, and so associativity
rule is followed (i.e. direction of execution is from left to right).
= 48 / 8 % 2
= 6 % 2
= 0 (The above modulus operation provides remainder 0)
(ii) Right to left: In this type, expression, evaluation starts from right to left direction.
Example:
a=b=c
In the above example, assignment operators are used. The value of c is assigned to b and then
to a. Thus, evaluation, is from right to left.
void main()
{
clrscr();
printf(“Addition = %d\nSubtraction = %d”,2+3,5-4);
}
OUTPUT:
Addition = 5
Subtraction = 1
Explanation:
In the above-mentioned program, the two equations are separated by commas. The results
are obtained by solving the expressions separated by commas. The result obtained is printed
through printf() statement.
(ii) Conditional Operator (?): The conditional operator contains condition followed by two
statements or values. The condition operator is also called the ternary operator. If the condi-
tion is true, the first statement is executed, otherwise the second statement is executed.
Conditional operators (?) and (:) are sometimes called ternary operators because they take
three arguments. The syntax of the conditional operator is as follows:
Syntax:
Condition ? (expression1) : (expression2);
Two expressions are separated by a colon. If the condition is true expression 1 gets evalu-
ated, otherwise expression 2 gets evaluated. The condition is always written before the ?
mark.
void main()
{
clrscr();
printf(“Result = %d”,2==3 ? 4 : 5 );
}
OUTPUT:
Result = 5
Explanation:
In the above-given program, the condition 2= =3 is false. Hence, 5 is printed.
3.4 Write a program to use the conditional operator with two statements.
void main()
{
clrscr();
3>2 ? printf(“True.”) : printf(“False.”);
}
OUTPUT:
True.
Explanation:
In the above-given program, a full statement is used as the conditional operator. The condi-
tion 3>2 is true. Hence, the first printf() statement is executed.
Operators Binary
Ternary
(i) Binary Operator: Table 3.3 shows different arithmetic operators that are used in C. These opera-
tors are commonly used in most of the computer languages. These arithmetic operators are used
for numerical calculations between the two constant values. They are also called Binary Arithme-
tic Operators. Binary operators are those operators which require two operands. The examples are
also given in Table 3.3. In the program, variables are declared instead of constants.
(ii) Unary Operators: The operators which require only one operand are called unary operators.
Unary operators are increment operator (++), decrement (– –) and minus (–). These operators
and their descriptions are given in Table 3.4.
Table 3.4 Unary arithmetic operators
Operator Description or Action
- Minus
++ Increment
-- Decrement
& Address operator
sizeof Gives the size of an operator
(a) Minus (−): Unary minus is used for indicating or changing the algebraic sign of a value.
Example:
int x=–50;
int y=–x;
assign the value of –50 to x and the value of –50 to y through x. The minus (–) sign used in this
way is called the unary operator because it takes just one operand. There is no unary plus (+)
in C. Even though, a value assigned with plus sign is valid, for example int x=+50, here, + is
valid, but in practice this sign should not be attached in C.
(b) Increment (++) and Decrement (– –) Operators: The C compilers produce very fast and ef-
ficient object codes for increment and decrement operations. This code is better than generated
by using the equivalent assignment statement. So, increment and decrement operators should
be used whenever possible.
The operator ++ adds one to its operand, whereas the operator -- subtracts one from its
operand. For justification, x=x+1 can be written as x++; and x=x–1; can be written as
x--;. Both these operators may either follow or precede the operand. That is x=x+1; can be
represented as x++; or ++x;
If ‘++’ or ‘--’ are used as a suffix to the variable name, then post-increment/decrement opera-
tions take place. Consider an example for understanding the ‘++’ operator as a suffix to the
variable.
x=20;
y=10;
z=x*y++;
In the above equation, the current value of y is used for the product. The result is 200, which
is assigned to ‘z’. After multiplication the value of y is incremented by one.
If ‘++’ or ‘— —’ are used as a prefix to the variable name, then pre increment/decrement operations
take place. Consider an example for understanding ‘++’ operator as a prefix to the variable.
x=20;
y=10;
z=x*++y;
In the above equation, the value of y is incremented and then multiplication is carried out. The
result is 220, which is assigned to ‘z’. The following programs can be executed for verification
of increment and decrement operations.
3.5 Write a program to show the effect of increment operator as a suffix.
void main()
{
int a,z,x=10,y=20;
clrscr();
z=x*y++;
a=x*y;
printf(“\n%d %d”,z,a);
}
OUTPUT:
200 210
Explanation:
In the above program, the equation z=x*y++ gives the result 200 because ‘y’ does not get
incremented. After multiplication, ‘y’ incremented to 21. The second equation gives the result,
i.e. 210. This can be verified by executing the above program.
3.6 Write a program to show the effect of increment operator as a prefix.
void main()
{
int a,z,x=10,y=20;
clrscr();
z=x*++y;
a=x*y;
printf(“\n%d %d”,z,a);
}
OUTPUT:
210 210
Explanation:
In the above program, ‘y’ gets first incremented and the equations are solved. Here, both the
equations give the same result, i.e. 210.
(c) sizeof and ‘&’ Operator :
The sizeof operator gives the bytes occupied by a variable, i.e. the size in terms of bytes
required in memory to store the value. The number of bytes occupied varies from variable to
variable depending upon its data types.
The ‘&’ operator prints address of the variable in the memory. The below mentioned example
illustrates the use of these operators.
3.7 Write a program to use ‘&’ and sizeof operator and determine the size of integer and float
variables.
void main()
{
int x=2;
float y=2;
clrscr();
printf(“\n sizeof(x)=%d bytes”,sizeof(x));
printf(“\n sizeof(y)=%d bytes”,sizeof(y));
printf(“\n Address of x=%u and y=%u”,&x,&y);
}
OUTPUT:
sizeof(x)=2
sizeof(y)=4
Address of x=4066 and y=25096
Explanation:
In the above example, variables x and y are declared and initialized. The variable x is an
integer and y is a float data type. Using sizeof() and ‘&’ operator, their sizes and ad-
dresses can be displayed.
3.6 Relational Operators
These operators are used to distinguish between two values depending on their relations. These op-
erators provide the relationship between two expressions. If the relation is true then it returns a value
1 otherwise 0 for false. The relational operators together with their descriptions, example and return
value are described in Table 3.5.
== Equal to 2==3 0
The relational operator’s symbols are easy for understanding. They are self-explanatory. How-
ever, for the benefit of the readers a program is illustrated below.
3.8 Write a program to use various relational operators and display their return values.
void main()
{
clrscr();
printf(“\nCondition : Return Values\n” );
printf(“\n10!=10 : %5d”,10!=10);
printf(“\n10==10 : %5d”,10==10);
printf(“\n10>=10 : %5d”,10>=10);
printf(“\n10<=100: %5d”,10<=100);
printf(“\n10!=9 : %5d”,10!=9);
}
OUTPUT:
Condition: Return Values
10!=10 : 0
10==10 : 1
10>=10 : 1
10<=100: 1
10!=9 : 1
Explanation:
In the above program, the true conditions return 1 and false 0. In this example, the first condi-
tion is false and remaining are true. Hence, the return value for the first is 0 and for remaining
it is 1.
Assume a program to perform certain steps on the basis of a condition. If A > 5, then some action
will be performed. The example, which is illustrated below, uses the relational operator.
Consider the following example: k=k+3; in this expression, the variable on the left side of = is
repeated on the right. The same can be written as follows:
k+=3;
The operators = and += are called assignment operators. The binary operators which need two oper-
ands to their either side are surely have a corresponding assignment operator operand = to the left
side.
Example:
j*=x+1;
or
j=j*(x+1);
3.9 Write a program to determine the value of ‘b’ depending on the inputted value of ‘a’. The
variable ‘a’ is used with the conditional operator.
void main()
{
int a,b;
clrscr();
printf(“Enter Any Integer either above 5 or below 5 :-”);
scanf(“%d”, &a);
b=(a>5 ? 3 : 4);
printf(“Calculated Value of b is :- %d”,b);
}
OUTPUT:
Enter Any Integer either above 5 or below 5:- 6
Calculated Value of b is:- 3
OR
Enter Any Integer either above 5 or below 5:- 3
Calculated Value of b is:- 4
Explanation:
On the execution of the above program, the value of b will be 3 if the value of a is greater than 5.
Otherwise, it will be 4 for any number which is less than 5. Similarly, for the other operators,
programs are as follows.
3.10 Determine the value of ‘b’ using the conditional statement.
void main()
{
int a,b;
clrscr();
Explanation:
In the above-given program, the value of the variable ‘a’ is entered. The value is compared
with 5. If a is equal to 5, 3 is assigned to b otherwise 4. In this example, 3 is entered which
is not equal to five. Hence, 4 is assigned to b.
The following program illustrates the use of various relational operators.
3.11 Write a program to read three variables x, y and z. Use conditional statements and evaluate
values of variables a, b and c. Perform the sum with two sets of variables. Check the sums
for equality and print different messages.
void main()
{
int x,y,z,a,b,c,m,n;
clrscr();
printf(“Enter Values of x, y, z :-”);
scanf(“%d %d %d”, &x,&y,&z);
a=(x>=5 ? 3 : 4);
printf(“\n Calculated value of a is :- %d”, a);
b=(y<=8 ? 10 : 9);
printf(“\n Calculated value of b is :- %d”, b);
c=(z==10 ? 20 : 30);
printf(“\n Calculated value of c is :- %d”, c);
m=x+y+z;
n=a+b+c;
printf(“\nAddition of x,y,z is %d (m)”, m);
printf(“\nAddition of a,b,c is %d (n)”, n);
printf(“\n%s”, m!=n ? “m & n NOT EQUAL” : “m & n ARE EQUAL”);
}
OUTPUT:
Enter Values of x, y, z:- 5 2 7
Calculated value of a is:- 3
Calculated value of b is:- 10
Calculated value of c is:- 30
Addition of x,y,z is 14 (m)
Addition of a,b,c is 43 (n)
m & n NOT EQUAL
Explanation:
In the above given program, three integers are entered through the keyboard (x, y and z).
Using conditional statements, values of a, b and c are obtained. The sum of x, y and z is
stored in ‘m’ and the sum of a, b and c is stored in ‘n’. The variables ‘m’ and ‘n’ are com-
pared and appropriate messages are displayed.
3.8 Logical Operators
The logical relationship between the two expressions is tested with logical operators. Using these
operators, two expressions can be joined. After checking the conditions, it provides logical true (1) or
false (0) status. The operands could be constants, variables and expressions. Table 3.7 describes the
three logical operators together with examples and their return values.
Table 3.7 Logical operators
Operator Description or Action Example Return Value
&& Logical AND 5>3 && 5<10 1
|| Logical OR 8>5 || 8<2 1
! Logical NOT 8!=8 0
From Table 3.7, following rules can be followed for logical operators:
(i) The logical AND (&&) operator provides true result when both expressions are true,
otherwise 0.
(ii) The logical OR (||) operator provides true result when one of the expressions is true,
otherwise 0.
(iii) The logical NOT operator (!) provides 0 if the condition is true, otherwise 1.
void main()
{
clrscr();
printf(“\nCondition : Return Values\n” );
printf(“\n5>3 && 5<10 : %5d”,5>3 && 5<10);
printf(“\n 8>5 || 8<2 : %5d”,8>5 || 8<2);
printf(“\n !(8==8) : %5d”,!(8==8));
}
OUTPUT:
Condition : Return Values
5>3 && 5<10 : 1
8>5 || 8<2 : 1
!(8==8) : 0
Explanation:
In the above example, the first and second conditions are true. In the first condition, 5 is greater
than 3 and smaller than 10; hence, output is 1. In the second condition, 8 is greater than 5 and due
to OR operation its output is 1. The third condition is wrong. Hence, result returned will be 0.
void main()
{
char x;
int y;
clrscr();
printf(“\nEnter a Character :”);
scanf(“%c”, &x);
y=(x>=65 && x<=90 ? 1 : 0);
printf(“Y :%d”,y);
}
OUTPUT:
Enter a Character : A
Y: 1
Enter a Character : a
Y: 0
Explanation:
In the above-given program, a character is entered. Using logical operator AND, entered
character’s ASCII value is checked. If it is in between 65 and 90, the result displayed will be 1
otherwise 0. The AND operator joins two conditions. If the condition is true, 1 is assigned to
y otherwise 0.
3.14 Write a program to display logic 0 if one reads a character through keyboard otherwise 1.
(ASCII values for 0 to 9 are 48 to 57, respectively.)
void main()
{
int y;
char x;
clrscr();
printf(“\n Enter The Character or Integer :”);
scanf(“%c”, &x);
y=(x>=48 && x<=57 ? 1 : 0);
Printf(“\nValue of Y =%d”,y);
}
OUTPUT:
Enter The Character or Integer : A
Value of Y = 0
OR
Enter The Character or Integer : 1
Value of Y = 1
Explanation:
The above-given program is the same as the previous one. Here, ASCII range 48 to 57 is
used. Equivalent of these values are 0 to 9 digits, respectively. If the entered number is in
between 0 to 9, the compiler returns 1 otherwise 0.
3.15 Write a program to display l if inputted number is between 1 and 100 otherwise 0. Use the
logical AND (&&) operator.
void main()
{
int x,z;
clrscr();
printf(“Enter numbers :”);
scanf(“%d”, &x);
z=(x>=1 && x<=100 ? 1 : 0);
printf(“Z=%d”, z);
}
OUTPUT:
Enter numbers : 5
Z = 1
Enter numbers : 101
Z = 0
Explanation:
The logical operator checks the entered value whether it is in between 1 and 100. If the condition
is true, 1 is assigned to z otherwise 0.
3.16 Write a program to display l if inputted number is either 1 or 100 otherwise 0. Use the logi-
cal OR (||) operator.
main()
{
int x,z;
clrscr();
printf(“Enter numbers :”);
scanf(“%d”, &x);
z=(x==1 || x==100 ? 1 : 0);
printf(“Z=%d”, z);
}
OUTPUT:
Enter numbers : 1
Z = 1
Enter numbers : 100
Z = 1
Enter numbers : 101
Z = 0
Explanation:
In the above-given program, the OR operator checks two conditions. If one of the conditions
satisfies, 1 is assigned to z otherwise 0.
3.17 Write a program to display l if the inputted number is except 100 otherwise 0. Use the logi-
cal NOT operator (!).
void main()
{
int x,z;
clrscr();
printf(“Enter number :”);
scanf(“%d”, &x);
z=(x!=100 ? 1 : 0);
printf(“d :%d”, z);
}
OUTPUT:
Enter number : 100
d : 0
Enter number : 10
d : 1
Explanation:
In the above-given program ! NOT operator is used with the conditional operator. The value of
x is also entered. Here, if the value of x is other than 100, then 1 is assigned to z otherwise 0.
void main()
{
int x,y;
clrscr();
printf(“Read The Integer from keyboard (x) :-”);
scanf(“%d”, &x);
x>>=2;
y=x;
printf(“The Right shifted data is = %d”,y);
}
OUTPUT:
Read The Integer from keyboard (x) :- 8
The Right shifted data is = 2
Before the execution of the program: The number entered through the keyboard is 8 and its corre-
sponding binary number is 1 0 0 0.
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
After execution of the program: As per the above-given program, the inputted data x is to be shifted
by 2 bits right side. The answer in binary bits would be as follows:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
Shifting two bits right means the inputted number is to be divided by 2 where s is the number of shifts
s
i.e. in short y=n/2s, where n = number and s = the number of position to be shift.
As per the program cited above, Y=8/22 = 2.
Similarly, a program for shifting to the left can be written as follows:
void main()
{
int x,y;
clrscr();
printf(“Read The Integer from keyboard (x) :-”);
scanf(“%d”, &x);
x<<=3;
y=x;
printf(“The Right shifted data is = %d”,y);
}
OUTPUT:
Read The Integer from keyboard (x) :- 2
The Left shifted data is = 16
Before the execution of the program: The number entered through the keyboard is 2 and its corre-
sponding binary number is 1 0. The bits will be as follows:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
After execution of the program: As per the above-given program, the inputted data x is to be shifted
by 3 bits left side. The answer in the binary bits would be as follows:
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
The corresponding decimal number is 16, i.e. answer should be 16.
Shifting three bits left means the number is multiplied by 8; in short y=n*2s where n = number and
s = the number of position to be shifted.
As per the program given above,
Y=2*23 = 16.
3.20 Write a program to use bitwise AND operator between the two integers and display the results.
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integers from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a & b;
printf(“The Answer after ANDing is (C)= %d”,c);
}
OUTPUT:
Read The Integers from keyboard (a & b) : 8 4
The Answer after ANDing is (C) = 0
Binary equivalent of 8 is
Before execution:
a=8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
b=4
Binary equivalent of 4 is
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
After execution
c=0
Binary equivalent of 0 is
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
OR
Read The Integers through keyboard (a & b) : 8 8
The Answer after ANDing is (C) = 8
Before execution
a=8
Binary equivalent of 8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
Before execution
b=8
Binary equivalent of 8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
After execution
c=8
Binary equivalent of 8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
The table for AND operation (Table 3.9) is as follows and can be used in future for reference.
Similarly, the table for OR operator (Table 3.10) can be used as follows.
Table 3.9 Table for AND Table 3.10 Table for OR operator
Inputs Output Inputs Output
X Y Z X Y Z
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1
3.21 Write a program to operate OR operation on two integers and display the result.
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integer from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a | b;
printf(“The Oring operation bewteen a & b in c = %d”,c);
getche();
}
OUTPUT:
Read The Integer from keyboard (a & b) :- 8 4
The Oring operation between a & b in c = 12
Before execution
a=8
Binary equivalent of 8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
Before execution
b=4
Binary equivalent of 4
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
After execution
c=12
Binary equivalent of 12
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
The table for Exclusive OR (XOR) is as follows (Table 3.11).
Table 3.11 Table of exclusive OR
Inputs Output
X Y Z
0 0 0
0 1 1
1 0 1
1 1 0
3.22 Write a program with Exclusive OR Operation between the two integers and display the result.
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integers from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a^b;
OUTPUT:
Read The Integers from keyboard (a & b) : 8 2
The data after Exclusive OR operation is in c =10
Before execution
a=8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
Before execution
b=2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
After execution
c=10
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 0
The table for bitwise complement-operator (Inverter Logic) is as follows (Table 3.12).
The operator ~ is used for inverting the bits with this operator 0 becomes 1 & 1 becomes 0.
void main()
{
unsigned int v=0;
clrscr();
printf(“\n %u”, ~v);
}
OUTPUT:
65535
SummArY
You have now studied the various operators such as arithmetic, logical and relational which are essen-
tial for writing and executing programs. The precedence and associativity of the operators in the arith-
metic operations are also furnished in the form of a table. The conditional and comma operators and
programs on them are also described in this chapter. You are made aware about the logical operators
OR, AND and NOT. Full descriptions of bitwise operators have been illustrated. Numerous simple
examples have been provided to the users to understand the various operators. The reader is expected
to write more programs on this chapter.
ExErcISES
I Select the appropriate option from the multiple choices given below:
1. What will be the output of the following program? 3. What will be the value of x, y and z after the
execution of the following program?
void main()
{ void main()
int ans=2; {
int m=10; int x,y,z;
int k; y=2;
k=!((ans<2) && (m>2)); x=2;
printf(“\n %d”,k); x=2*(y++);
} z=2*(++y);
printf(“\n x=%d y=%d
(a) 1
z=%d”,x,y,z);
(b) 0
}
(c) –1
(d) 2 (a) x=4 y=4 z=8
(b) x=6 y=4 z=8
2. What will be the output of the following
program? (c) x=2 y=4 z=8
(d) x=4 y=4 z=4
void main()
{ 4. What will be the value of ‘x’ after the execution
int m,j=3,k; of the following program?
m=2*j/2; void main()
k=2*(j/2); {
clrscr(); int x=!0*10;
printf(“\n m=%d k=%d”,m,k); }
}
(a) 10
(a) m=3 k=2 (b) 1
(b) m=3 k=3 (c) 0
(c) m=2 k=3
(d) None of the above
(d) m=2 k=2
7. What will be the output after the execution of the 13. The result of expression (23*2) % (int)
following program? 5.5 is
void main() (a) 2
{ (b) 1
int k=8; (c) 3
printf(“k=%d”, k++-k++); (d) 0
}
14. The result of 16>>2 is
(a) k=-1;
(b) k=0; (a) 4
(c) k=8; (b) 8
(d) k=9; (c) 2
(d) 5
8. What will be the value of b after the execution of
the following program? 15. The result of 5&&2 is
void main() (a) 0
{ (b) 1
int b,k=8; (c) 2
b=(k++-k++-k++,k++); (d) 5
}
16. The value of c after the execution of the
(a) b=11; program will be
(b) b=12;
(c) b=7; void main()
{
(d) b=9; int a,b,c;
9. The ‘&’ operator displays a=9;
b=10;
(a) address of the variable c=(b<a || b>a);
(b) value of the variable clrscr();
(c) Both (a) and (b) printf(“\n c=%d”,c);
(d) None of the above }
10. Addition of two numbers is performed using OUTPUT:
(a) arithmetic operator (a) c=1
(b) logical operator (b) c=0
(c) unary operator (c) c=–1
(d) comma operator (d) None of the above
1. Write a program to shift the entered number by 11. Write a program to calculate the total cost of the
three bits left and display the result. vehicle by adding basic cost with (i) excise duty
(15%) (ii) sales tax (10%) (c) octroi (5%) and (d)
2. Write a program to shift the entered number by road tax (1%). Input the basic cost.
five bits right and display the result.
12. Write a program to display ASCII equivalents of
3. Write a program to mask the most significant
digit of the entered number. Use AND operator. (a) ‘A’, ‘B’,‘C’ and ‘a’,‘b’,‘c’.
(b) ‘a’-‘C’, ‘b’-‘A’ and ‘c’ – ‘B’.
4. Write a program to enter two numbers and find the
smallest out of them. Use conditional operator. (c) ‘a’+‘c’, ‘b’*‘a’ and ‘c’+12.
5. Write a program to enter a number and carry out 13. Write a program to enter a number that should
modular division operation by 2, 3 and 4 and be less than 100 and greater than 9. Display the
display the remainders. number in reverse order using modular division
and division operation.
6. Attempt the program (5) with division operation
and find the quotients. 14. Write a program to enter a four-digit number.
Display the digits of the number in the reverse
7. Write a program to enter an integer number and order using modular division and division
display its equivalent values in octal and hexa- operation. Perform addition and multiplication
decimal. of digits.
8. Write a program to convert hexadecimal to deci- 15. Write a program to display numbers from 0 to 9.
mal numbers. Enter the numbers such as 0x1c, Use ASCII range 48 to 59 and control string %c.
0x18, 0xbc, 0xcd.
16. Write a program to evaluate the following
9. Write a program to find the average temperature expressions and display their results.
of five sunny days. Assume the temperature in
(a) x2 +(2*x3)*(2*x)
Celsius.
(b) x1+y2+z3
10. Write a program to enter two numbers. Make
a comparison between them with a conditional assume variables are integers.
operator. If the first number is greater than the
second perform multiplication otherwise 17. Write a program to print whether the number
division operation. entered is even or odd. Use conditional operator.
1. Explain different types of operators supported 8. What are the symbols used for (a) OR, (b) AND,
by C. (c) XOR and (d) NOT operations?
2. What are the uses of comma (,) and conditional 9. Explain the precedence of operators in arithmetic
(?) operators? operations?
3. What are unary operators and describe their uses? 10. List the operators from higher priority to least
priority.
4. Describe logical operators with their return
values. 11. What is the difference between %f and %g?
5. Distinguish between logical and bitwise 12. What are the differences between division and
operators. modular division operations?
6. What are the relational operators? 13. What are the ASCII codes? List the codes for
digits 1 to 9, A to Z and a to z.
7. What is the difference between ‘=’ and ‘= =’?
14. Explain different types of assignment operators. 16. What are the differences between precedence
and associativity?
15. Explain properties of operators.
AnSwErS
I Select the appropriate option from the multiple choices given below:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. a 2. a 3. a 4. a 5. a
6. a 7. a 8. a 9. a 10. a
11. a 12. a 13. b 14. a 15. b
16. a
Chapter Outline
4.1 Introduction
4.2 Formatted Functions
4.3 Flags, Widths and Precision with Format String
4.4 Unformatted Functions
4.5 Commonly Used Library Functions
4.6 Strong Points for Understandability
4.1 Introduction
Reading input data, processing it and displaying the results are the three tasks of any program. The
data is read from the input device such as a keyboard. Operations on the data are performed on the
basis of the operators, and the result is displayed on the screen. All the three tasks are important and
none of them can be ignored.
There are two ways to accept the data. In one method, a data value is assigned to the variable with
an assignment statement. The programmer writes assignment statements in most of the programs. The
assignment statements are mentioned throughout the book. Examples of an assignment statement are
as follows:
(i) int year=2005; (ii) char letter=‘a’; (iii) long int x=123456.
Another way of accepting the data is with functions. In C the input and output functions can be used
for inputting the data and for getting the results, respectively. To perform these tasks in a user friendly
manner, C has a number of input and output functions. When a program needs data, it takes the data
through the input functions and sends results obtained through the output functions. Thus, the input/
output functions are the link between the user and terminals.
There are a number of I/O functions in C, based on the data types. The input/output functions are
classified in two types:
(i) Formatted functions
(ii) Unformatted functions
With formatted functions, the input or output is formatted as per our requirement. The readability
in easy way is possible with formatted functions. For example, with formatted functions one can
decide how the result should appear or display on the screen. The result can be shown on the second
line or it can appear after leaving some space or if the result is a real number then decisions on
the number of digits before and after decimal point, etc. will be taken care in formatted functions.
All I/O functions are defined as stdio.h header file, which can be initialized at the starting of a
program; that is this header file should be included in the program at the beginning. However, for-
matting is not possible with unformatted functions. Various functions of these categories are listed
in Figure 4.1.
Streams perform all input and output operations. The streams are nothing but a sequence of bytes.
In input operations, the bytes (data) flow from input device such as keyboard, a disc drive or network
connection to main memory. Similarly, in output operation bytes flow from main memory to output
devices such as monitor, printer, disc drive, network connection.
When a program performs input and output operations, the streams are connected to the pro-
gram automatically. The operating system always allows streams to redirect to other devices. While
performing these operations, if any error occurs, it will be reported on the screen by the third stream
called standard error stream.
Further elaboration on formatted functions is as follows.
(i) Formatted Functions: The formatted input/output functions read and write, respectively, all
types of data values. They require format string to produce formatted results. Hence, they can
be used for both reading and writing of all data values. The formatted functions return values
after execution. The return value is equal to the number of variables successfully read/written.
Using this value, the user can find out the error that occurred during reading or writing of
data. Using this function, the given numeric data can be represented in float, integer and
double to possible available limits of the language.
printf()
getch() putch()
scanf ()
getche() putchar()
getchar() puts()
gets()
The syntax of input function for inputting the data such as scanf() is as follows:
scanf(“control string”, argu1, argu2,. . .);
Precisely, if we write scanf() as scanf(“%d”,&x); where %d is a control string
which is nothing but conversion specification and it is to be placed within double quote.
The other part is the argument and a sign & (ampersand) must precede it. Arguments are the
identifiers.
For displaying the result, prinf() formatted function is used. In Section 4.2, printf()
and scanf() are discussed in depth.
(ii) Unformatted Functions: The unformatted input/output functions work only with character
data type. They do not require format conversion symbol for formatting of data types because
they work only with character data type. There is no need to convert data. In case, values of
other data types are passed to these functions, they are treated as character data.
void main()
{
int x=2;
float y=2.2;
char z=‘C’;
printf(“%d %f %c”,x,y,z);
}
OUTPUT:
2 2.2000 C
In the above program, %d corresponds to ‘x’ variable, %f to y and %c to ‘z’. The conversion
symbol given by the user helps the printf() to identify the data type of a given variable.
In case a mismatch occurs, the value of a variable is converted according to the conversion
symbol given.
Example:
int main()
{
int y=65;
clrscr();
printf(“%c %d”,y,y );
return 0;
}
OUTPUT:
A 65
In the above example, the integer variable ‘y’ contains the value of 65. The variable ‘y’ is
printed using two-conversion symbols, integer and character. As shown in the output, %c
converts numeric 65 value to its corresponding character A. %d prints the value 65, as it is,
because the variable is of integer type. Sometimes, if no conversion is possible between two
data types, some garbage value is printed.
Example:
int main()
{
int y=7;
clrscr();
printf(“%f”,y );
return 0;
}
In the above example, it is attempted in the printf() statement to print the integer value as
float value providing %f as a conversion symbol. This is not the proper way. While compil-
ing time no error occurs, but after execution the printf() function will produce an error
message ‘floating points formats not linked’.
The format string is nothing but a string that begins and ends with the double quote. The
printf() statement is used to display the data on console or stdout (standard output device).
The format string is a combination of two types of character objects. They are plain character
and conversion specification.
void main()
{
clrscr();
printf(“\n%.2s”,“abcdef”);
printf(“\n%.3s”,“abcdef”);
printf(“\n%.4s”,“abcdef”);
}
OUTPUT:
ab
abc
abcd
Explanation:
Observe the above program carefully and watch the width specified along with conversion
specification character %s. Although the actual string length is six characters, the number of
printed characters as per printf() statements is 2, 3 and 4, respectively.
4.2 Write a program to demonstrate the use of width specifier.
void main()
{
int x=55,y=33;
clrscr();
printf(“\n %3d”,x-y);
printf(“\n %6d”,x-y);
}
OUTPUT:
22
22
Explanation:
In this program, in the first printf() statement width is given 3 and in second width is
given 6. Hence, the results are displayed at different positions on the screen.
4.3 Write a program to demonstrate the use of ‘*’ for formatting.
void main()
{
int x=55,y=33;
clrscr();
printf(“\n %*d”,15,x-y);
printf(“\n %*d”,5,x-y);
}
OUTPUT:
22
22
Explanation:
In this program, ‘*’ is used along with format string or conversion specification character %d.
An extra parameter is required to mention or set the starting column for printing. This value
is given along the set of variables. You can observe in the printf() statements the values
15 and 5 that indicate the position from where printing on screen begins.
Precision specifiers: Precise results on the screen can be obtained. The precision specifier
always starts with a period or a dot in order to separate it from any preceding width specifiers.
Consider the following program:
4.4 Write a program to demonstrate the use of precision specifiers.
void main()
{
float g=123.456789;
clrscr();
printf(“\n %.1f”,g);
printf(“\n %.2f”,g);
printf(“\n %.3f”,g);
printf(“\n %.4f”,g);
}
OUTPUT:
123.5
123.46
123.457
123.4568
Explanation:
In the above program, the precision value is specified before the format string. Fractional part
after decimal point can be precisely shown in various printf() statements. The output
shows these numbers.
From the above examples, it is now clear that outputs can be shown in different formats. Table 4.1
describes the various formats for presenting various outputs.
void main()
{
clrscr();
printf(“\n%5d”,12);
printf(“\n%5d”,123);
printf(“\n%5d”,1234);
printf(“\n %4.5f”,6.12);
printf(“\n %4.6f”,16.12);
printf(“\n %4.7f”,167.12);
printf(“\n %4.8f”,1678.12);
printf(“\n %8s”,“Amitkumar”);
printf(“\n %8.2s”,“Amitkumar”);
getche();
}
OUTPUT:
12
123
1234
6.12000
16.120000
167.1200000
1678.12000000
Amitkumar
Am
(ii) The scanf() statement: The scanf() statement reads all types of data values. It is used
for runtime assignment of variables. The scanf() statement also requires conversion
symbol to identify the data to be read during the execution of the program. The scanf()
statement stops functioning when some input entered does not match with format string.
The syntax of the scanf() statement is the same as printf() except they work exactly
opposite of each other.
Syntax:
The syntax of the input function for inputting the data is scanf().
Example:
scanf(“control string”, address of variable 1,address of vari-
able 2,----);
The control string has to be enclosed within double quotes. It specifies the format specifier,
such as %d for integer, %f for float, %c for character, etc. and the data are to be invoked by
arguments, such as address of variable1, address of variable 2, etc.
Precisely, we write scanf() as scanf(“%d”,&x);
Here, “ %d” is the format specifier in the control string, which is nothing but the conversion
specification and it is to be placed within double quotes. The other part is the variable and &
(ampersand) must precede it.
The format specifiers and their meanings are given below.
%d: The data is taken as integer.
%c: The data is taken as character.
%s: The data string.
%f: The data is taken as float.
scanf(“%d %f %c”,&a,&b,&c);
The scanf() statement requires ‘&’ operator called address operator. The address operator
prints the memory location of the variable. Here, in the scanf() statement the role of ‘&’
operator is to indicate the memory location of the variable, so that the value read would be
placed at that location.
The scanf() statement also returns values. The return value is exactly equal to the number
of values correctly read. In case of any mismatch, error will be thrown. Otherwise, if the read
value is convertible to the given format, conversion is made. The following program shows an
example of such a mismatch case.
void main()
{
int a;
clrscr();
printf(“Enter value of ‘A’ : ”);
scanf(“%c”,&a);
printf(“A=%c”,a);
}
OUTPUT:
Enter value of ‘A’ : 8
A=8
Explanation:
In the above program, although the type of variable ‘a’ is int, it works perfectly with
conversion symbol of character, i.e. character and integer data types are compatible to
each other. When the two data types are compatible to each other, the compatible range
is equal to the lowest range from the two data types. The above example illustrates this
point.
4.7 Write a program to read and print the integer value using the character variable.
void main()
{
char a;
clrscr();
printf(“Enter value of ‘A’ : ”);
scanf(“%d”,&a);
printf(“A=%d”,a);
}
OUTPUT:
Enter value of ‘A’ : 255
A=255
Enter value of ‘A’ : 256
A=0
Explanation:
In the above program variable ‘a’ is of character type, i.e. its valid range is 0 to 255. The
variable ‘a’ is used with conversion symbol of integer data type, i.e. in the printf() and
scanf() statements the variable ‘a’ is supposed as an integer type. The value read in the
first execution is valid. Hence, it is printed as it is read. In the second execution, the value
read is greater than the range of the character type. In such a case, the excess range is again
considered as the beginning or starting point. Here, the excess value is 1. That is why 0 is
printed.
Consider the following scanf() statements, where a, b and c are integer variables.
Examples:
(i) scanf(“%d %d %d”,a,b,c);
(ii) scanf(“%d,%d,%d”,a,b,c);
In the first statement, the format strings (%d) are separated by a space. It indicates that while
inputting values for these variables, the values should be separated by space. Similarly, in the
second statement, the format strings (%d) are separated by a comma; therefore, while input-
ting, values should be separated by a comma. The following program illustrates this.
4.8 Write a program to demonstrate the use of comma with scanf() statement.
void main()
{
int a,b,c;
clrscr();
printf(“\nEnter values :”);
scanf(“%d, %d,%d”,&a,&b,&c);
printf(“a=%d b=%d c=%d”,a,b,c);
}
OUTPUT:
Enter values: 4,5,8
a=4 b=5 c=8
Explanation:
From the above program, it is very clear that if format strings are separated by commas, the
inputs should also be separated by commas. The readers are advised to try this by writing more
programs. Table 4.2 describes the formats for the various inputs.
void main()
{
int a,b;
float x;
char name[20];
clrscr();
printf(“Enter two integers:-\n”);
scanf(“%4d %4d”,&a,&b);
printf(“\nEntered integers are”);
printf(“\n%4d %4d”,a,b);
printf(“\n”);
printf(“\nEnter a real number:-\n”);
scanf(“%f”,&x);
printf(“\n Entered float number is ”);
printf(“\n%f”,x);
printf(“\n”);
printf(“\nEnter a string :-\n”);
scanf(“%7s”,name);
printf(“\n Entered string ”);
printf(“\n%7s”,name);
getche();
}
OUTPUT:
Enter two integers:-
1 2
Entered integers are
1 2
Enter a real number:-
12.3
Entered float number is
12.300000
Enter a string:-
Deelipkumar
Entered string
Deelipk
Explanation:
In the scanf() statements, the format for various inputs are taken. Similarly, the outputs
are also provided with various formats. The readers can verify the input and output.
The prinf() and scanf() statements follow different data types which are listed in
Table 4.3. It can be seen from this table that format string is initialized with %sign as a special
character, which indicates the format of the data to be displayed on the screen.
The printf() and scanf() statements follow the combination of characters called es-
cape sequences. In order to come out, computers from routine sequence escape sequences are
used. These are nothing but special characters starting with ‘\’. The escape sequences and
their uses are illustrated in Table 4.4.
void main()
{
int a=1,b=a+1,c=b+1,d=c+1;
clrscr();
printf(“\tA=%d\nB=%d \‘C=%d\’”,a,b,c);
printf(“\n\b***\D=%d**”,d);
printf(“\n*************”);
printf(“\rA=%d B=%d”,a,b);
}
OUTPUT:
A=1
B=2 ‘C=3’
***D=4**
A=1 B=2******
Explanation:
In the above program, a few commonly used escape sequences are described.
(i)
In the first printf() statement due to ‘\t’, prints the value of ‘a’ after a tab. The ‘\n’
splits the line and prints the value of B and C on the next line.
(ii) In the second printf() statement the three prefixes ‘*’ are written followed by the ‘\b’. The
‘\b’ overwrites the last character. The output D=4 will be displayed.
(iii) In the third printf() statement only the sequences of ‘*’ are printed, but in the output only
half line is displayed because it is affected by the fourth printf() statement.
(iv) In the fourth printf() statement ‘\r’ is used which reverses the printable area one line
before from the current location. Hence, the line generated by the third statement is replaced
by the output of the fourth statement.
The programs illustrated below use printf() and scanf() statements.
4.11 Write a program to print the third power of 2 using pow() function. Assume the floating-
point numbers.
#include <math.h>
void main()
{
double x = 2.0, y = 3.0;
clrscr();
printf(“%lf raised to %lf is %lf\n”, x, y, pow(x, y));
}
OUTPUT:
2.000000 raised to 3.000000 is 8.000000
Explanation:
In the above program, two variables x and y are declared and initialized. In the printf()
statement using pow() function expression x^y is calculated and displayed.
4.12 Write a program to print the third power of 10 using pow10() function. Assume the floating-
point numbers.
#include <math.h>
void main
{
int p = 3;
OUTPUT:
Ten raised to 3.000000 is 1000.000000
Explanation:
In the above program, power of 10 is calculated. Here, p is declared as an integer data type. The
value returned by this function is of double data type. Hence, conversion symbol %lf is used.
4.13 Write a program to detect an error while inputting a data. Use return value of scanf()
statement.
void main()
{
int a,b,c,v;
clrscr();
printf(“Enter value of ‘A’,‘B’ & ‘C’ : ”);
v=scanf(“%d %d %d”,&a,&b,&c);
(v<3 ? printf(“\n Error In Inputting.”) : printf(“\n Values
Successfully read.”));
}
OUTPUT:
Enter value of ‘A’,‘B’ & ‘C’ : 1 2 3
Value Successfully read.
Enter value of ‘A’,‘B’ & ‘C’ : 1 J 2
Error In Inputting.
Explanation:
In the above program, the printf() statement returns values equal to the number of vari-
ables correctly read. The conditional statement checks the value of variable ‘v’ and prints
the respective messages.
4.14 Write a program to find the length of the string using printf() function.
void main()
{
char nm[20];
int l;
clrscr();
printf(“Enter String :”);
scanf(“%s”,nm):
l=printf(nm);
printf(“\nLength = %d”,l);
}
OUTPUT:
Enter String : HELLO
Length = 5
Explanation:
The printf() function returns the length of the string entered. In the above program the
string entered is ‘HELLO’. Length of the string is 5, which is stored in variable ‘l’.
4.15 Write a program to perform the addition of two numbers.
void main()
{
int a,b,c;
printf(“\n ENTER TWO VALUES\n”);
scanf(“\n %d %d”, &a, &b);
c=a+b;
printf(“\n Sum is=%d”,c);
}
OUTPUT:
ENTER TWO VALUES 5 8
Sum is = 13
Explanation:
In the above program, variables a, b and c are declared. Values of a and b are read through
the keyboard using scanf() statement. The addition of variables a and b is performed and
assigned to variable c.
4.16 Write a program to find the square of the given number.
void main()
{
int a,c;
printf(“\n ENTER ANY NUMBER\n”);
scanf(“\n %d”, &a);
c=a*a;
printf(“\n SQUARE OF GIVEN NUMBER = %d”,c);
}
OUTPUT:
ENTER ANY NUMBER 5
SQUARE OF GIVEN NUMBER 25
Explanation:
The above program is same as the previous one. Only difference is that instead of addition,
the square of a is calculated.
4.17 Write a program to input a single character and display it.
void main()
{
char ch;
clrscr();
printf(“Enter any character :”);
scanf(“%c”,&ch);
printf(“\n Your Entered Character is : %c”,ch);
}
OUTPUT:
Enter any character: C
Your Entered Character is: C
Explanation:
In the above program, a character is entered and stored in variable ch. The printf() statement
displays the entered character.
4.18 Write a program to swap the values of two variables without the use third variable.
void main()
{
int a=7,b=4;
clrscr();
printf(“\n A= %d B= %d”,a,b);
a=a+b;
b=a-b;
a=a-b;
printf(“Now A= %d B= %d”,a,b);
}
OUTPUT:
A=7 B=4
Now A= 4 B=7
Explanation:
In the above program, no third variable is used as a mediator for swapping the values. The
below given steps illustrate the working of the program.
(i) In the first statement, variable ‘a’ contains the sum of a+b, i.e. 11.
(ii) In the second statement, variable ‘b’ contains a-b, i.e. 11−4 =7.
(iii) In the third statement, variable ‘a’ contains a-b, i.e. 11−7=4.
Thus, the two values are interchanged.
4.4 Unformatted Functions
C has three types of I/O functions.
(i) Character I/O
(ii) String I/O
(iii) File I/O
1.
getchar() -
This function reads a character-type data from standard input. It reads one character at a time
till the user presses the enter key. The syntax of the getchar() is as follows:
Variable name=getchar();
Example:
char c;
c=getchar();
A program is supported for the following getchar() function.
4.19 Write a program to accept characters through keyboard using getchar() function.
void main()
{
char c;
clrscr();
printf(“\nEnter a char :”);
c=getchar();
printf(“a=%c”,c);
}
OUTPUT:
Enter a char :g
a=g
Explanation:
In the above program, a character variable c is declared. The getchar() reads a character
through the keyboard. The same is displayed by the printf() statement.
2.
putchar() -
This function prints one character on the screen at a time, read by the standard input.
The syntax is as follows:
putchar(variable name);
Example:
char c=‘C’;
putchar (c);
A program is provided on putchar().
void main()
{
char c=‘C’;
clrscr();
putchar(c);
}
OUTPUT:
C
Explanation:
In this program, the character variable c assigns a char ‘C’; the same is displayed by the
putchar() statement. The argument c is used with the putchar() statement.
3.
getch() & getche()
These functions read any alphanumeric character from the standard input device. The char-
acter entered is not displayed by the gectch() function.
Syntax of getche() is as follows:
getche();
4.21 Write a program to show the effect of getche() and getch().
void main()
{
clrscr();
printf(“Enter any two alphabetic”);
getche();
getch();
}
OUTPUT:
Enter any two alphabetic A
Explanation:
In the above program, even though two characters are entered, the user can see only one
character on the screen. The second character is accepted but not displayed on the console.
The getche() accepts and displays the character whereas getch() accepts but does not
display the character.
4.
putch() :
This function prints any alphanumeric character taken by the standard input device.
4.22 Write a program to read and display the character using getch() and putch().
void main()
{
char ch;
clrscr();
printf(“Press any key to continue”);
ch=getch();
printf(“\n You Pressed :”);
putch(ch);
}
OUTPUT:
Press any key to continue
You Pressed: 9
Explanation:
The function getch() reads a keystroke and assigns to the variable ch. The putch() dis-
plays the character pressed.
(ii) String I/O
1.
gets () :
This function is used for accepting any string through stdin (keyboard) until enter key is
pressed. The header file stdio.h is needed for implementing the above function. Format of
gets() is as follows:
char str[length of string in number];
gets(str)
A program is given on gets().
4.23 Write a program to accept string through the keyboard using the gets() function.
void main()
{
char ch[30];
clrscr();
printf(“Enter the String :”);
gets(ch);
printf(“\n Entered String : %s”, ch);
}
OUTPUT:
Enter the String : USE OF GETS()
Entered String : USE OF GETS()
Explanation:
In the above program, gets() reads string through the keyboard and stores it in character
array ch[30]. The printf() function displays the string on the console.
2.
puts() :
void main()
{
char ch[30];
clrscr();
printf(“Enter the String :”);
gets(ch);
puts(“Entered String :”);
puts(ch);
}
OUTPUT:
Enter the String: puts is in use.
Entered String:
puts is in use.
Explanation:
This program is the same as the previous one. Here, to display the string puts() function
is used.
3.
cgets() :
This function reads string from the console. The syntax is as follows.
Syntax:
cgets(char *st);
It requires character pointer as an argument. The string begins from st[2].
4.
cputs() :
Syntax:
cputs(char *st);
4.25 Write a program to read string using cgets() and display it using cputs().
void main()
{
static char *t;
clrscr();
printf(“\n Enter Text Here :”);
cgets(t);
t+=2;
printf(“\n Your Entered Text :”);
cputs(t);
getche();
}
OUTPUT:
Enter Text Here: How are you?
Your Entered Text: How are you?
Explanation:
In this example character pointer ‘t’ is declared. The cgets() function reads string
through the keyboard and the cputs() function displays the string on the console.
1.
clrscr()
This function is used to clear the screen. It clears previous output from the screen and dis-
plays the output of the current program from the first line of the screen. It is defined in
conio.h header file. The syntax is as follows.
Syntax:
clrscr();
2.
exit()
3.
sleep()
This function pauses the execution of the program for a given number of seconds. The number
of seconds is to be enclosed between parentheses. It is defined in dos.h header file. The syn-
tax is as follows.
Syntax:
sleep(1);
An example on sleep() is given below.
4.26 Write a program to show the effect of the sleep() function.
void main()
{
static char t[10];
clrscr();
printf(“\n Enter Text Here :”);
gets(t);
printf(“\n Your Entered Text :”);
sleep(5);
puts(t);
getche();
}
OUTPUT:
Enter Text Here: ashok
Your Entered Text: ashok
Explanation:
The explanation is straightforward and self-explanatory. See the effect of sleep(5). The
display appears after taking a pause.
3.
system ()
This function is helpful in executing different DOS commands. It returns 0 on success and –1 on
failure. The syntax is as follows.
Syntax:
system (“dir”);
The command should be enclosed within double quotation marks. After we run this command using
C, directory will be displayed. Programmer can verify this command.
(iv) Provide a gap between two lines so that the text should be readable.
(v) Alert the user about what to do and what not to do.
(vi) Use formatted inputs and outputs for precisely inputting the data and outputting results.
(vii) It is recommended to use escape sequence characters such as \t, \b, \n.
summary
This chapter dealt with formatted functions such as printf() and scanf() statements. The unfor-
matted functions such as putchar(), getche(), gets() have been illustrated with suitable
examples. The different data types and conversion symbols used in the C programs have also been
elaborated. The special symbols such as escape sequences together with their applications are also
discussed. A few of the functions which are commonly used in the programs such as clrscr(),
exit() are described in this chapter. Input and output functions together with examples are narrated
with programming example. At last, the main points for the understanding of programs are given to
the readers so that they can follow them.
eXercIses
I Fill in the blanks:
1. _______functions provide the conversion symbol (c) gets()
to identify the data type. (d) pow()
(a) Formatted 4. The ________statement reads all types of data
(b) Unformatted values.
(c) Library
(d) User defined (a) scanf()
(b) printf()
2. ______functions does not convert data. (c) puts()
(a) Formatted (d) abs()
(b) Unformatted
5. _______function reads one character type data at a
(c) Library
time till the user presses the enter key.
(d) User defined
(a) getchar()
3. The function prints all types of data values on to
(b) puts()
the console_____
(c) accept()
(a) printf() (d) floor()
(b) scanf()
II True or false:
1. Formatted functions require format string to for- 4. Formatted functions return values.
mat the data.
5. The function gets() is defined in
2. The function gets() is an unformatted <string.h>.
function.
6. Any signed data type can have negative as well as
3. The ‘\n escape sequence inserts a tab. positive values.
7. The functions cgets() and cputs() work 11. The ‘\a’ escape sequence is for alert bell.
with character pointer as argument.
12. The format string %g is used for float type.
8. While inputting values through scanf(), & is
required before a variable name. 13. The %s is used to format the string.
9. The getche() is used to read data character by 14. The format string %P is used to display hexadeci-
character. mal in lowercase.
10. The char requires one byte space in the memory. 15. The %lf is used for long integer
III Select the appropriate options from the choices given in the questions:
1. What will be the output of the following pro- 5. What is the ASCII range for A to Z letters?
gram?
(a) 65 to 90
void main() (b) 48 to 57
{ (c) 97 to 122
printf(“\n %d%d%d%d”,‘A’, (d) None of the above
‘B’,‘C’,‘D’);
} 6. The escape sequence ‘\t’ is a
2. What will be the values of a and b after the ex- 7. What would be the value of x on execution of the
ecution of the following program? program?
void main() void main()
{ {
int a,b; float x=2.3;
a=65*66; clrscr();
b=‘A’ * ‘B’; x+=.2;
clrscr(); printf(“%g”,x);
printf(“a=%d b=%d”,a,b); }
}
(a) 2.5
(a) a=4290 b=4290 (b) 4.3
(b) a=4290 b=AB (c) 4
(c) a=4290 b=0 (d) None of the above
(d) None of the above
8. What will be the output of the following pro-
3. What function is appropriate for accepting a string? gram?
(a) gets() void main()
(b) getch() {
(c) getche() system(“”);
(d) scanf() }
4. What is the ASCII range for 0 to 9 digits? (a) control goes to the DOS prompt
(a) 48 to 57 (b) syntax error
(b) 65 to 90 (c) bad command or file name
(c) 97 to 122 (d) None of the above
(d) None of the above
1. Write a program to input the rainfall of 8. Write a program to enter the name of this book
three consecutive days in CMS and find its and display it.
average?
9. Write a program to store and interchange two
2. Find the simple interest? Inputs are principal float numbers in variables a and b.
amount, period in year and rate of interest.
10. Write a program to enter text with gets() and
3. Write a program to find the total number of min- display it using printf() statement. Also find
utes of 12 hours? the length of the text.
4. Find the area and perimeter of (a) square and 11. Write a program to ensure that the subtraction of
(b) rectangle. Input the side(s) through the any two-digit number and its reverse is always the
keyboard? multiple of nine. For example, entered number is
5. Accept any three numbers and find their squares 54 and its reverse is 45. The difference between
and cubes. them is 9.
6. The speed of a van is 80 km/hour. Find the num- 12. Write a program to convert kilograms into
ber of hours required for covering a distance of grams.
500 km? Write a program in this regard.
13. Write a program to find the total amount when
7. Write a program to convert inches into there are five notes of Rs. 100, three notes of
centimetres. Rs. 50 and 20 notes of Rs. 20.
14. Write a program to enter the temperature in 15. Write a program to display the list of c
Fahrenheit and convert it to Celsius. Formula program files and directories. Use sys-
to be used is tc= ((tf-32)*5)/9 where tem() function to execute DOS commands.
tc and tf are temperatures in Celsius and Fahr-
enheit, respectively.
ansWers
I Fill in the blanks:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. a 2. b 3. a 4. a 5. a
II True or false:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. T 2. T 3. F 4. T 5. F
6. T 7. T 8. T 9. T 10. T
11. T 12. T 13. T 14. F 15. F
III Select the appropriate options from the choices given in the questions:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. a 2. a 3. a 4. a 5. a
6. a 7. a 8. a 9. a 10. a
11. a 12. a 13. b
5 Decision
Statements
Chapter Outline
5.1 Introduction
5.2 The if Statement
5.3 The if–else Statement
5.4 Nested if–else Statements
5.5 The if-else-if Ladder Statement
5.6 The break Statement
5.7 The continue Statement
5.8 The goto Statement
5.9 The switch Statement
5.10 Nested switch case
5.11 The switch case and nested ifs
5.1 Introduction
A program is nothing but the execution of one or more instructions sequentially in the order in
which they come into sight. This process is analogous to reading the text and figures that appear
on the page of a notebook. In the monolithic program, the instructions are executed sequentially
in the order in which they appear in the program. Quite often, it is desirable in a program to alter
the sequence of the statements depending upon certain circumstances. In real time applications,
there are a number of situations where one has to change the order of the execution of statements
based on the conditions.
Decision-making statements in a programming language help the programmer to transfer
the control from one part to other parts of the program. Thus, these decision-making statements
facilitate the programmer in determining the flow of control. This involves a decision-making
condition to see whether a particular condition is satisfied or not. On the basis of real time
applications it is essential:
(i) to alter the flow of a program.
(ii) to test the logical conditions.
(iii) to control the flow of execution as per the selection.
These conditions can be placed in the program using decision-making statements. C language sup-
ports the control statements as listed below:
(i) The if statement
(ii) The if–else statement
(iii) The if–else–if ladder statement
(iv) The switch case statement
(v) The goto unconditional jump
(vi) The loop statement
Besides, the C also supports other control statements such as continue, break.
The decision-making statement checks the given condition and then executes its sub-block.
The decision statement decides which statement to execute after the success or failure of a given
condition.
The conditional statements use relational operators, which have been explained in Chapter 3. The
relational operators are useful for comparing the two values. They can be used to check whether they
are equal to each other, unequal or one is smaller/greater than the other.
The reader or the programmer is supposed to understand the concepts as cited above. Following
points are expected to be known to the programmer related to the decision-making statements.
Sequential execution: The statements in the program are executed one after another in a
sequential manner. This is called the sequential execution.
Transfer of control: The C statements such as if, goto, break, continue, switch
allow a program to transfer the control at different places in the program. This is accomplished by
skipping one or more statements appearing in a sequential flow. This jumping of control is called the
transfer of control.
During 1960s, programmers faced various difficulties in the program in which goto statement
was used which allows a programmer to transfer the control anywhere in the program. Bohm and
Jacopini reported that the programmer should not use the goto statement in their programs. Both
Bohm and Jacopini demonstrated that all the programs could be written by using only three control
structures, i.e. sequence structure, selection structure and repetition structure by eliminating the goto
statement.
5.2 The if Statement
void main ()
C uses the keyword if to execute a set of command
lines or one command line when the logical condition {
is true. It has only one option. The sets of command TRUE FALSE
lines are executed only when the logical condition is if (expression)
true (see Figure 5.1). {
statement1;
statement2;
}
Syntax for the simplest if statement :-
if (condition) /* no semi-colon */ statement3;
}
statement;
The if statement contains an expression which is evaluated. If the expression is true it returns 1,
otherwise 0. The statement is executed when the condition is true. In case the condition is false,
the compiler skips the lines within the if block. The condition is always enclosed within a pair of
parentheses. The conditional statements should not be terminated with semi-colons (;). The statements
following the if statement are normally enclosed within curly braces. The curly braces indicate the
scope of the if statement. The default scope is one statement. But it is good practice to use curly
braces even if a single statement is used following the if condition.
Given below are simple programs that demonstrate the use of the if statement.
5.1 Write a program to check whether the entered number is less than 10. If yes, display
the same.
void main()
{
int v;
clrscr();
printf(“Enter the number :”);
scanf(“%d”, &v);
if(v<10)
printf(“\nNumber entered is less than 10”);
sleep(2); /* process halts for given value in seconds */
}
OUTPUT:
Enter the number : 9
Number entered is less than 10
Explanation:
In the above program, the user can enter the number. The entered number is checked with the
if statement. If it is less than 10, a message ‘Number entered is less than 10’
is displayed. For the sake of understanding, Figure 5.2 is given for the above program.
START
Input Value of v
False True
is v<10?
Print Message
STOP
5.2 Write a program to check whether the candidate’s age is greater than 17 or not. If yes, display
message ‘Eligible for Voting’.
void main()
{
int age;
clrscr();
printf(“\n Enter age in the years :”);
scanf(“%d”,&age);
if(age>17)
printf(“\n Eligible for Voting.”);
getch();
}
OUTPUT:
Enter age in the years : 20
Eligible for Voting.
Explanation:
In the above program, age is entered through the keyboard. If the age is greater than 17 years,
a message will be displayed as shown at the output.
5.3 Write a program using curly braces in the if block. Enter only the three numbers and calcu-
late their sum and multiplication.
void main()
{
int a,b,c,x;
clrscr();
printf(“\nEnter Three Numbers:”);
x=scanf(“%d %d %d”,&a,&b,&c);
if(x==3)
{
printf(“\n Addition : %d”,a+b+c);
printf(“\n Multiplication : %d”, a*b*c);
}
}
OUTPUT:
Enter Three Numbers: 1 2 4
Addition : 7
Multiplication : 8
After second time execution
Enter Three Numbers: 5 v 8
Explanation:
The variable ‘x’ contains the number of values correctly inputted by the user. If the value of
‘x’ is 3, the addition and multiplication operations are performed as per the first example
in the output. In the second example, the numbers are not correctly entered. Hence, the if
condition is false and no operation is performed. Here, the statements following the if con-
dition is enclosed within curly braces.
Figure 5.3 The if–else statements Figure 5.4 The if–else statement
OR
# include <math.h>
void main()
{
int b,a,c;
float x1,x2;
clrscr();
printf(“\n Enter Values for a,b,c :”);
scanf(“%d %d %d”, &a,&b,&c);
if(b*b>4*a*c)
{
x1=-b+sqrt(b*b-4*a*c)/2*a;
x2=-b-sqrt(b*b-4*a*c)/2*a;
printf(“\n x1=%f x2=%f”,x1,x2);
}
else
printf(“\n Roots are Imaginary”);
getch();
}
OUTPUT:
Enter Values for a,b,c : 5 1 5
Roots are Imaginary
Explanation:
The user can enter the values of a, b and c in the above program. The terms b2 and 4 a c are
evaluated. The if condition checks whether b2 is greater than 4 a c. If true, x1 and x2 are
evaluated and printed; otherwise message displayed will be ‘Roots are Imaginary’.
5.5 Write a program to calculate the square of those numbers only whose least significant
digit is 5.
void main()
{
int s,d;
clrscr();
printf(“\n Enter a Number :”);
scanf(“%d”,&s);
d=s%10;
if(d==5)
{
s=s/10;
printf(“\n Square = %d%d”,s*s++,d*d);
}
else
printf(“\n Invalid Number”);
}
OUTPUT:
Enter a Number : 25
Square = 625
Explanation:
In the above program, a number whose square is to be computed is entered. With the modular
division, operation the last digit is separated to confirm whether it is 5 or not. If yes, the body
of the if loop is executed where 10 divides the entered number and a quotient is obtained.
The quotient and its consecutive number are multiplied and displayed. Followed by this, a
square of 5 is calculated and displayed. Care is taken in the printf() statement to display
the two results: (i) multiplication of quotient and its consecutive number and (ii) square of 5
without space. Thus, the square of a number is displayed.
5.6 Write a program to calculate the salary of a medical representative based on the sales. Bonus
and incentive to be offered to him will be based on total sales. If the sale exceeds or equals to
Rs.1,00,000, follow the particulars of Table 1, otherwise follow Table 2.
1. TABLE 2. TABLE
Basic=Rs. 3000. Basic=Rs. 3000.
Hra=20% of basic. Hra=20% of basic.
Da=110% of basic. Da=110% of basic.
Conveyance=Rs.500. Conveyance=Rs.500.
Incentive=10% of sales. Incentive=5% of sales.
Bonus=Rs. 500. Bonus=Rs. 200.
void main()
{
float bs,hra,da,cv,incentive,bonus,sale,ts;
clrscr();
printf(“\n Enter Total Sales in Rs.:”);
scanf(“%f”, &sale);
if(sale>=100000)
{
bs=3000;
hra=20 * bs/100;
da=110 * bs/100;
cv=500;
incentive=sale*10/100;
bonus=500;
}
else
{
bs=3000;
hra=20 * bs/100;
da=110 * bs/100;
cv=500;
incentive=sale*5/100;
bonus=200;
}
ts=bs+hra+da+cv+incentive+bonus;
printf(“\nTotal Sales : %.2f”,sale);
printf(“\nBasic Salary : %.2f”’,bs)
printf(“\nHra : %.2f”,hra);
printf(“\nDa : %.2f”,da);
printf(“\nConveyance : %.2f”,cv);
printf(“\nIncentive : %.2f”,incentive);
printf(“\nBonus : %.2f”,bonus);
printf(“\nGross Salary : %.2f”,ts);
getch();
}
OUTPUT:
Enter Total Sales in Rs. 100000
Total Sales: 100000.00
Basic Salary: 3000.00
Hra: 600.00
Da: 3300.00
Conveyance: 500.00
Incentive: 10000.00
Bonus: 500.00
Gross Salary: 17900.00
Explanation:
This program calculates the salary of a medical representative depending on sales. The basic
salary is the same but other allowances and incentives change, depending on the sales. If the
sale is more than Rs. 1,00,000, the rate of allowances and incentive is as per Table 1 otherwise
it is as per Table 2. The if condition checks the given figure of sales. If sale is more than
Rs. 1,00,000, the first bock following the if statement is executed otherwise the else block
is executed. In both the blocks, simple arithmetic operations are performed to calculate the
allowances and total salary.
Is 1st
False True
Condition
Satisfied?
Is 3rd Is
False True
Condition False True
2nd Condition
Satisfied? Satisfied?
Next Statement
if(condition)
{
/*Inside first if block*/
if(condition)
{
statement 1; /*if block*/
statement 2;
}
else
{
statement 3; /*else block*/
statement 4;
}
}
else
{
/*Inside else block*/
if(condition)
{
statement 5; /*if block*/
statement 6;
}
else
{
statement 7; /*else block*/
statement 8;
}
}
From the above block, following rules can be described for applying nested if-else-if
statements.
1. Nested if-else can be chained with one another.
2. If the condition is true control passes to the block following first if. In that case, we may
have one more if statement whose condition is again checked. This process continues till
there is no if statement in the last if block.
3. If the condition is false control passes to else block. In that case, we may have one more if
statement whose condition is again checked. This process continues till there is no if state-
ment in the last else block.
The statement is named as if-else-if ladder because it forms a ladder like structure as shown
in Figure 5.6.
From Previous Statement
To Next Statement
if(condition)
{
statement 1; /*if block*/
statement 2;
}
else if(condition)
{
statement 3; /*second if block*/
statement 4;
}
else if(condition)
{
statement 5; /*third if block*/
statement 6;
}
else
{
statement 7; /*else block*/
statement 8;
}
From the above block, following rules can be described for applying nested if-else-if
statements:
1. Nested if-else can be chained with one another.
2. If the first if condition is false control passes to else-if block where condition is again
checked with the next if statement. This process continues till there is no if statement in
the last else block.
3. If one of the if statements satisfies the condition, other nested else-if statement will not
be executed.
Given below programs are described on the bases on nested if-else and if-else-if lad-
der statements.
5.7 Write a program to calculate electricity bill. Read the starting and ending meter reading.
The charges are as follows.
void main()
{
int initial,final,consumed;
float total;
clrscr();
printf(“\n Initial & Final Readings :”);
scanf(“%d %d”, &initial, &final);
consumed = final-initial;
if(consumed>=200 && consumed<=500)
total=consumed * 3.50;
else if(consumed>=100 && consumed<=199)
total= consumed * 2.50;
else if(consumed<100)
total=consumed*1.50;
printf(“Total bill for %d unit is %f”,consumed,total);
getche();
}
OUTPUT:
Initial & Final Readings : 800 850
Total bill for 50 unit is 75.000000
Explanation:
Initial and final readings are entered through the keyboard. Their difference is nothing but the
total energy consumed. As per the table given in the example, rates are applied and total bill
based on consumption of energy is calculated.
5.8 Write a program to find the maximum number out of six numbers invoked though the
keyboard.
void main()
{
int a,b,c,d,e,f;
clrscr();
printf(“Enter 1st number:”);
scanf(“\n%d”,&a);
printf(“Enter 2nd number:”);
scanf(“\n%d”,&b);
printf(“Enter 3 rd number:”);
scanf(“\n%d”,&c);
printf(“Enter 4th number:”);
scanf(“\n%d”,&d);
printf(“Enter 5th number:”);
scanf(“\n%d”,&e);
printf(“Enter 6th number:”);
scanf(“\n%d”,&f);
if((a>b)&&(a>c)&&(a>d)&&(a>e)&&(a>f))
printf(“Maximum out of six Numbers is : %d”,a);
else if((b>c)&&(b>d)&&(b>e)&&(b>f))
printf(“Maximum out of six Numbers is : %d”,b);
else if((c>d)&&(c>e)&&(c>f))
printf(“Maximum out of six Numbers is :%d”,c);
else if((d>e)&&(d>f))
printf(“Maximum out of six Numbers is : %d”,d);
else if(e>f)
printf(“Maximum out of six Numbers is : %d”,e);
else
printf(“Maximum out of six Numbers is : %d”,f);
getch();
}
OUTPUT:
Enter 1st number:23
Enter 2nd number:45
Enter 3rd number:67
Enter 4th number:89
Enter 5th number:80
Enter 6th number:90
Maximum out of six Numbers is : 90
Explanation:
Six numbers are entered through the keyboard. All the values of variables are compared
with one another using && (and) in nested if–else–if statements. When one of the if
statements satisfies the condition that if block is executed which prints the largest number
otherwise the control passes to another if–else–if statement.
5.9 Write a program to find the largest number out of three numbers. Read the numbers through
the keyboard.
void main()
{
int x,y,z;
clrscr();
printf(“\nEnter Three Numbers x, y, z :”);
scanf(“%d %d %d”, &x,&y,&z);
printf(“\nLargest out of Three Numbers is :”);
if(x>y)
{
if(x>z)
printf(“x=%d\n”,x);
else
printf(“z=%d\n”,z);
}
else
{
if(z>y)
printf(“z=%d\n”,z);
else
printf(“y=%d\n”,y);
}
}
OUTPUT:
Enter Three Numbers x, y, z : 10 20 30
Largest out of Three Numbers is :z=30
Explanation:
This is also an example of the nested ifs. When the if statement satisfies the condition,
control passes to another if statement block. Three numbers are entered through keyboard.
The first if statement compares the first number with the second number. If the condition is
a true, the block followed by first if statement executes. Inside the block, the if statement
checks whether the first number is larger than the third number. If yes, then the largest number
is the first one and the same is displayed. Else the third number is the largest and the same is
printed. In case the first if statement fails to satisfy the condition, the else block with nested
if would be executed. The third number is compared with the second number. If it is true the
third number is the largest otherwise the second number is the largest.
5.10 Write a program to find the smallest out of the three numbers.
void main()
{
int a,b,c,smallest;
clrscr();
printf(“\n Enter Three Numbers :”);
OUTPUT:
Enter Three Numbers : 1 5 8
The smallest of 1 5 8 is 1
Explanation:
The logic in the above program is the same as the last one. Instead of > (greater than) < (less
than) condition is used.
5.11 Write a program to calculate the gross salary for the conditions given below.
void main()
{
float bs,hra,da,cv,ts;
clrscr();
printf(“\n Enter Basic Salary :”);
scanf(“%f”,&bs);
if(bs=>5000)
{
hra=20 * bs/100;
da= 110 * bs/100;
cv=500;
}
else
if(bs=>3000 && bs<5000)
{
hra=15*bs/100;
da=100*bs/100;
cv=400;
}
else
{
if(bs<3000)
hra=10*bs/100;
da= 90*bs/100;
cv=300;
}
ts=bs+hra+da+cv;
printf(“\nBasic Salary : %5.2f”,bs);
printf(“\nHra : %5.2f”,hra);
printf(“\nDa : %5.2f”,da);
printf(“\nConveyance : %5.2f”,cv);
printf(“\nGross Salary : %5.2f”,ts);
getch();
}
OUTPUT:
Enter Basic Salary: 5400
Basic Salary: 5400
Hra: 1080
Da: 5940
Conveyance: 500
Gross Salary:12920
Explanation:
In the above program, the basic salary of an employee is entered through the keyboard.
This entered figure is checked with different conditions as cited in the problem. The if–
else conditions are used and on the basis of the conditions gross salary is calculated and
displayed.
5.12 Calculate the total interest based on the following.
void main()
{
float princ,nyrs,rate,interest;
clrscr();
printf(“\n Enter Loan & No. of years :-”);
scanf(“%f %f”, &princ, &nyrs);
if(princ>=10000)
rate=20;
else
if(princ>=8000 && princ<=9999)
rate=18;
else
if(princ<8000)
rate=16;
interest = princ * nyrs * rate/100;
printf(“\nYears : %6.2f”,nyrs);
printf(“\nLoan : %6.2f”,princ);
printf(“\nRate : %6.2f”,rate);
printf(“\nInterest : %6.2f”,interest);
getche();
}
OUTPUT:
Enter Loan & No. of years :- 5000 3
Loan : 5000.00
Years : 3.00
Rate : 16.00
Interest : 2640.00
Explanation:
In the above program, the loan and the number of years are entered through the keyboard.
The entered principal amount is checked with the if statement. Based on the principal
amount, the rate of interest is charged. The interest is calculated by considering different
factors such as loan amount, the number of years and the rate of interest as per the table.
5.13 Write a program to find the average of six subjects and display the results as follows.
AVERAGE RESULT
>=35 & <50 Third Division
>=50 & <60 Second Division
>=60 & <75 First Division
>=75 & <=100 Distinction
If marks in any subject less than 35 Fail
void main()
{
int a,b,c,d,e,f;
float sum=0;
float avg;
clrscr();
printf(“\nEnter Marks:\n”);
printf(“P C B M E H\n”);
scanf(“%d %d %d %d %d %d”,&a,&b,&c,&d,&e,&f);
if(a<35 || b<35 || c<35 || d<35 || e<35 || f<35)
{
printf(“\nResult: Fail”);
exit();
}
sum=a + b + c + d + e + f;
avg=sum/6;
printf(“Total : %g \nAverage : %g”, sum,avg);
if(avg>=35 && avg<50)
printf(“\n Result: Third Division”);
else
if(avg>=50 && avg <60)
printf(“\n Result: Second Division”);
else
if(avg>=60 && avg<75)
printf(“\n Result: First Division”);
else
if(avg>75 && avg <=100)
printf(“\nResult : Distinction”);
getche();
}
Enter Marks:
P C B M E H
56 57 56 89 78 45
Total : 381
Average : 63.5
Result: First Division
Explanation:
In the above program, marks of six subjects are entered through the keyboard. Their sum
and average are calculated. The first if statement checks the condition whether the marks
in individual subjects are less than 35. If so, message displayed will be ‘Result: Fail’
and the program terminates. The logical OR (||) is used here.
The average marks obtained are checked with different conditions. The if-else blocks are
used. Based on the conditions the statements are executed.
# include <stdlib.h>
void main()
{
int x;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”,&x);
if(x%2==0)
goto even;
else
goto odd;
even :
printf(“\n %d is Even Number.”,x);
return;
odd:
printf(“\n %d is Odd Number.”,x);
}
OUTPUT:
Enter a Number : 5
5 is Odd Number.
Explanation:
In the above program, a number is entered. The number is checked for even or odd with mod-
ules division operator. When the number is even, the goto statement transfers the control to
the label even. Similarly, when the number is odd the goto statement transfers the control
to the label odd and respective message will be displayed.
5.15 Write a program to calculate the telephone bill. Transfer controls at different places
according to the number of calls and calculate the total charges. Follow rates as per
given in the table.
void main()
{
int nc;
clrscr();
printf(“\nEnter Number of Calls :”);
scanf(“%d”,&nc);
if(nc<100)
goto free;
else if(nc>99 && nc<200)
goto charge1;
else if(nc>199 && nc<300)
goto charge2;
else
goto charge3;
free :
printf(“\n No charges.”);
return;
charge1:
printf(“\n Total Charges : %d Rs.”,nc*1);
return;
charge2:
printf(“\n Total Charges : %d Rs.”,nc*2);
return;
charge3:
printf(“\n Total Charges : %d Rs.”,nc*3);
}
OUTPUT:
Enter Number of Calls : 500
Total Charges: 1500 Rs
Explanation:
The execution process of the above program is the same as that of the previous one. The
difference is that in this program control is transferred to various labels.
5.16 Write a program to check if the entered year is a leap year or not. Use the goto
statement.
#include <stdio.h>
#include <conio.h>
int main()
{
int year;
clrscr();
printf(“\nEnter Year :”);
scanf(“%d”,&year);
if(year%4==0 && year%100!=0 || year%400==0)
goto leap;
else
goto noleap;
leap:
printf(“%d is a leap year.”,year);
return 0;
noleap:
printf(“%d is not leap year.”,year);
getch();
return 0;
}
OUTPUT:
Enter Year : 2012
2012 is a leap year.
Explanation:
The entered year is divided using the modulus division operator 400. The condition is satis-
fied hence the year 2012 is the leap year.
switch(variable or expression)
{
case constant A :
statement;
break;
case constant B :
statement;
break;
default :
statement ;
}
void main()
{
int ch;
clrscr();
printf(“\n[1] .........”);
printf(“\n[2] _________”);
printf(“\n[3] *********”);
printf(“\n[4] ==========”);
printf(“\n[5] EXIT”);
printf(“\n\n ENTER YOUR CHOICE :”);
scanf(“%d”, &ch);
switch(ch)
{
case 1 :
printf(“\n ............................................”);
break;
case 2 :
printf(“\n ___________________________________________”);
break;
case 3 :
printf(“\n ********************************************”);
break;
case 4 :
printf(“\n ============================================”);
break;
case 5 :
printf(“\n Terminated by choice”);
exit();
break;
default :
printf(“\n Invalid Choice”);
}
getch();
}
OUTPUT:
[1] .........
[2] _________
[3] *********
[4] ==========
[5] EXIT
ENTER YOUR CHOICE : 1
...........................
Explanation:
In this program, a menu appears with five options and it requests the users to enter their
choice. The choice entered by the user is then passed to switch statement. In the switch
statement, the value is checked with all the case constants. The matched case statement is
executed in which the line is printed of the user’s choice. If the user enters a non-listed value,
then no match occurs and default is executed. The default warns the user with a mes-
sage ‘Invalid Choice’.
5.18 Write a program to calculate (1) Addition, (2) Subtraction, (3) Multiplication, (4) Division,
(5) Remainder calculation, (6) Larger out of two numbers by using switch statements.
void main()
{
int a,b,c,ch;
clrscr();
printf(“\t =================”);
printf(“\n\t MENU”);
printf(“\n\t =================”);
printf(“\n\t[1] ADDITION”);
printf(“\n\t[2] SUBTRACTION”);
printf(“\n\t[3] MULTIPLICATION”);
printf(“\n\t[4] DIVISION”);
printf(“\n\t[5] REMAINDER”);
printf(“\n\t[6] LARGER OUT OF TWO”);
printf(“\n\t[0] EXIT”);
printf(“\n\t=================”);
printf(“\n\n\t ENTER YOUR CHOICE :”);
scanf(“%d”, &ch);
if(ch<=6 & ch>0)
{
printf(“Enter Two Numbers :”);
scanf(“%d %d”,&a,&b);
}
switch ( ch)
{
case 1 :
c=a+b;
printf(“\n Addtion : %d”,c);
break;
case 2 :
c=a-b;
printf(“\n Subtraction : %d”,c);
break;
case 3 :
c=a*b;
printf(“\n Multiplication : %d”,c);
break;
case 4 :
c=a/b;
printf(“\n Division : %d”,c);
break;
case 5 :
c=a%b;
printf(“\n Remainder : %d”,c);
break;
case 6 :
if(a>b)
printf(“\n\t %d (a) is larger than %d (b).”,a,b);
else
if(b>a)
printf(“\n\t %d (b) is larger than %d (a).”,b,a);
else
printf(“\n\t %d (a) & %d (b) are same.”,a,b);
break;
case 0 :
printf(“\n Terminated by choice”);
exit();
break;
default :
printf(“\n Invalid Choice”);
}
getch();
}
OUTPUT:
MENU
=================
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[0] EXIT
=================
ENTER YOUR CHOICE : 6
Enter Two Numbers : 8 9
9 (b) is larger than 8 (a).
Explanation:
In this program also, a menu appears with different arithmetic operations. It requests the user
to enter the required choice number. The choice entered by the user is checked with the if
statement. If it is in between 1 and 6 the if block is executed which prompts the user to enter
two numbers. After this, the choice entered by the user is passed to the switch statement
and it performs relevant operations.
5.19 Write a program that converts number of years into (1) minutes, (2) hours, (3) days, (4)
months and (5) seconds using switch statements.
void main()
{
long ch,min,hrs,ds,mon,yrs,se;
clrscr();
printf(“\n[1] MINUTES”);
printf(“\n[2] HOURS”);
printf(“\n[3] DAYS”);
printf(“\n[4] MONTHS”);
printf(“\n[5] SECONDS”);
printf(“\n[0] EXIT”);
printf(“\n Enter Your Choice :”);
scanf(“%ld”, &ch);
if(ch>0 && ch<6 )
{
printf(“Enter Years :”);
scanf(“%ld”,&yrs);
}
mon=yrs*12;
ds=mon*30;
ds=ds+yrs*5;
hrs=ds*24;
min=hrs*60;
se=min*60;
switch(ch)
{
case 1 :
printf(“\n Minutes : %ld”,min);
break;
case 2 :
printf(“\n Hours : %ld”,hrs);
break;
case 3 :
printf(“\n Days : %ld”,ds);
break;
case 4 :
printf(“\n Months : %ld”,mon);
break;
case 5 :
printf(“\n Seconds: %ld”,se);
break;
case 0 :
printf(“\n Terminated by choice”);
exit();
break;
default :
printf(“\n Invalid Choice”);
}
getch();
}
OUTPUT:
[1] MINUTES
[2] HOURS
[3] DAYS
[4] MONTHS
[5] SECONDS
[0] EXIT
Enter Your Choice : 4
Enter Years : 2
Months : 24
Explanation:
In this program, the number of years is entered and according to the user’s choice switch
case structure performs the operation.
5.20 Write a program to perform the following operations:
1. Display any numbers or stars on the screen by using for loop.
2. Display the menu containing the following: (a) whole screen, (b) half screen, (c) the top three
lines and (d) the bottom three lines.
void main()
{
int i,c;
clrscr();
for (i=0;i<=700;i++)
printf(“%d”,i);
printf(“\n\n\t\tCLRAR SCREE MENU\n”);
printf(“\t\t1] Whole screen\n”);
printf(“\t\t2] Half Screen\n”);
printf(“\t\t3] Top 3 Lines \n”);
printf(“\t\t4] Bottom 3 Lines\n”);
printf(“\t\t5] Exit \n Enter Your Choice :”);
scanf(“%d”,&c);
switch(c)
{
case 1:
clrscr();
break;
case 2 :
for (i=0;i<=189;i++)
{
gotoxy(i,1);
printf(“\t”);
}
break;
case 3 :
for (i=1;i<=99;i++)
{
gotoxy(i,1);
printf(“\t”);
}
break;
case 4 :
for (i=1;i<120;i++)
{
gotoxy(i,21);
printf(“\t”);
}
default :
break;
}
getche();
}
Explanation:
In the above program, the for loop is used for displaying numbers on the screen. The screen
will be covered with numbers. The screen as a whole or part or top or bottom portion can
be cleared by using switch cases. While using switch cases for loops are used. The
programmer can execute the program and see its effect by entering the different choices.
5.21 Write a program to display the following files of current directory by using system the DOS
command: (1) .exe files, (2) .bat files, (3) .obj files and (4) .bak files.
void main()
{
int c;
clrscr();
printf(“\n FILE LISTING MENU”);
printf(“\n 1] .EXE”);
printf(“\n 2] .BAT”);
printf(“\n 3] .obj”);
printf(“\n 4] .bak\n Enter Your Choice -:”);
scanf(“%d”,&c);
switch(c)
{
case 1 :
system(“dir .exe”);
break;
case 2:
system(“\dir .c”);
break;
case 3:
system(“\dir .obj”);
break;
case 4:
system(“\dir .bak”);
break;
default :
break;
}
getch();
}
Explanation:
In the above program, a menu is displayed. The user can give different choices. The effect
can be observed by selecting one of the choices. The user can view all .exe, .bat,
.obj, .bak files. The effect is the same as the DOS ‘dir’ command. The System func-
tion is used to call the operating system command.
5.22 Write a program to display days in a calendar format of an entered month of year 2015.
void main()
{
int m,h,i=1,a,j,b=1;
clrscr();
printf (“\n Enter Month Number of the Year 2015 : “);
scanf (“%d”,&m); /* Program for finding days of any month of 2015*/
switch(m)
{
case 1 :
a=5;
j=31;
break;
case 2 :
a=1;
j=28;
break;
case 3 :
a=1;
j=31;
break;
case 4 :
a=4;
j=30;
break;
case 5 :
a=6;
j=31;
break;
case 6 :
a=2;
j=30;
break;
case 7 :
a=4;
j=31;
break;
case 8 :
a=7;
j=31;
break;
case 9 :
a=3;
j=30;
break;
case 10 :
a=5;
j=31;
break;
case 11 :
a=1;
j=30;
break;
case 12 :
a=3;
j=31;
break;
default :
printf (“\a\a Invalid Month”);
exit();
}
/* starting day is to be shown/adjusted as per calendar */
printf (“\n\n\n”);
printf (“\t\t\tMonth - %d - 2015\n\n”,m);
printf (“ SUN MON TUE WED THU FRI SAT\n\n”);
switch (a)
{
case 1 :
printf (“\t%d”,i);
break;
case 2 :
printf (“\t\t%d”,i);
break;
case 3 :
printf (“\t\t\t%d”,i);
break;
case 4 :
printf (“\t\t\t\t%d”,i);
break;
case 5 :
printf (“\t\t\t\t\t%d”,i);
break;
case 6 :
printf (“\t\t\t\t\t\t%d”,i);
break;
case 7 :
printf (“\t\t\t\t\t\t\t%d”,i);
break;
}
h=8-a; /* The starting day is subtracted from 8 */
for (i=2;i<=h;i++) /* To display the first row */
printf (“\t%d”,i);
printf (“\n”);
for (i=h+1; i<=j;i++) /* To continue with second row onwards */
{
if (b==8) /* To terminate the line after every week */
{
printf (“\n”);
b=1;
}
printf (“\t%d”,i);
b++;
}
getch();
}
OUTPUT:
Enter Month Number of the Year 2015: 2
Month – 2 – 2015
SUN MON TUE WED THU FRI SAT
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Explanation:
This program prints the days of a given month of a year (2015) in the calendar form. This
will be done without the help of system resources. The month number is to be entered by the
user. It is passed to the first switch structure. This structure finds the first day of the month
in the numeric form and the number of days present in that month. These values are assigned
to a and j, respectively. Here, Sunday to Monday refer to 1 to 7 values, respectively. The
printf() functions and second switch structure perform printing of dates in a column-
wise manner. The variables i, b are initialized to 1.
The second switch structure defines starting column and prints the value of ‘i’ that is
always 1. The value of ‘h’ (8 minus ‘a’) determines the number of dates to be printed in the first row.
This task is performed by the first for loop. In the second for loop, h is incremented with 1 and loop
continues up to the number of day, i.e. j. To break up dates rowwise, the if statement compares the
value of variable ‘b’ with 8. If b=8 then line breaks and ‘b’ again initializes to 1. Whenever b=8,
line is broken and whole dates of month are arranged in a calendar form.
# include <process.h>
void main()
{
int x,y=30,z;
clrscr();
printf(“\nEnter a number :”);
scanf(“%d”,&x);
printf(“\n Conversion of Decimal to Hexadecimal Number \n”);
for( ;; )
{
if(x==0)
exit(1);
z=x%16;
x=x/16;
gotoxy(y--,5);
switch(z)
{
case 10 :
printf(“A”);
break;
case 11 :
printf(“%c”,‘B’);
break;
case 12 :
printf(“%c”,“C”);
break;
case 13 :
printf(“D”);
break;
case 14 :
printf(“E”);
break;
case 15 :
printf(“F”);
break;
default :
printf(“%d”,z);
}
}
}
OUTPUT:
Enter a number : 31
Conversion of Decimal to Hexadecimal Number
1F
Explanation:
In the above program, an infinite for loop is used. In the for loop, the switch case
statement is used for printing letters A to F. In case entered numbers are in between 1 to 9,
the same will be displayed. But if the remainders obtained are greater than 9, in for loop, the
appropriate case statement is executed for displaying hexadecimal symbols A to F.
void main()
{
int x,y;
clrscr();
printf(“\n Enter a Number :”);
scanf(“%d”,&x);
switch(x)
{
case 0 :
printf(“\n Number is Even.”);
break;
case 1 :
printf(“\n Number is Odd .”);
break;
default :
y=x%2;
switch(y)
{
case 0:
printf(“\n Number is Even.”);
break;
default :
printf(“\n Number is Odd.”);
}
}
getche();
}
OUTPUT:
Enter a Number : 5
Number is Odd.
Explanation:
In the above-given program, the first switch statement is used for displaying the message
such as even or odd numbers when the entered numbers are 0 and 1, respectively.
When the entered number is other than 0 and 1, its remainder is calculated with modulous operator
and stored in the variable ‘y’. The variable ‘y’ is used in the inner switch statement. If the remainder
is ‘0’ the message displayed will be ‘Number is Even’, otherwise for non-zero it will be ‘Number is
Odd’. Here, the constants used for inner and outer switch statements are the same.
5.25 Write a program to count the number of 1s, 0s, blank spaces and others using nested
switch statement.
void main()
{
static int x,s,a,z,o;
char txt[20];
clrscr();
printf(“\nEnter Numbers :”);
gets(txt);
while(txt[x]!=’\0’)
{
switch(txt[x])
{
case ‘ ’ :
s++;
break;
default :
switch(txt[x])
{
case ‘1’:
a++;
break;
case ‘0’:
z++;
break;
default :
o++;
}
}
x++;
}
printf(“\n Total Spaces : %d”, s);
printf(“\n Total 1s : %d”,a);
printf(“\n Total 0s : %d”,z);
printf(“\n Others : %d”,o);
printf(“\n String Length: %d”,s+a+z+o);
}
OUTPUT:
Enter Numbers : 1110022 222
Total Spaces : 1
Total 1s : 3
Total 0s : 2
Others : 5
String Length:11
Explanation:
In the above-mentioned program, the outer switch counts only spaces in a given text. For
other than spaces, the inner switch statement is used. The inner switch is for counting
1s, 0s and others. The string length is printed at the end of the program, which is the addition
of all the counts.
Table 5.3 Distinction between the switch case and nested ifs
switch case nested ifs
The switch can only test for equality, i.e. only The if can evaluate relational or logical expressions.
constant values are applicable.
No two case statements have identical constants in Same conditions may be repeated for the number of
the same switch. times.
Character constants are automatically converted to Character constants are automatically converted to
integers. integers.
In switch case statement nested if can be In nested if statement switch case can be used.
used.
void main()
{
int x;
clrscr();
printf(“\n Enter a Number :);
scanf(“%d”,&x);
if(x==‘A’)
printf(“%c”,x);
}
OUTPUT:
Enter a Number : 65
A
Explanation:
In this program, the variable ‘x’ is declared as an integer variable. Its value is entered through
the keyboard. The ASCII value of entered number is checked with the if statement. If there
is a match, the ASCII, value is displayed.
5.27 Write a program to use nested if–else statements in the switch statement. Also show
the effect of conversion of integer to character.
void main()
{
int i;
clrscr();
printf(“\n Enter Any ASCII Number :”);
scanf(“%d”,&i);
clrscr();
switch(i)
{
case ‘A’:
printf(“Capital A\n”);
break;
case ‘B’:
printf(“Capital B\n”);
break;
case ‘C’:
printf(“Capital C\n”);
break;
default:
if(i>47 && i<58)
printf(“\n Digit :[ %c ]”,i);
else if(i>=58 && i<=64)
printf(“\nSymbol :[ %c ]”,i);
else if(i>64 && i<91)
printf(“\nCapital :[ %c ]”,i);
else if(i>96 && i<123)
printf(“\n Small :[ %c ]”,i);
else
printf(“\n Invalid Choice”,i);
getche();
}
}
OUTPUT:
Enter Any ASCII Number : 65
Capital A
Explanation:
An ASCII number is entered. In the outer switch if its ASCII value is equivalent to ‘A’,
‘B’ and ‘C’ then relevant message is displayed. If the ASCII values are other than these
three values, then the inner switch statement is used to determine its equivalent ASCII
symbols. The symbols may be any character including special symbols and digits. If we
enter 65, Capital A is displayed.
Summary
The reader is made aware about the decision-making statements such as if and the if–else state-
ments in the C programming. Also, the multi-way-decision statement switch case is also dis-
cussed. How nested if–else and switch case statements are to be used in programs are also
illustrated in a simple and easy way. Ample simple examples have been explained on the decision-
making statements. To change the flow of the program, the programmer can use statements such as
break, continue and goto. The reader is expected to execute all programs given in this chapter
so as to achieve the expertise in handling decision-making statements in the programs. By writing
programs for solving more real-life problems, a programmer benefits a lot.
eXercISeS
I Fill in the blanks:
1. The switch can only test for ________. (b) different constants
(c) variables
(a) equality
(b) non-equality 4. In switch, character constants are automatically
(c) None of them converted to ________
2. Only ______ values are applicable in the switch (a) floats
structure. (b) integers
(c) bool values
(a) constants
(b) variables 5. Same conditions may be repeated for number of
(c) objects times in _______structure.
3. No two case statements have ______ in the same (a) nested ifs
switch. (b) switch case
(c) None of the them
(a) identical constants
II True or false:
1. The else is associated with if. 10. Like if-else the switch statement can be
nested.
2. The else block is executed when condition is false.
11. The default statement is compulsory for
3. The if statement can have multiple else statements
switch statement
4. The statement if (1) executes if block.
12. The switch statement testes for equality only.
5. One switch statement can have multiple case
13. The if statement can evaluate relational and
statements but only one default statement.
logical expressions.
6. The default statement can be written anywhere in
14. The if statement works with expression as well
the switch block.
as constants.
7. The break statement is used to separate two
15. The default is a keyword.
case statements.
16. The default statement can be placed at the
8. The case statement is always terminated by a
beginning of switch, without any statement in
semi-colon.
its block
9. The switch statement accepts only constant as an
17. The switch block should be terminated by a
argument.
semi-colon.
III Select the appropriate option from the multiple choices given below:
1. The switch statement is used to 2. The default statement is executed when
(a) switch between functions in a program (a) all the case statements are false
(b) switch from one variable to another variable (b) one of the case is true
(c) choose from multiple possibilities which may (c) one of the case is false
arise due to different values of a single variable (d) None of the above
(d) use switching variables
1. Is it possible to use multiple else with if state- 7. Is it possible to use the else statement in place
ment? of default or vice versa?
2. Is it possible to use multiple default statements 8. Can we put default statement anywhere in the
in switch statement? switch case structure?
3. Write the use of else and default statements in 9. What are the limitations of the switch case
if–else and switch statements, respectively. statement?
4. Why goto statement is avoided? 10. What is a sequential execution?
5. Why the break statement is essential in the 11. What is the transfer of control?
switch statement?
6. Which other functions or keywords can be used in
place of the break statement?
anSWerS
I Fill in the blanks:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. a 2. a 3. a 4. b 5. a
II True or false:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. T 2. T 3. F 4. T 5. T
6. T 7. T 8. F 9. T 10. T
11. T 12. T 13. T 14. T 15. T
16. T 17. F
III Select the appropriate option from the multiple choices given below:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. a 2. a 3. a 4. a 5. a
6. a 7. a
6 Loop Control
Chapter Outline
6.1 Introduction
6.2 The for Loop
6.3 Nested for Loops
6.4 The while Loop
6.5 The do-while Loop
6.6 The while Loop within the do-while Loop
6.7 Bohm and Jacopini’s Theory
6.1 Introduction
In our life, we need to perform tasks which are repetitive in nature in numerous applications. It is a
tedious process to perform such kind of tasks repeatedly with pen/pencil and paper. But with
computer programming languages and packages, the task becomes easy, accurate and fast. For
example, salary of labours of a factory can be calculated simply by a formula (number of hours
work carried × wage rate per hour). The accounts department of every organization does this
calculation every month/week. Such a type of repetitive deeds can easily be done using a loop in
a program.
Steps in Loop
Loop variable : It is a variable used in the loop.
Initialization: It is the first step in which starting and final values are assigned to the loop
variable. Each time the updated value is checked by the loop itself.
Incrimination/decrimination: It is the numerical value added or subtracted to the variable in
each round of the loop. The updated value is compared with the final value and if it is found
less than the final value the steps in the loop are executed.
The above steps are implemented in numerous programs in this chapter.
(ii) Sentinel-controlled repetition: This is also called the indefinite repetition. One cannot esti-
mate how many iterations are to be performed. In this type, loop termination happens on the
basis of certain conditions using the decision-making statement.
The C language supports three types of loop control statements and their syntaxes are
described in Table 6.1 (also see Figures 6.1 and 6.2).
Start
Start Body of
loop
Initialization True
True Test
condition?
Test Body Update the
condition? statement/s initialised value
False
False
Stop Stop
Figure 6.1 The while statement Figure 6.2 The do-while statement
The for loop statement comprises three actions. These actions are placed in the for statement
itself. The three actions are initialize counter, test condition and Re-evalua-
tion parameters, which are included in one statement. The expressions are separated by
semi-colons (;). This leads the programmer to visualize the parameters easily. The for statement is
equivalent to while and do-while statements. The only difference between for and while is
that in the latter case logical condition is tested and then the body of the loop gets executed. However,
in the for statement, test is always performed at the beginning of the loop. The body of the loop may
not be executed at all times if the condition fails at the beginning.
for(a=10;a<10;a–-)
printf(“%d”, a);
For example, in the above two-line program will never execute because the test condition is not
proper at the beginning, hence statement following to for loop does not execute.
The do-while loop executes the body of the loop at least once regardless of the logical condition.
Increment the
Keyword
variable
for(counter=0;counter<=5;counter++)
Expression 1
Test NO
condition? Out of the loop
YES
Statements
Expression 3
1. The initialize counter sets to an initial value. This statement is executed only once.
2. The test condition is a relational expression, that determines the number of iterations
desired or determines when to exit from the loop. The ‘for’ loop continues to execute
as long as conditional test is satisfied. When the condition becomes false the control of
the program exits from the body of the ‘for’ loop and executes next statement after the
body of the loop.
3. The re-evaluation parameter decides how to make changes in the loop (increment or dec-
rement operations are to be used quite often). The body of the loop may contain either a
single statement or multiple statements. In case, there is only one statement after the for
loop, braces may not be necessary. In such a case, only one statement is executed till the
condition is satisfied. It is good practice to use braces even for single statement following
the for loop.
The syntax of the ‘for’ loop with only one statement is shown in the third row of Table 6.3.
The for loop can be specified by different ways and it is as per Table 6.3.
6.1 Print the first five numbers starting from 1 together with their squares.
void main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
printf(“\n Number: %5d it’s Square: %5d”,i,i*i);
}
OUTPUT:
Number: 1 it’s Square: 1
Number: 2 it’s Square: 4
Number: 3 it’s Square: 9
Number: 4 it’s Square: 16
Number: 5 it’s Square: 25
Explanation:
Let us now examine how the program executes.
1. The value of i sets to one for the first time when the program execution starts in the for
loop.
2. The condition i ≤ 5 is specified and tested in each iteration. Initially, the condition is true
since the value of i is 1. The statements following the for loop gets executed.
3. Upon execution of the printf() statement, compiler sends control back to the for
loop where the value of i is incremented by one. This is repeated till the value of ‘i’
is less than or equal to 5.
4. If the new updated value of i exceeds 5, the control exits from the loop.
5. The printf() statement executes as long as the value of i reaches 5.
The for loop can be used by different ways. Various examples using for loops are given
below.
void main()
{
int i;
clrscr();
for(i=1;i<=15;i++)
printf(“%5d”,i);
getche()
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation:
In the above program counter is initialized with a variable i = 1. Testing and incrementa-
tion of counter value are done in the for statement itself. Instead of i++ we can also use
i = i + 1. Here, we are illustrating a program using i = i +1.
6.3 Display numbers from 1 to 15 using for loop. Use i = i +1.
void main()
{
int i;
clrscr();
for(i=1;i<=15;i=i+1)
printf(“%5d”,i);
getche();
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation:
In the above program also, the value of counter is incremented at each time in the for state-
ment itself. Instead of i ++, i = i +1 is used in the for statement. The same result can
be observed as found in the previous example. The incrementation of a counter can be done
anywhere in the body of for loop and for infinite times. An example is stated below where
in the counter value is incremented in the body of the loop and not in the for statement.
6.4 Write a program to display numbers from 1 to 16. Use incrementation operation in the body
of the loop for more than one time.
void main()
{
int i,c=0;
clrscr();
for(i=0;i<=15;)
{
i++;
printf(“%5d”,i);
i=i+1;
printf(“%5d”,i);
c++;
}
printf(“\n\n The Body of the loop is executed for %d times.”,c);
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The Body of the loop is executed for 8 times.
Explanation:
The body of the loop is executed for eight times. Incrementation operation is done following
the for statement. Hence, the counter which is initialized in the for statement is incre-
mented first, i.e. the value of i after incrementation is one and the same is displayed with
the first printf() statement. After this operation, once again in the loop i is incremented
by 1 and the values are displayed using the second printf() statement. The body of the
loop is executed till i=15 and for eight times. In the example given below, the declaration of
counter is done before the for statement.
6.5 Write a program to display even numbers from 0 to 14. Declare the initial counter value
before the for loop statement.
void main()
{
int i=0;
clrscr();
for(;i<=15;)
{
printf(“%5d”,i);
i+=2;
}
}
OUTPUT:
0 2 4 6 8 10 12 14
Explanation:
In this program, the for statement contains only test condition. The semi-colon (;) is
essential before and after the condition. The for statement must contain two semi-colons
even though no parameters are provided.
6.6 Write a program to display the numbers in ascending (1 to 10) and descending (10 to 1) orders.
void main()
{
int i=0;
clrscr();
printf(“Numbers in Ascending Order :”);
for(;++i<=10;)
printf(“%3d”,i);
printf(“\n\n”);
printf(“Numbers in Descending Order :”);
for(;i-->1;)
printf(“%3d”,i);
}
OUTPUT:
Numbers in Ascending Order : 1 2 3 4 5 6 7 8 9 10
Numbers in Descending Order: 10 9 8 7 6 5 4 3 2 1
Explanation:
In the above example, incrementation and comparison are done in the first for loop.
The decrementation operation is in the second for loop. With ++i<=10, firstly, i is
incremented and comparison is made and result is displayed through the printf()
statement. With i–->1, (counter) value is compared first. After satisfying decrementation
operation is performed and the value is displayed.
6.7 Write a program to display letters from a to j using infinite for loop. Use goto statement
to exit from the loop.
void main()
{
char i=97;
clrscr();
for(; ;)
{
printf(“%5c”,i++);
if(i==107)
goto stop;
}
stop:;
getche();
}
OUTPUT:
a b c d e f g h i j
Explanation:
The for(; ;) statement is used in the above program. This statement allows the execution
of the body of the loop infinite times. To exit from the infinite for loop, goto statement is
used. After satisfying the test condition, goto statement is executed which terminates the
program. The output is displayed in alphabets from a to j.
6.8 Write a program to count numbers between 1 to 100 not divisible by 2, 3 and 5.
void main()
{
int x,c=0;
clrscr();
OUTPUT:
Numbers from 1 to 100 not divisible by 2,3 & 5
1 7 11 13 17 19 23 29 31 37
41 43 47 49 53 59 61 67 71 73
77 79 83 89 91 97
Total Numbers : 26
Explanation:
In the above program, for loop executes from 1 to 100. Each time mod operation is per-
formed with 2, 3 and 5 with the value of the loop variable. If the remainder is non-zero then
the counter ‘c’ is incremented. Thus, 1 to 100 numbers are checked. At the end, the variable
‘c’ displays the total number.
6.9 Write a program to display the numbers in increasing and decreasing order using the infinite
for loop.
void main()
{
int n,a,b;
clrscr();
printf(“Enter a number :”);
scanf(“%d”,&n);
a=b=n;
printf(“(++) (–-)\n”);
printf(“============”);
for(; ; (a++,b–-))
{
printf(“\n%d\t%d”,a,b);
if(b==0)
break;
}
}
OUTPUT:
Enter a number : 5
(++) (--)
==========
5 5
6 4
7 3
8 2
9 1
10 0
Explanation:
The infinite for loop can also be specified as shown in the above program. The initial coun-
ter value, which is set to a given number, can be continuously incremented or decremented.
In order to terminate from the infinite for loop, a condition (b==0) is tested. After satisfy-
ing break statement allows to exit from the loop.
6.10 Create an infinite for loop. Check each value of the for loop. If the value is even, display
it otherwise continue with iterations. Print even numbers from 1 to 21. Use break state-
ment to terminate the program.
void main()
{
int i=1;
clrscr();
printf(“\n\t\t Table of Even numbers from 1 to 20”);
printf(“\n\t\t ===== == ==== ======= ==== = == ==\n”);
for(; ;)
{
if(i==21)
break;
else if(i%2==0)
{
printf(“%d\t”,i);
i++;
continue;
}
else
{
i++;
continue;
}
}
getche();
}
OUTPUT:
Table of Even numbers from 1 to 20
==== == ==== ======= === = == ==
2 4 6 8 10 12 14 16 18
Explanation:
In the above program, both break and continue statements are in use. The program dis-
plays only even numbers from 1 to 21. An infinite loop is created and in the loop variable ‘i’ is
incremented. The value of ‘i’ is checked every time. If it is even, it is printed otherwise con-
tinue statement is executed, which passes control at the beginning of the for loop. When the
value of ‘i’ reaches to 21, the break statement is executed and it terminates the loop.
6.11 Write a program to display numbers from 1 to 9 and their square roots.
# include <math.h>
void main()
{
int i;
float a;
clrscr();
for(i=1;i<=9;i++)
printf(“\n\t %d %.2f “,i,a=sqrt(i));
getche();
}
OUTPUT:
1 1.00
2 1.41
3 1.73
4 2.00
5 2.24
6 2.45
7 2.65
8 2.83
9 3.00
Explanation:
In the above program, the for loop executes nine times from 1 to 9. The sqrt() functions
return square root of a number. Each time value of variable ‘i’ is passed to sqrt() and it
returns square root of that number. The header file math.h is essential.
6.12 Write a program to find the number in between 7 and 100 which is exactly divisible by 4
and if divided by 5 and 6 remainders obtained should be 4.
# include <process.h>
void main()
{
int x;
clrscr();
for(x=7;x<100;x++)
{
if(x%4==0 && x%5==4 && x%6==4)
{
printf(“\n Number : %d”,x);
}
}
getche();
}
OUTPUT:
Number : 64
Explanation:
In the above program, the for loop is initialized from 7 to 100. The if statement is used
for dividing with modular division operations by 4, 5 and 6. The remainders obtained are
checked. If they are 0, 4 and 4 respectively, then the number is displayed.
6.13 Write a program to evaluate the series given in comments.
/* x=1/1+1/4+1/9...1/n2 */
/* y=1/1+1/8+1/27...1/n3 */
# include <math.h>
void main()
{
int i,n;
float x=0,y=0;
clrscr();
printf(“Enter Value of n:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
x=x+(1/pow(i,2));
y=y+(1/pow(i,3));
}
printf(“Value of x = %f”,x);
printf(“\nValue of y = %f”,y);
getche();
}
OUTPUT:
Enter Value of n: 2
Value of x = 1.2500
Value of Y = 1.12500
Explanation:
Initially, it is assumed that the sum of the two series 1 and 2 is zero. So, the variables ‘x’ and
‘y’ are set to zero. The denominators of the first and second equations are squares and cubes
of numbers from 1 to ‘n’ respectively. The user enters the value of ‘n’, which determines
how long the series should be continued. Every time in the loop square and cube of variable
‘i’ are calculated using the library function pow(). They are added to variables ‘x’ and
‘y’, respectively.
6.14 Write a program to generate the triangular number.
Note: Triangular number is nothing but summation of 1 to given number.
For example, when entered number is 5, its triangular number would be (1+2+3+4+5)=15.
void main()
{
int n,j,tri_num=0;
clrscr();
printf(“What Triangular number do you want :”);
scanf(“%d”,&n);
for(j=1;j<=n;++j)
tri_num=tri_num+j;
printf(“Triangular number of 5 is %d”,tri_num);
}
OUTPUT:
What Triangular number do you want? : 5
Triangular number of 5 is 15
Explanation:
In the above program, a number is entered whose triangular number is to be calculated. The
for loop is initialized from 1 to ‘n’. In each iteration of for loop, the value of ‘j’ is added
to the ‘tri_num’ variable. When the loop terminates the ‘tri_num’ contains triangular
number of the entered number.
/* 1. 1+2+3+..n */
/* 2. 12+22+32+..n2 */
void main()
{
int sum=0,ssum=0,i,j;
clrscr();
printf(“Enter Number :”);
scanf(“%d”, &j);
clrscr();
printf(“ Numbers:”);
for(i=1;i<=j;i++)
printf(“%5d”,i);
printf(“\n\nSquares:”);
for(i=1;i<=j;i++)
{
printf(“%5d”,i*i);
sum=sum+i;
ssum=ssum+i*i;
}
printf(“\n\nSum of Numbers from 1 to %d :%d”,j,sum);
printf(“\nSum of Squares of 1 to %d Numbers :%d”,j,ssum);
}
OUTPUT:
Enter Number: 5
Numbers: 1 2 3 4 5
Squares: 1 4 9 16 25
Sum of Numbers from 1 to 5: 15
Sum of Squares of 1 to 5 Numbers: 55
Explanation:
In the above program, sum and square of sum are assumed to be zero. The first for loop
prints number from 1 to the entered number. The second for loop does sum and squares
of the numbers from 1 to the entered number. The variable ‘sum’ and ‘ssum’ are used for
displaying the final results.
6.16 Write a program to find the perfect squares from 1 to 500.
#include <math.h>
void main()
{
int i,count,x;
float c;
clrscr();
printf(“\n\n”);
printf(“ Perfect squares from 1 to 500\n”);
count=0;
for(i=1;i<=500;i++)
{
c=sqrt(i);
x=floor(c); /* For rounding up floor() is used. */
if(c==x)
{
printf(“\t%5d”,i);
count++;
}
}
printf(“\n\n Total Perfect Squares =%d\n”,count);
getch();
}
OUTPUT:
Perfect squares from 1 to 500
1 4 9 16 25 36 49 64 81 121 144
169 196 225 256 289 324 361 400 441 484
Total Perfect Squares = 22
Explanation:
Numbers like 2, 4, 9, 25, . . . are perfect squares. In the above program a for loop is used from
1 to 500. We can use the sqrt() function for finding the square root of numbers. The square
root obtained is stored in variable ‘c’, and it is rounded off and stored in another variable ‘x’.
The value of ‘c’ remains unchanged. Now the comparison between ‘x’ and ‘c’ is made. If both
of them are the same, then the number becomes a perfect square root. Perfect square roots are
only integers and not floats. Hence, floor() function does not affect the integer values.
6.17 Write a program to detect the largest number out of five numbers and display it.
#include<process.h>
void main()
exit(0);
{
int a,b,c,d,e,sum=0,i;
clrscr();
printf(“\nEnter Five numbers :”);
scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e);
sum=a+b+c+d+e;
for(i=sum; i<=sum;i–-)
{
if(i==a || i==b || i==c || i==d || i==e)
{
printf(“The Largest Number : %d”,i);
exit(0);
}
}
}
OUTPUT:
Enter Five numbers : 5 2 3 7 3
The Largest Number : 7
Explanation:
Through the keyboard, five numbers are entered and their sum is stored in the vari-
able ‘sum’. The for loop is used up to the value of ‘sum’ in the reverse order (––).
While decrementing the value of sum, the same is tested each time as to whether dec-
remented sum is equal to one of the entered numbers. In case the condition is satisfied,
the largest number is displayed and exit() terminates the program. The largest num-
ber entered through the keyboard appears first while decrementing the value of ‘sum’
(sum=a+b+c+d+e).
6.18 Write a program to print the five entered numbers in the ascending order.
void main()
{
int a,b,c,d,e,sum=0,i;
clrscr();
printf(“\nEnter Five numbers :”);
scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e);
printf(“\n Numbers in ascending order :”);
sum=a+b+c+d+e;
for(i=1; i<=sum;i++)
{
if(i==a || i==b || i==c || i==d || i==e)
{
printf(“%3d”,i);
}
}
}
OUTPUT:
Enter Five numbers : 5 8 7 4 1
Numbers in ascending order : 1 4 5 7 8
Explanation:
The logic used is the same as in the previous program. Here, after satisfying the if condi-
tion the program does not terminate and searches for the next number. This procedure is
continued till the value of ‘a’ reaches to ‘sum’. The numbers are sorted and displayed in
the increasing order.
For descending order the for should be ‘for(i=sum; i<=sum;i––)’.
6.19 Perform multiplication of two integers by using the negative sign.
void main()
{
int a,b,c,d=0;
clrscr();
printf(“\n Enter two numbers :”);
scanf(“%d %d”, &a,&b);
for(c=1;c<=b;c++)
d=(d)-(-a);
printf(“Multiplication of %d * %d :%d”,a,b,d);
getche();
}
OUTPUT:
Enter two numbers : 5 5
Multiplication of 5 * 5 : 25
Explanation:
The multiplication is nothing but repetitive addition. For example, multiplication of 5 × 5 is 25
and the result is obtained by adding 5, five times. Here, the two numbers are entered and the
1st number (‘a’) is repeatedly added to ‘b’ (2nd number) times and result is stored in ‘d’. Instead
of using ‘+’ sign double negative is used. Multiplication of two −ve signs is +ve (− − = +).
6.20 Perform multiplication of two integers by using repetitive addition.
void main()
{
int a,b,c=1,d=0;
clrscr();
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &a,&b);
for(;;)
{
d=d+a;
if(c==b)
goto stop;
c++;
}
stop:
printf(“Multiplication of %d * %d :%d”,a,b,d);
getche();
}
OUTPUT:
Enter two numbers : 8 4
Multiplication of 8 * 4 : 32
Explanation:
Here, also the two numbers are entered through the keyboard. The infinite for loop is used
and counter ‘c’ is initialized to 1 and ‘d’ to 0. Variable ‘d’ is used for storing the result after
repetitive addition. After adding the value of ‘a’ in ‘d’ each time the counter ‘c’ is tested with
‘b’. If there is no match, counter is incremented and program goes back in the loop and the
addition is performed again. When ‘c’ equals to ‘b’ (repetitive addition of the first number
till the counter is equal to the second number), program terminates using the goto statement
and the result of multiplication is displayed.
6.21 Calculate the sum and average of five subjects.
void main()
{
int a,b,c,d,e,sum=0,i;
float avg;
clrscr();
printf(“\nEnter The Marks of Five Subjects”);
for(i=1;i<=5;i++)
{
printf(“\n[%d] Student:”,i);
if(scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e)==5)
{
sum=a+b+c+d+e;
avg=sum/5;
printf(“\n Total Marks of Student[%d] %d”,i,sum);
printf(“\n Average Marks of Student[%d] %f\n”,i,avg);
}
else
{
clrscr();
printf(“\n Type Mismatch”);
}
}
}
OUTPUT:
Enter The Marks of Five Subjects
[1] Student: 58 52 52 56 78
Total Marks of Student[1] 296
Average Marks of Student[1] 59.000000
[2] Student:
Explanation:
Here, the for loop is used for entering marks of five students. The marks of five subjects are en-
tered through the keyboard. They are assigned to variables ‘a’, ‘b’, ‘c’, ‘d’ and ‘e’. Their ‘sum’ and
‘average’ are calculated. If by mistake, the user enters marks other than integers the program
reports the error message ‘Type Mismatch’. The scanf() is compared with the number of
arguments entered correctly. If it is less than the given argument the program displays ‘Type
Mismatch’. The marks of the second student onwards can be entered and the results can be
observed.
6.22 Write a program to enter a character and display its position in alphabets.
# include <ctype.h>
void main()
{
int c=1;
char i, ch;
clrscr();
printf(“Enter a character :”);
scanf(“%c”,&ch);
ch=toupper(ch);
for(i=65;i<=90;i++,c++)
if(ch ==i)
printf(“\n’%c’is%d [st/nd/rd/th] Character in Alphabetic.”,i,c);
}
OUTPUT:
Enter a character : U
‘U’ is 21 [st//nd/rd/th] Character in Alphabetic.
Explanation:
In this program, a character is entered. It is converted into capital. The ASCII values of A
to Z are from 65 to 90. The for loop is taken from 65 to 90 and these values are compared
with the entered character. Certainly, there will be a match somewhere. For this, statement
(ch==i) is used. Till the match is achieved counter is incremented. Once the match occurs,
we get the position of character from the first alphabetic with the help of a counter.
6.23 Write a program to enter mantissa and exponent. Calculate the value of mx. Where ‘m’ is a
mantissa and ‘x’ is an exponent.
void main()
{
int i,number,power;
long ans;
clrscr();
printf(“\n Enter Number :”);
scanf(“%d”,&number);
printf(“\n Enter Power :”);
scanf(“%d”,&power);
ans=1;
for(i=1;i<=power;i++)
ans*=number;
printf(“\n The Power of %d raised to %d is %ld\n”, number,
power,ans);
getche();
}
OUTPUT:
Enter Number : 5
Enter Power : 3
The Power of 5 raised to 3 is 125.
Explanation:
In the above program, mantissa and exponents are entered. The first number is mantissa and
the second is its power. The variable ‘ans’ stores repetitive multiplication of mantissa till the
loop is active. Finally, it displays the power of a given number.
6.24 Write a program to perform subtraction of two loop variables. Use nested for loops.
void main()
{
int a,b,sub;
clrscr();
for(a=3;a>=1;a–-)
{
for(b=1;b<=2;b++)
{
sub=a-b;
printf(“a=%d\t b=%d\t a-b=%d\n”,a,b,sub);
}
}
}
OUTPUT:
a=3 b=1 a-b = 2
a=3 b=2 a-b = 1
a=2 b=1 a-b = 1
a=2 b=2 a-b = 0
a=1 b=1 a-b = 0
a=1 b=2 a-b =-1
Explanation:
In the above program, the outer loop variable and inner loop variables are ‘a’ and ‘b’, respec-
tively. For each value of ‘a’ the inner loop is executing twice. The inner loop terminates when
the value of ‘b’ exceeds 2 and the outer loop terminates when the value of ‘a’ is 0. Thus, the
outer loop executes thrice and for each outer loop, the inner loop executes twice. Thus, the
total iterations are 3 × 2 = 6 and six output lines are shown in the output.
6.25 Write a program to illustrate an example based on the nested for loops.
void main()
{
int i,j;
clrscr();
for(i=1;i<=3;i++) /* outer loop */
{
for(j=1;j<=2;j++) /* inner loop */
printf(“\n i*j : %d”,i*j);
}
}
OUTPUT:
i*j = 1
i*j = 2
i*j = 2
i*j = 4
i*j = 3
i*j = 6
Explanation:
Here, in the above example for each value of ‘i’ the inner loop’s j value varies from 1 to 2. Outer
loop executes three times whereas the inner loop executes six times. The inner loops terminate
when the value of j = 2 and the outer loop terminates when the value of i =3. The total number
of iterations=outer loop iterations (3) inner loop iterations (2) = 6.
6.26 Write a program using nested for loops. Print values and messages when any loop ends.
void main()
{
int a,b,c;
clrscr();
for(a=1;a<=2;a++) /* outer loop */
{
for(b=1;b<=2;b++) /* middle loop */
{
for(c=1;c<=2;c++) /* inner loop */
printf(“\n a=%d + b=%d + c=%d : %d”,a,b,c,a+b+c);
printf(“\n Inner Loop Over.”);
}
printf(“\n Middle Loop Over.”);
}
printf(“\n Outer Loop Over.”);
}
Explanation:
The execution of the above program will be done by the C compiler in sequence as per Table 6.4.
The total number of iterations is equal to 2 2 2 = 8. The final output provides eight results.
# include<math.h>
void main()
{
int i, j, k;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”,&k);
for(i=1;i<k;i++)
{
for(j=1;j<=i;j++)
{
if(i==pow(j,3))
printf(“\nNumber : %d & it’s Cube :%d”,j,i);
}
}
}
OUTPUT:
Enter a Number : 100
Number : 1 & it’s Cube : 1
Number : 2 & it’s Cube : 8
Number : 3 & it’s Cube : 27
Number : 4 & it’s Cube : 64
Explanation:
In the above program, the programmer has to enter the number up to which the perfect cubes
are to be obtained. For example, if the user enters 100, the perfect cubes up to 100 are 1, 8, 27
and 64. Here, the two for loops are used. The outer for loop varies up to the entered num-
ber. The inner for loop varies up to value of ‘i’. For each value of ‘j’, its cube is calculated
and checked with the value of ‘i’. If the if condition is true, the perfect cubes are printed,
otherwise the loop continues. Thus, all the perfect cubes up to a given number are displayed.
6.28 Write a program to display numbers 1 to 100 using ASCII values from 48 to 57. Use the
nested loops.
void main()
{
int i,j=0,k= -9;
clrscr();
printf(“\t Table of 1 to 100 Numbers Using ASCII Values \n”);
printf(“\t ===== == = == === ======= ===== ===== ======\n”);
for(i=48;i<=57;i++,k++)
{
for(j=49;j<=57;j++)
printf(“%5c%c”,i,j);
if(k!=1)
printf(“%5c%c”,i+1,48);
if(k==0)
printf(“\b\b%d%d%d”,k+1,k,k);
printf(“\n\n”);
}
getche();
}
OUTPUT:
Table of 1 to 100 Numbers Using ASCII Values
==== == = == === ======= ===== ===== ==
01 02 03 04 05 06 07 08 09 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Explanation:
The first for loop is varying from 48 to 57. These numbers are used for printing the first
digit of every number from 1 to 100. 48 to 57 are ASCII codes for 0 to 9. The second for
loop is varying from ASCII 49 to 57 whose equivalent numerical numbers are 1 to 9. These
ASCII codes are used for printing the second digit. In each output line the common digit like
0 in the first line is decided by the variable of the outer loop. It varies from 0 to 9. The second
digit of each line is decided by the variable of inner loop, which varies for all lines from 1 to
9. The value of k = −9 for displaying 10 rows. For displaying numbers from 01 to 99, ‘i’ and
‘j’ are printed without using space in one printf() statement. The first if statement is
used for printing 10, 20, 30 up to 90 numbers. The second if is used to print 100.
6.29 Write a program to count number of votes secured by ‘A’ & ‘B’. Assume three voters are
voting them. Also count the invalid votes.
# include <ctype.h>
void main()
{
int a=0,b=0,o=0,i;
char v;
clrscr();
printf(“\tPress A or B\n”);
for(i=1;i<=3;i++)
{
printf(“\n\nVoter no. %d”,i);
printf(“Enter Vote :”);
v=getche();
v=toupper(v);
if(v==‘A’)
a++;
else if(v==‘B’)
b++;
else
o++;
}
printf(“\n\n Status of vote(s) \n”);
printf(“\nA secures %d vote(s).”,a);
printf(“\nB secures %d vote(s).”,b);
printf(“\nInvalid votes %d.”,o);
}
OUTPUT:
Press A or B
Voter no. 1 Enter Vote :A
Voter no. 2 Enter Vote :A
Voter no. 3 Enter Vote :A
Status of vote(s)
A secures 3 vote(s).
B secures 0 vote(s).
Invalid votes 0.
Explanation:
In the above program, the for loop is used for the number of voters who will be voting to
either ‘A’ or ‘B’. The body of the loop is executed for three times. The voter can give his/her
choice by pressing either ‘A’ or ‘B’. Apart from these two characters, if the user enters any
other character, the vote will be invalid. The results are displayed at the output.
6.30 Write a program to simulate a digital clock.
# include <dos.h>
void main()
{
int h,m,s;
clrscr();
for(h=1;h<=12;h++)
{
clrscr();
for(m=1;m<=59;m++)
{
clrscr();
for(s=1;s<=59;s++)
{
gotoxy(8,8);
printf(“hh mm ss\n”);
gotoxy(8,9);
printf(“%d %d %d”,h,m,s);
sleep(1);
}
}
}
}
OUTPUT:
hh mm ss
1 1 1
Explanation:
The above program uses three for loops for hour, minute and second. The inner most loop
is for second’s operation, followed by middle loop for minutes and the outer most for hours.
When the second’s loop executes 60 times, the minutes loop increments by 1. Similarly, the
hours loop increments after completing minute’s loop. The hours loop increments only up to
12. Thereafter, it resets from 1. The gotoxy() function is used for selecting the position
where hh mm ss is to be marked.
6.31 Write a program to count the occurrence of 0 to 9 digits between 1 and the given decimal
number.
void main()
{
int t,k,n,l,i;
static int st[10];
clrscr();
printf(“\n Enter a Decimal Number :”);
scanf(“%d”,&n);
for(l=1;l<=n;l++)
{
t=l;
while(t!=0)
{
k=t%10;
t=t/10;
st[k]++;
}
}
Explanation:
A decimal number is entered through a keyboard with the variable n. The for loop is used
from 1 to n (up to the given number). The value of ‘l’ is copied to another variable ‘t’. In
the body of the while loop mod operation is performed on variable ‘t’ for separating indi-
vidual digits, and the separated digit is stored in the variable ‘k’. Further, the ‘t’ is divided
by 10 for obtaining remainders and is assigned to ‘t’. The array st[10] is initialized
to 0 using static storage class. The variable ‘k’ is used as an argument with st[], and it is
incremented. The value of ‘k’, whatever it contains when used in arrays st[] that element
number will be incremented. Thus, we get the occurrence of digits from 0 to 9 by printing
this array.
6.32 Write a program to accept a number and find sum of its individual digits repeatedly till the
result is a single digit.
void main()
{
int n,s=0;
clrscr();
printf(“\n Enter a Number :”);
scanf(“%d”,&n);
printf(“\n Sum of Digits till a single digit\n %d”,n);
for(; n!=0 ;)
{
s=s+n%10;
n=n/10;
if(n==0 && s>9)
{
printf(“\n %2d”,s);
n=s;
s=0;
}
}
printf(“\n %2d”,s);
}
OUTPUT:
Enter a Number :4687
Sum of Digits till a single digit
4687
25
7
Explanation:
In the above program, a number is entered through the keyboard. The for loop executes till
the value of variable ‘n’ is non-zero. The sum of digits obtained is assigned to variable ‘n’. If
‘n’ is found zero and sum is greater than 9 the for loop continues. Thus, repeatedly the sum
of digits is calculated till the result of sum becomes less than 10.
6.33 Write a program to display octal numbers in binary. Attach a parity bit with “1” if number
of 1s are even otherwise “0”.
OR
Generate odd parity to octal numbers 0 to 7. Express each number in binary and attach the
parity bit.
void main()
{
int x,y,a,b,c=0,j=12,k=2;
clrscr();
printf(“ Binary Bits Parity Bits\n”);
printf(“ =========== ===========”);
for(x=0;x<8;x++)
{
k++;
j=12;
y=x;
for(a=0;a<3;a++)
{
b=y%2;
gotoxy(j-=3,k);
printf(“%d”,b);
y=y/2;
if(b==1)
c++;
}
if(c%2==0)
{
gotoxy(25,k);
printf(“%d”,1);
}
else
{
gotoxy(25,k);
printf(“%d”,0);
}
c=0;
}
}
OUTPUT:
Binary Bits Parity Bits
=========== ===========
0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0
Explanation:
In the above program, two for loops are used. The inner for loop generates three binary
bits for each octal number. The 0 to 7 octal numbers are taken from the outer for loop. If the
bit is 1 counter ‘c’ is incremented. The value of ‘c’ is checked for even or odd condition. If
‘c’ is odd, the parity bit ‘0’ is displayed otherwise ‘1’ will be displayed.
6.34 Write a program to evaluate the series given in comments.
/ sum of series of x-x3/3!+x5/5!-x7/7!+...xn/n! */
# include <math.h>
void main()
{
int n,i,x,c=3,f=1,l;
float sum;
clrscr();
printf(“Enter x & n :”);
scanf(“%d %d”,&x,&n);
sum=x;
for(i=3;i<=n;i+=2)
{
f=1;
if(c%2!=0)
{
for(l=1;l<=i;l++)
f=f*l;
sum=sum-pow(x,i)/f;
}
else
{
for(l=1;l<=i;l++)
f=f*l;
sum=sum+pow(x,i)/f;
}
c++;
}
printf(“\nSum of series Numbers :%f”,sum);
getche();
}
OUTPUT:
Enter x & n : 2 5
Sum of series Numbers :0.9333
Explanation:
Through the keyboard, the values of ‘x’ and ‘n’ are entered, where numerical constant values
are assigned to ‘x’ and ‘n’. Throughout the series, ‘n’ decides how long the series should con-
tinue. The series contains alternate + and − terms. The two for loops within if are used for
calculating the factorials. The if statement decides the positive or negative term depending
upon odd or even value of ‘c’.
The following are the programs based on a series. The logic of the programs is simple for under-
standing.
6.35 Write a program to evaluate the series given in comment.
/* x+x2/2!+x4/4!+x6/6!+...xn/n! */
# include <math.h>
void main()
{
int f=1,l,i,x,y;
float sum;
clrscr();
printf(“Enter the value of x & y :”);
scanf(“%d %d”,&x,&y);
sum = x;
for(i=2;i<=y;i+=2)
{
f=1;
for(l=1;l<=i;l++)
f=f*l;
sum = sum + pow(x,i)/f;
}
printf(“\n Sum of Series : %f”, sum);
getche();
}
OUTPUT:
Enter the value of x & y : 4 4
Sum of Series :22.6666
# include <math.h>
void main()
{
int n,i,c=3,l;
float sum=0,f=1,k;
clrscr();
printf(“Enter value of n :”);
scanf(“%d”,&n);
sum=1;
for(i=1;i<=n;i++)
{
f=1;
if(c%2!=0)
{
for(l=1;l<=i;l++)
f=f*l;
k=i/f;
sum=sum-k;
}
else
{
for(l=1;l<=i;l++)
f=f*l;
sum=sum+(i/f);
}
c++;
}
printf(“\nSum of series Numbers :%f”,sum);
}
OUTPUT:
Enter value of n : 3
Sum of series Numbers : 0.5000
6.37 Write a program to detect the Armstrong numbers in three digits from 100 to 999. If the sum
of cubes of each digits of the number is equal to the number itself, then the number is called
an Armstrong number (e.g. 153 = 13 53 33 = 153).
# include <math.h>
void main()
{
int n,d,x;
int k,i,cube=0;
clrscr();
printf(“\n The following numbers are armstrong numbers.”);
for(k=100;k<=999;k++)
{
cube=0;
x=1;
d=3;
n=k;
while(x<=d)
{
i=n%10;
cube=cube+pow(i,3);
n=n/10;
x++;
}
if(cube==k)
printf(“\n\t\ %d”,k);
}
}
OUTPUT:
The Following Numbers are Armstrong numbers.
153
370
371
470
Explanation:
The program separates individual digit of number and calculates cubes of each digit. If the sum
of the cubes of individual digits of a number is equal to that number, then the number is called
Armstrong numbers.
void main()
{
int x,i,j;
clrscr();
printf(“How many lines stars (*) should be printed ? :”);
scanf(“%d”,&x);
for(i=1;i<=x;i++)
{
for(j=1;j<=i;j++)
{
printf(“*”);
}
printf(“\n”);
}
}
OUTPUT:
How many lines stars (*) should be printed ? : 5
*
* *
* * *
* * * *
* * * * *
Explanation:
Here in the above example, the two for loops are used for displaying as per the format
shown in the output. Variables ‘x’, ‘i’ and ‘j’ are used according to the requirement. On the
execution of inner loop star/stars are displayed. To display them in different lines the second
printf() statement is used.
6.39 Write a program to generate the pattern of numbers as given below.
5 4 3 2 1 0
4 3 2 1 0
3 2 1 0
2 1 0
1 0
0
void main()
{
int i,c=0;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”,&i);
for(;i>=0;i–-)
{
c=i;
printf(“\n”);
for(; ;)
{
printf(“%3d”,c);
if(c==0)
break;
c–-;
}
}
}
OUTPUT:
Enter a number: 6
6 5 4 3 2 1 0
5 4 3 2 1 0
4 3 2 1 0
3 2 1 0
2 1 0
1 0
0
Explanation:
An integer value is read for variable ‘i’. The first for loop decrements the value of ‘i’. The
value of ‘i’ is assigned to variable ‘c’. In the second infinite for loop, the value of ‘c’ is
printed and decremented. The if condition terminates the infinite for loop when it finds
the value of ‘c’ is 0.
6.40 Write a program to display the series of numbers as given below.
1
1 2
1 2 3
1 2 3 4
4 3 2 1
3 2 1
2 1
1
void main()
{
int i,j,x;
printf(“\nEnter Value of x :”);
scanf(“%d”,&x);
clrscr();
for(j=1;j<=x;j++)
{
for(i=1;i<=j;i++)
printf(“%3d”,i);
printf(“\n”);
}
printf(“\n”);
for(j=x;j>=1;j–-)
{
for(i=j;i>=1;i–-)
printf(“%3d”,i);
printf(“\n”);
}
}
OUTPUT:
Enter Value of x : 4
1
1 2
1 2 3
1 2 3 4
4 3 2 1
3 2 1
2 1
1
Explanation:
The first two for loops are used to display the first four lines of the output. The next two for
loops are used to display the last four lines of the output. The outputs of the first four lines are
in ascending order whereas in the last four lines the numbers are in descending order.
void main()
{
int k,i,j,x,p=34;
printf(“\n Enter A number :”);
scanf(“%d”,&x);
clrscr();
for(j=0;j<=x;j++)
{
gotoxy(p,j+1);
/* position curosr on screen (x cordinate,y cordinate) */
for(i=0-j;i<=j;i++)
printf(“%3d”,abs(i));
p=p-3;
}
}
OUTPUT:
Enter a number : 3
0
1 0 1
2 1 0 1 2
3 2 1 0 1 2 3
Explanation:
Here, in the above program ‘p’ is equated to 34. This number decides the ‘x’ co-ordinate on
the screen from where numbers are to be displayed. The ‘y’ co-ordinate is decided by j+1
where ‘j’ is varying from 0 to the entered number. The value of ‘i’ is negative towards the
left of zero. Hence, its absolute value is taken. The inner for loop is executed for displaying
digits towards the left and right of zero.
void main()
{
int x[5]={1,1,1,1,1};
int y=x[0],i;
clrscr();
printf(“\n Values in different Iterations. \n”);
printf(“====== == ========= ===========\n”);
for(i=0;i<4;i++)
{
y=y*2+x[i+1];
printf(“[%d] %d\t”,i+1,y);
}
printf(“\nEquivalent of [”);
for(i=0;i<5;i++)
printf(“%d”,x[i]);
printf(“] in Decimal Number is :”);
printf(“%d\t”,y);
getche();
}
OUTPUT:
Values in different Iterations.
=======================
[1] 3 [2] 7 [3] 15 [4] 31
Equivalent of [1 1 1 1 1] in Decimal Number is : 31
Explanation:
A binary number is initialized in an array. The first element of the array is assigned to vari-
able ‘y’. The logic used here is to multiply by 2 the variable ‘y’ and add the next successive
bit. For this the equation y=y*2+x[i+1] is used. The number of iterations to be carried out
is equal to the number of binary bits minus 1. Here, five bits are initialized, hence the number
of iterations will be four.
6.43 Write a program to add a parity bit with four binary bits such that the total number of one’s
should be even.
void main()
{
int bit[5],j,c=0;
clrscr();
printf(“\n Enter four bits :”);
for(j=0;j<4;j++)
{
scanf(“%d”,&bit[j]);
if(bit[j]==1)
c++;
else
if(bit[j]>1 || bit[j]<0)
{
j–-;
continue;
}
}
if(c%2==0)
bit[j]=0;
else
bit[j]=1;
printf(“\n Message bits together with parity bit :”);
for(j=0;j<5;j++)
printf(“%d”,bit[j]);
}
OUTPUT:
Enter four bits : 1 1 1 1
Message bits together with parity bit : 11110
Explanation:
In the above program, the four binary bits are entered through the keyboard. If the number of
one’s entered is even, then the fifth bit is set to 0 otherwise to 1. This is checked by the if
statement.
6.44 Write a program to convert a binary to decimal number. Enter the binary bits by using the
for loop.
#include <process.h>
void main()
{
int a,b,z[10],i;
clrscr();
printf(“\nEnter the number of bits:-”);
scanf(“%d”,&b);
printf(“\nEnter the binary bits:-”);
for(i=0;i<b;i++)
scanf(“%d”,&z[i]);
a=z[0];
for(i=0;i<(b-1);i++)
{
a=a*2+z[i+1];
printf(“\n%d”,a);
}
printf(“\nDecimal Number is : %d”,a);
getche();
}
OUTPUT:
Enter the number of bits:- 5
Enter the binary bits:- 1 0 0 0 1
2
4
8
17
Decimal Number is : 17
Explanation:
In the above program, the number of binary bits is entered. Using this number, individual bits
are entered through the keyboard. For this for loop is used. The first element of the array is
assigned to variable ‘a’. The logic used here is to multiply by 2 to the variable ‘a’ and add the
next successive bit. For this the equation a=a*2+z[i+1]; is used. The number of iterations
to be carried out is equal to the number of binary bits minus one. Here, five bits are initialized,
hence the number of iterations will be four.
Table 6.5 gives the truth table of logic gates AND, OR and EX-OR.
Table 6.5 Logic gates truth table of AND, OR and EX-OR
Outputs
Inputs
AND Gate OR Gate EX-OR Gate
A B C C C
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
6.45 Write a program to verify the truth table of AND Gate. Assume AND Gate has two input
bits A and B and one output bit C.
void main()
{
int x,a[4],b[4],c[4];
clrscr();
printf(“Enter Four Bits :”);
for(x=0;x<4;x++)
{
scanf(“%d”,&a[x]);
if(a[x]>1 ||a[x]<0)
{
x–-;
continue;
}
}
printf(“Enter Four Bits :”);
for(x=0;x<4;x++)
{
scanf(“%d”,&b[x]);
if(b[x]>1 ||b[x]<0)
{
x–-;
continue;
}
}
printf(“\nA B C”);
for(x=0;x<4;x++)
{
if(a[x]==1 && b[x]==1)
c[x]=1;
else
c[x]=0;
printf(“\n%d %d %d”,a[x],b[x],c[x]);
}
}
OUTPUT:
Enter Four Bits: 1 0 1 0
Enter Four Bits: 1 0 0 1
A B C
1 1 1
0 0 0
1 0 0
0 1 0
Explanation:
The four binary bits for A and B are entered. The if statement checks the bits of A and B. If both
of them are 1 then the output ‘C’ must be 1, otherwise for all other conditions the output is 0.
void main()
{
int x,a[4],b[4],c[4];
clrscr();
printf(“Enter Four Bits :”);
for(x=0;x<4;x++)
{
scanf(“%d”,&a[x]);
if(a[x]>1 ||a[x]<0)
{
x–-;
continue;
}
}
printf(“Enter Four Bits :”);
for(x=0;x<4;x++)
{
scanf(“%d”,&b[x]);
if(b[x]>1 ||b[x]<0)
{
x–-;
continue;
}
}
for(x=0;x<4;x++)
{
if(a[x]==0 && b[x]==0)
c[x]=0;
else
c[x]=1;
printf(“\n%d %d %d”,a[x],b[x],c[x]);
}
}
OUTPUT:
Enter Four Bits: 1 1 1 0
Enter Four Bits: 1 0 0 0
A B C
1 1 1
1 0 1
1 0 1
0 0 0
Explanation:
The four binary bits for A and B are entered. The if statement checks the bits of A and B.
If one of them is at logic 1, then the output ‘C’ must be 1. When the inputs are 0, the output
is also 0.
void main()
{
int x,a[4],b[4],c[4];
clrscr();
printf(“Enter Four Bits :”);
for(x=0;x<4;x++)
{
scanf(“%d”,&a[x]);
if(a[x]>1 ||a[x]<0)
{
x–-;
continue;
}
}
printf(“Enter Four Bits :”);
for(x=0;x<4;x++)
{
scanf(“%d”,&b[x]);
if(b[x]>1 ||b[x]<0)
{
x–-;
continue;
}
}
printf(“\nA B C”);
for(x=0;x<4;x++)
{
if(a[x]==0 && b[x]==1)
c[x]=1;
else
if(a[x]==1 && b[x]==0)
c[x]=1;
else
c[x]=0;
printf(“\n%d %d %d”,a[x],b[x],c[x]);
}
}
OUTPUT:
Enter Four Bits: 1 1 1 0
Enter Four Bits: 1 0 0 0
A B C
1 1 0
1 0 1
1 0 1
0 0 0
Explanation:
The four binary bits for A and B are entered. The if statement checks the bits of A and B. If
the input bits are dissimilar the output ‘C’ must be 1. When the inputs are similar, the output
is also 0. In the two extreme cases, the output is zero.
6. 48 Write a program to find the Hamming code for the entered binary code. Assume the binary
code of four bits in length. The Hamming code should be seven bits.
Tip: R.W. Hamming developed error correcting and detecting codes in communication the four
bits data which is to be transmitted containing additional three check bits. The word that is to be
transmitted, its format, will be D7, D6, D5, P4, D3, P2 and P1. Where D bits are data bits and the
P bits are parity bits. P1 is set so that it provides even parity over bits P1, D3, D5 and D7. P2 is set
for even parity over bits P2, D3, D6 and D7. P4 is set for even parity over bits P4, D5, D6 and D7
void main()
{
static int c[7];
int x,b[4];
clrscr();
printf(“\n Read the Binary Numbers :”);
for(x=0;x<4;x++)
scanf(“%d”,&b[x]);
/* piece copy operation */
c[0]=b[0];
c[1]=b[1];
c[2]=b[2];
c[4]=b[3];
printf(“\n Before XOR operation :”);
for(x=0;x<=6;x++)
printf(“%3d”,c[x]);
c[6]= c[0]^c[2]^c[4];
c[5]= c[0]^c[1]^c[4];
c[3]= c[0]^c[1]^c[2];
printf(“\n Hamming code after XOR operation :”);
for(x=0;x<=6;x++)
printf(“%3d”,c[x]);
getche();
}
OUTPUT:
Read the Binary Numbers : 1 0 1 0
Before XOR operation : 1 0 1 0 0 0 0
Hamming code after XOR operation : 1 0 1 0 0 1 0
Explanation:
The hamming code that contains seven bits is initially assumed as zeros. This is declared
with static int c[7]. The four bit data is read through the keyboard using the first
for loop. The data bits are placed at the appropriate positions using piece copy operations.
The three parity bits are evaluated using XOR bitwise operations. Ultimately, the seven bits
are displayed using the last for loop.
6.49 Write a program to show the results of students who appeared in the final examination.
Assume that the students have to appear in six subjects. The result declared should be as per
the following table.
Total Marks Result
>=420 Distinction
>=360 First Division
>=240 Second Division
Otherwise Fail
Explanation:
In the above program, the number of students whose result is to be calculated is entered.
After this, the marks of six subjects with their roll numbers are entered. The sum of six
subjects is calculated. The sum is compared with distinction, first and second macros using
if–else ladder and appropriate result is displayed.
In this program, macros are used. During preprocessing, the preprocessors replace every occur-
rence of distinction with 420, similarly, first and second are replaced with 360 and 240, respectively.
Distinction, first and second in the above program are ‘macro templates’, whereas 420, 360 and 240
are called their corresponding macro expansions. For details of macros refer to Chapter 12.
while(test condition)
{
body of the loop
}
The test condition is indicated at the top and it tests the value of the expression before processing
the body of the loop. The test condition may be any expression. The loop statements will be executed
till the condition is true, i.e. the test condition is evaluated and if the condition is true, then the body
of the loop is executed. When the condition becomes false the execution will be out of the loop.
The execution of the loop can be followed by the following flow chart given in Figure 6.5.
Entry
Initialize
Figure 6.5 The flow chart showing the execution of the loop
Here, the block of the loop may contain either a single statement or a number of statements. The
same block can be repeated.
The braces are needed only if, the body of the loop contains more than one statement. However,
it is good practice to use braces even if the body of the loop contains only one statement.
6.50 Write a program to print the string ‘You have learnt C program’ nine times using
while loop.
void main()
{
int x=1;
while(x<10)
{
printf(“\n You have learnt C program”);
x++;
}
}
OUTPUT:
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
Explanation:
The parentheses after ‘while’ contains a condition. As long as the condition remains true,
all the statements within the body of the loop get executed repeatedly. The variable ‘x’ is
initialized to 1. The compiler checks the condition and after satisfying it, the body of the
loop is executed. The control then goes to the while loop. Next time, the value of ‘x’ is
incremented by 1. Now if ‘x’ is 2 again it satisfies the condition and the body of the loop
gets executed. This process is continued till the value of ‘x’ reaches 9. When the condition
becomes false (after 9), the control passes to the first statement that follows the body of the
while loop and the program is now terminated. The output of the program is shown above.
6.51 Write a program to add 10 consecutive numbers starting from 1. Use the while loop.
void main()
{
int a=1,sum=0;
clrscr();
while(a<=10)
{
printf(“%3d”,a);
sum=sum+a;
a++;
}
printf(“\n Sum of 10 numbers :%d”,sum);
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10
Sum of 10 numbers : 55
Explanation:
In the above program, integer variable ‘a’ is initialized to 1 and variable ‘sum’ to 0.
The while loop checks the condition for a≤10. The variable ‘a’ is added to variable
‘sum’ and each time ‘a’ is incremented by 1. In each while loop ‘a’ is incremented
and added to ‘sum’. When the value of ‘a’ reaches 10, the condition given in while
loop is false. At last the loop is terminated. The sum of the number is displayed.
6.52 / 6.53 Write a program to calculate factorial of a given number. Use while loop.
void main()
{
int a,fact=1;
clrscr();
printf(“\n Enter The Number :”);
scanf(“%d”, &a);
while(a>=1)
{
printf(“ %d *”,a);
fact=fact*a;
a–-;
}
printf(“ = %d”,fact);
printf(“\n Factorial of Given number is %d”,fact);
}
OUTPUT:
Enter The Number: 5
5* 4 * 3 * 2 * 1 * = 120
Factorial of Given number is 120
Explanation:
In the above program, the working of the while loop is the same as that in the previous
one. The only difference is that variable ‘a’ is decremented. Factorial of a number means
a product from 1 to that number. Here, variable ‘fact’ is initialized to 1. For each itera-
tion of while loop the entered number is multiplied with the previous value of the variable
‘fact’ and ‘a’ is decremented. When the entered number ‘a’ reaches 1, the while
loop terminates and ‘fact’ variable contains the product of 1 to the entered number. Here,
the entered number is 5 and its factorial value is 120, and the same is displayed.
OR
void main()
{
int a,b=1,fact=1;
clrscr();
printf(“\n Enter The Number :”);
scanf(“%d”, &a);
while(b<=a)
{
printf(“ %d *”,b);
fact=fact*b;
b++;
}
printf(“ = %d”,fact);
printf(“\n Factorial of %d is %d”,b-1,fact);
}
OUTPUT:
Enter the Number: 4
1 * 2 * 3 * 4 * = 24
Factorial of 4 is 24.
Explanation:
The working of the above program is the same as the last one. Here, we declared and initial-
ized one more variable ‘b’ to 1. Here, we are keeping the variable ‘a’ unchanged. We
require an extra variable to count the number of loops completed by the while loop. Once
the value of the variable ‘b’ matches with the entered number ‘a’, the while loop termi-
nates. The factorial of a number in variable ‘fact’ is displayed.
6.54 Write a program to convert decimal number to binary number.
void main()
{
int x,y=40;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”,&x);
printf(“\n Binary Number :”);
while(x!=0)
{
gotoxy(y–-,3);
printf(“%d”,x%2);
x=x/2;
}
}
OUTPUT:
Enter a Number : 25
Binary Number : 11001
Explanation:
In the above program, the number, which is to be converted into binary, is entered through
the keyboard. The while loop is executed till the value of ‘x’ becomes non-zero. The
body of the while loop contains the mod (%) and divide operations. With these opera-
tions, remainders are obtained and the value of ‘x’ is reduced to half. Binary bits corre-
sponding to the decimal number which are obtained are taken in the reverse order by using
the gotoxy() function. In the statement gotoxy (y––, 3), the first argument (y––)
provides the column position and the second provides the row number where the output is
to be displayed.
Similarly, for conversion of decimal to octal instead of 2 one can use 8 for mod as well as division
operations.
6.55 Write a program to convert decimal number to the user-defined number system. The base of
the number system may be taken up to 9.
void main()
{
int m,b,y=35;
clrscr();
printf(“Enter the Decimal Number :”);
scanf(“%d”,&m);
printf(“Enter base of number System :”);
scanf “%d”,&b);
printf(“The Number Obtained :”);
while(m!=0)
{
gotoxy(y–-,3);
printf(“%d”,m%b);
m=m/b;
}
getche();
}
OUTPUT:
Enter the Decimal Number : 50
Enter base of number System : 5
The Number Obtained : 200
Explanation:
The logic of the above program is the same as explained in the previous program. The only
difference is that the user has a choice to enter the base of any number system. This program
is more flexible than the previous one.
6.56 Write a program to convert binary number to equivalent decimal number.
# include <math.h>
# include <process.h>
void main()
{
long n;
int x,y=0,p=0;
clrscr();
printf(“\n Enter a Binary Number :”);
scanf(“%ld”,&n);
while(n!=0)
{
x=n%10;
if(x>1 || x<0)
{
printf(“\n Invalid Digit.”);
exit(1);
}
y=y+x*pow(2,p);
n=n/10;
p++;
}
printf(“\n Equivalent Decimal Number is %d.”,y);
getche();
}
OUTPUT:
Enter a Binary Number : 1111
Equivalent Decimal Number is 15
Enter a Binary Number : 120
Invalid Digit.
Explanation:
In the above program, binary number is entered. The equation y=y+x*pow (2,p) is used in
each iteration where ‘y’ is initialized to 0. The variable ‘x’ is obtained by mod operation
which separates individual digit of entered number, and the variable ‘p’ acts as an exponent for
base 2. It is initially zero and incremented by one in each iteration, where p varies from 0 to the
number of digits −1. The product (x*pow (2,p)) is added with the previous value of ‘y’.
6.57 Write a program to read a positive integer number ‘n’ and generate the numbers in the follow-
ing way. If entered number is 5, the output will be as follows. OUTPUT: 5 4 3 2 1 0 1 2 3 4 5.
# include <math.h>
void main()
{
int n,i,k=0;
clrscr();
printf(“Enter a number :”);
scanf(“%d”,&n);
i=n+1;
k=k-n;
while(i!=k)
{
printf(“%3d”,abs(k));
k++;
}
}
OUTPUT:
Enter a number : 3
3 2 1 0 1 2 3
Explanation:
The value of ‘n’ is entered through the keyboard. The variable ‘k’ is initially declared zero.
The equation k=k-n i.e. k=0-n=-n. The value of ‘k’ is negative, hence abs() function is
used to print the positive (absolute) value. The while loop checks the condition for(i!=k).
Variable ‘k’ is printed and incremented till its value becomes n+1. In this way, the numbers
are printed as asked in the problem.
6.58 Write a program to enter a number through keyboard and find the sum of its digits.
void main()
{
int n,k=1,sum=0;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”,&n);
while(n!=0)
{
k=n%10;
sum=sum+k;
k=n/10;
n=k;
}
printf(“Sum of digits %d “,sum);
}
OUTPUT:
Enter a Number : 842
Sum of digits 14
Explanation:
In the above program, a number is entered by the user. It is assigned to variable ‘n’. In
the while loop mod and division operations are done on the entered number. At each
rotation of while loop, the remainder is obtained and added to the variable ‘sum’. The
original number is also reduced by the division operation. Due to continuos division, at
one stage the entered number reduces to zero. At this stage, the while loop condition
mismatches and is terminated. The variable ‘sum’ displays the ‘sum’ of all digits of the
entered number.
6.59 Write a program to enter few numbers and count the positive and negative numbers together
with their sums. When 0 is entered program should be terminated.
void main()
{
int j=1,p=0,n=0,s=0,ns=0;
clrscr();
printf(“\n Enter Numbers (0) Exit :”);
while(j!=0)
{
scanf(“%d”,&j);
if(j>0)
{
p++;
s=s+j;
}
else if(j<0)
{
n++;
ns=ns+j;
}
}
printf(“\n Total Positive Numbers : %d”,p);
printf(“\n Total Negative Numbers : %d”,n);
printf(“\n Sum of Positive Numbers : %d”,s);
printf(“\n Sum of Negative Numbers : %d”,ns);
}
OUTPUT:
Enter Numbers (0) Exit :1 2 3 4 5 -5 -4 -8 0
Total Positive Numbers : 5
Total Negative Numbers : 3
Sum of Positive Numbers : 15
Sum of Negative Numbers : -17
Explanation:
Numbers are entered through the keyboard. The if statement checks whether the entered
numbers are greater or less than zero. If the numbers are greater than zero the if block is
executed otherwise the else block is executed. The output shows the number of positive
and negative numbers and their sums. When 0 is entered while loop terminates.
6.60 Read an integer through the keyboard. Sort odd and even numbers by using while loop.
Write a program to add the sum of odd and even numbers separately and display the results.
void main()
{
int a,c=1,odd=0,even=0;
float b;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”, &a);
printf(“ODD EVEN”);
printf(“\n”);
while(c<=a) /* A
{
b=c%2;
while(b==0){/* B
printf(“\t%d “,c);
even=even+c;
b=1;}
b=c%2;
while(b!=0){ /*c
printf(“\n%d”,c);
odd=odd+c;
b=0;}
c++;
}
printf(“\n===============”);
printf(“\n%d %d”,odd,even);
}
OUTPUT:
Enter a Number: 10
ODD EVEN
1 2
3 4
5 6
7 8
9 10
==========
25 30
Explanation:
The above program is an example of nested while loops. When the entered number is even
the first loop (B loop) is executed and number is added to variable ‘even’, otherwise the
while loop (C loop) is executed and the same job of addition is done with variable ‘odd’.
Thus, variables ‘odd’ and ‘even’ give the sum of even and odd numbers.
6.61 Write a program to print the entered number in the reversed order.
void main()
{
int n,d,x=1;
int i;
clrscr();
printf(“Enter the number of digits :-”);
scanf(“%d”,&d);
printf(“\nEnter the number which is to be reversed:-”);
scanf(“%d”,&n);
printf(“\nThe Reversed Number is :-”);
while(x<=d)
{
i=n%10;
printf(“%d”,i);
n=n/10;
x++;
}
getche();
}
OUTPUT:
Enter the number of digits :- 4
Enter the number which is to be reversed:- 5428
The Reversed Number is :- 8245
Explanation:
The statements following the while loop are i=n%10 and n=n/10. They provide the
remainder and quotient values, respectively. By taking repeatedly remainders and quotients,
we get the number in the reverse order. For repeating the loop the ‘x’ is to be incremented.
6.62 Write a program to enter a statement entering a combination of capital, lower case, symbols
and numerical. Carry out separation of capitals, lower case, symbols and numerical by using
ASCII values from 48 to 122.
# include <ctype.h>
void main()
{
static char scan[40],cap[20],small[20],num[20],oth[20];
int i=0,c=0,s=0,h=0,n=0;
clrscr();
puts(“Enter Text Here :\n”);
gets(scan);
while(scan[i]!=‘\0’)
{
if(scan[i]>=48 && scan[i]<=57)
num[++n]=scan[i];
else
if(scan[i]>=65 && scan[i]<=90)
cap[++c]=scan[i];
else
if(scan[i]>=97 && (scan[i]<=122))
small[++s]=scan[i];
else
oth[++h]=scan[i];
i++;
}
printf(“\nCapital Letters :[”);
for(i=0;i<20;i++)
printf(“%c”,cap[i]);
printf(“]\nSmall Letters :[”);
for(i=0;i<20;i++)
printf(“%c”,small[i]);
printf(“]\nNumaric Letters :[”);
for(i=0;i<20;i++)
printf(“%c”,num[i]);
printf(“]\nOther Letters :[”);
for(i=0;i<20;i++)
printf(“%c”,oth[i]);
printf(“]”);
getche();
}
OUTPUT:
Enter Text Here: HAVE A NICE DAY, contact me on 51606.
Capital Letters: [HAVEANICEDAY]
Small Letters : [contactmeon]
Numaric Letters : [28669]
Other Letters: [,]
Explanation:
The array scan[40] contains the string. The string is to be entered by the user. The arrays
small[20], num[20] and oth[20] are used at run time in the program. The while loop
reads the array scan[] character by character. The if–else ladder statements check
the characters, whether the character is small, capital or symbol, and assigns it to the different
arrays according to its case or type.
6.63 /6.64 Write a program to sort numbers 0 to 9, alphabets in upper and lower case using
equivalent ASCII values. The following table can be used.
ASCII values Corresponding Symbols
48 to 57 0 to 9
65 to 90 A to Z
97 to 120 a to z
void main()
{
char a;
int i=48;
clrscr();
printf(“NUMBERS \n”);
while(i<=57)
{
printf(“%c”,i);
i++;
}
i+=7;
printf(“\n\n CAPITAL ALPHABETS\n”);
while(i<=90)
{
printf(“ %c”,i);
i++;
}
i+=6;
printf(“\n\n SMALL ALPHABETS \n”);
while(i<=122)
{
printf(“%c”,i);
i++;
}
}
OUTPUT:
NUMBERS
0 1 2 3 4 5 6 7 8 9
CAPITAL ALPHABETS
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
SMALL ALPHABETS
a b c d e f g h i j k l m n o p q r s t u v w x y z
Explanation:
In the above program, three while loops are used. These three while loops are used for
sorting numbers, capital letters and lowercase letters. The variable ‘i’ is initialized to 48
because the ASCII 48 is ‘0’. The three while loops check ASCII values as per the ranges
given in the table. The number, capital and small letters are not continuous in ASCII. Some
symbols are also present between these values. To ignore these symbols, variable ‘i’ is
increased twice with 7 and 6.
OR
#include <process.h>
void main()
{
int i=48;
clrscr();
printf(“Numbers :”);
while(i<124)
{
if(i<58)
printf(“%2c”,i);
else
{
if(i==58)
{
printf(“\nCapital Letters :”);
i+=7;
}
if(i>64 && i<91)
printf(“%2c”,i);
if(i==90)
{
printf(“\n Small Letters :”);
i+=7;
}
if(i>96 && i<123)
printf(“%2c”,i);
}
i++;
}
}
Explanation:
The output of the above program is the same as for the previous one. Instead of nested
while loop, nested if–else statements are used.
6.65 Write a program to use three while nested loops. Print numbers after each iteration and
messages after termination of each loop.
void main()
{
int i=1,j=1,k=1;
clrscr();
while(i<4)
{
while(j<3)
{
while(k<2)
{
printf(“\n\n i=%d j=%d k=%d”,i,j,k);
k++;
}
printf(“\n Inner Loop (k) Completed.”);
k=1;
j++;
}
printf(“\n Middle Loop (j) Completed.”);
j=1;
i++;
}
printf(“\n Outer Loop (i) Completed.”);
}
OUTPUT:
i=1 j=1 k=1
Inner Loop (k) Completed.
i=1 j=2 k=1
Inner Loop (k) Completed.
Middle Loop (j) Completed.
i=2 j=1 k=1
Inner Loop (k) Completed.
i=2 j=2 k=1
Inner Loop (k) Completed.
Middle Loop (j) Completed.
i=3 j=1 k=1
Inner Loop (k) Completed.
i=3 j=2 k=1
Explanation:
In the above program, variables i, j and k are declared and initialized to 1. The inner most loop
is ‘k’, the middle is ‘j’ and the outer most is ‘i’. The execution of loop starts from outer to
inner and the completion will be from inner most to the outer most. Here, for example, the values
of i, j and k are printed and messages are printed to understand the termination of loops.
do
{
statement/s;
}
while(condition);
The difference between the while and do-while loop is the place where the condition is to be
tested. In the while loops the condition is tested following the while statement, and then the body gets
executed, whereas in the do-while the condition is checked at the end of the loop. The do-while loop
will execute at least one time even if the condition is false initially. The do-while loop executes until the
condition becomes false. The comparison between the while and do-while loop is given in Table 6.6
Some programs are given on do-while loop.
6.66 Use the do–while loop and display a message ‘this is a program of do–while loop’ five
times.
void main()
{
int i=1;
clrscr();
do
{
Explanation:
The body of the loop is executed and the value of ‘i’ is incremented. The incremented value
is tested with the condition specified at the outside of the loop. If the condition is true the
statement within the loop gets executed. In the above program, the statement within the loop
gets executed five times and the result is as shown above.
6.67 Write a program to print the entered number in the reversed order. Use do-while loop.
Also perform sum and multiplication with their digits.
void main()
{
int n,d,x=1,mul=1,sum=0;
int i;
clrscr();
printf(“Enter the number of digits :-”);
scanf(“%d”,&d);
printf(“\nEnter the number which is to be reversed:-”);
scanf(“%d”,&n);
printf(“\n Reversed Number :-”);
do
{
i=n%10;
printf(“%d”,i);
sum=sum+i;
mul=mul*i;
n=n/10;
x++;
}
while(x<=d);
printf(“\n Addition of digits :- %4d”,sum);
printf(“\n Multiplication of digits :- %4d”, mul);
getche();
}
OUTPUT:
Enter the number of digits : 4
Enter the number which is to be reversed:- 4321
Explanation:
In the above program, the length of the number and a number are entered. Using repetitive mod
operations, digits are separated and displayed. The separated digits are repeatedly added and
multiplied with variables ‘sum’ and ‘mul’, respectively. Initially ‘sum’ is 0 and ‘mul’
is 1. After the termination of loop ‘sum’ and ‘mul’ display addition and multiplication of
individual digits of the entered number.
6.68 Write a program to find the cubes of 1 to 10 numbers using do–while loop.
Explanation:
Here, the mathematical function pow (x, 3) is used. Its meaning is to calculate the third
power of x. With this function, we get the value of y=x3. For the use of the pow() function,
we have to include math.h header file.
6.69 Write a program to check whether the given number is prime or not?
void main()
{
int n,x=2;
clrscr();
printf(“Enter The number for testing (prime or not) :”);
scanf(“%d”,&n);
do
{
if(n%x==0)
{
printf(“\n The number %d is not prime.”,n);
getch();
exit(0);
}
x++;
}
while(x<n);
printf(“\n The number %d is prime.”,n);
getche();
}
OUTPUT:
Enter The number for testing (prime or not) : 5
The number 5 is prime.
Explanation:
The number is said to be a prime number, if it is not divisible by any number starting
from 2 onwards up to n-1, where ‘n’ is the entered number by the user. Here, in this
example, the entered number is 5. The mod operation is performed using the divisor from
2 to n-1 (5−1).
If the remainder is 0 then it is not a prime number and controls exit from the program. Otherwise,
if the remainder is non-zero then the number is prime.
6.70 Write a program to count the number of students having age less than 25 and weight less
than 50 kg out of five.
void main()
{
int age,count=0,x=1;
float wt;
clrscr();
printf(“\nEnter data of 5 boys\n”);
printf(“\nAge Weight\n”);
do
{
scanf(“%d %f”, &age, &wt);
if( age<25 && wt<50)
{
count++;
}
x++;
}
while(x<=5);
printf(“\n Number of boys with age <25”);
printf(“and weight <50 Kgs =%d\n”,count);
getch();
}
OUTPUT:
Enter data of 5 boys
Age Weight
24 51
20 45
25 51
20 35
24 54
Number of boys with age <25 and weight <50 kgs = 2
Explanation:
In the above-given program, age and weight of five boys are entered. The if condition
checks the age and weight and after satisfying the condition counter variable count is in-
creased by one. Thus, loop executes five times. The program displays the number of students
having ages less than 25 years and weight less than 50 kg.
6.71 Compute the factorial of a given number using the do–while loop.
void main()
{
int a,fact=1;
clrscr();
printf(“\n Enter The Number :”);
scanf(“%d”, &a);
do
{
printf(“ %d *”,a);
fact=fact*a;
a- -;
}
while(a>=1);
printf(“ = %d”,fact);
printf(“\n Factorial of Given number is %d”,fact);
}
OUTPUT:
Enter The Number : 5
5 * 4 * 3 * 2 * 1 * = 120
Factorial of Given number is 120.
Explanation:
The logic of the program is self-explanatory.
6.72 Write a program to evaluate the series such as 1+2+3+. . . i. Use do–while loop. Where
i can be a finite value. Its value should be read through the keyboard.
void main()
{
int i,a=1;
int s=0;
clrscr();
printf(“\n Enter a number:”);
scanf(“%d”,&i);
do
{
printf(“%d +”,a);
s=s+a;
a++;
}
while(a<=i);
printf(“\b\bs=%d”,s);
}
OUTPUT:
Enter a number: 5
1 + 2 + 3 + 4 +5 s= 15
Explanation:
In the above program, variable ‘a’ is initially 1 and ‘s’ is 0. The value of variable ‘i’
is read which determines the final step of the series. In the do-while loop variable ‘a’ is
printed, added to variable ‘s’ and then incremented. This loop is continuously executed till
‘a’ equals the entered number ‘i’. The output provides the summation of 1 to the entered
number. Here, the entered number is 5. Hence, the sum from 1 to 5 is 15.
{
statement/s;
}
while(condition);
6.73 Write a program to use while statement in do–while loop and print values from 1 to 5.
void main()
{
int x=0;
clrscr();
do while(x<5)
{
x++;
printf(“\t %d”,x);
}
while(x<1);
}
OUTPUT:
1 2 3 4 5
Explanation:
The specialty of using the second while loop in the above program is to know that the
programmer can take the second while loop.
suMMArY
This chapter deals with the loops that are to be used in the C programs. The scope of the various three
loops such as (i) the for loop, (ii) the while loop and (iii) the do-while has been narrated in
detail in this chapter. In this chapter the numbers of solved programs on these loops have been given
for the benefit of the programmers. Also examples on nested loops have been given in a simple lan-
guage and in depth. The information on breaking the loop and continuing the same is also elaborated
in detail together with examples.
eXercIses
I True or false:
1. A loop repeatedly executes a block of statements 3. The for(; ;) loop with no arguments can be
for certain number of times. executed.
2. The loop for(; ;) is a non-working loop. 4. The loop for(a=1;a<20;a++) will be executed
for 20 times.
III Select the appropriate option from the multiple choices given below:
1. What will be the last value of ‘c’ after the (a) x=1
execution of following program? (b) x=0
void main() (c) x=1.1
{ (d) None of the above
int c=1,d=0;
clrscr(); 3. What will be the value of ‘f’ after the execution of
while(d<=9) following program?
{
printf(“\n %d %d”,++d,++c); void main()
} {
} char k;
(a) 11 float f=65;
(b) 10 clrscr();
(c) 12 for(k=1;k<=10;k++)
(d) 9 {
f-=.1;
2. What will be the value of ‘x’ after the execution
of following program? }
printf(“\nf=%g”,f);
void main()
{ }
int k; (a) f=64
float x=0;
clrscr(); (b) f=-65
for(k=0;k<10;k++) (c) f=66
x+=.1; (d) None of the above
printf(“\nx=%g”,x);
}
1. Write a program to display alphabets as given 6. Write a program to find the total number of votes in
below. favour of persons ‘A’ and ‘B’. Assume 100 voters
Az by cx dw ev fu gt hs Ir jq kp lo mn nm ol pk will be casting their votes to these persons. Count
qj ri sh tg uf ve wd xc yb za. the number of votes gained by ‘A’ and ‘B’. User can
enter his/her choices by pressing only ‘A’ or ‘B’.
2. Write a program to display count values from
0 to 100 and flash each digit for one second. Reset 7. Write a program to pass the resolution in a meeting
the counter after it reaches to hundred. The proce- comprising of five members. If three or more votes
dure is to be repeated. Use for loop. are obtained the resolution is passed otherwise
rejected.
3. Develop a program to simulate seconds in a
clock. Put the 60 dots on the circle with equal dis- 8. Assume that there are 99 voters voting to a
tance between each other and mark them 0 to 59. person for selecting chairman’s candidature.
A second’s pointer is to be shown with any symbol. If he secures more than 2/3 votes he should be
Also print the total number of revolution made by declared as chairman otherwise his candidature will
second’s pointer. be rejected.
4. Write a program to simulate analog watch 9. Write a program to display the numbers of a series
(1 to 12 numbers to be arranged in circular fashion 1, 3, 9, 27, 81. . . . n by using the for loop.
with all the three pointers for seconds, minutes, and
10. Write a program to check that entered input data
hours) on the screen. Use nested for loops.
for the following. Whenever input is non-zero or
(a) Use (.) dot for second’s pointer. positive display numbers from 1 to that number,
(b) Use (*) star for minute’s pointer. otherwise display message ‘negative or zero’. The
(c) Use (#) hash for hour’s pointer. program is to be performed for 10 numbers.
5. Write a program to calculate the sum of first and 11. Write a program to check entered data types for
last number from 1 to 10. 10 times. If a character is entered print ‘Character
(Example 1+10,2+9, 3+8 sums should be is entered’ otherwise ‘Numeric is entered’ for
always 11.) numerical values.
12. Write a program to find the sum of the first hundred (a) a+1+b+2+c+3. . . .n, where n is an integer.
natural numbers. (1+2+3+ . . . +100). (b) z+y+x. . .+a.
(c) za+yb+xc. . .+az.
13. Write a program to display numbers 11, 22, 33. . . , 99
using ASCII values from 48 to 57 in loops. 24. Enter the 10 numbers through the keyboard and
sort them in ascending and descending order,
14. Create an infinite for loop. Check each value of using do-while loop.
the for loop. If the value is odd, display it other-
wise continue with iterations. Print even numbers 25. Enter text through the keyboard and display it in
from 1 to 100. Use break statement to terminate the reverse order. Use do-while loop.
the program.
26. Print multiplication of digits of any number.
15. Write a program to show the display as a Fox example number 235, multiplication to be
rectangle of characters as shown below. 5 3 2 = 30. Use do-while loop.
27. Print square roots of each digit of any number.
Z Consider each digit as perfect square. For
YZY example, for 494 the square roots to be printed
XYZYX should be 2 3 2.
RXYZYXR
28. Write a program to read a positive integer
XYZYX
number ‘n’ and generate the numbers in the
YZY
following way. If entered number is 3 the output
Z
will be as follows.
16. Write a program to read 10 numbers through the
(a) 9 4 1 0 1 4 9
keyboard and count number of positive, negative
(b) 9 4 1 0 1 2 3
and zero numbers.
29. Write a program to enter two integer values
17. Write a nested for loop that prints a 5 × 10
through the keyboard. Using while loop, per-
pattern of 0s.
form the product of two integers. In case product
18. Is it possible to create a loop using the goto is zero (0), loop should be terminated otherwise
statement? If yes write the code for it. loop will continue.
19. Write a program to find the triangular number 30. Write a program to enter a single character either
of a given integer. Fox example triangular of 5 is in lower or uppercase. Display its correspond-
(1+2+3+4+5) 15. Use do–while loop. ing ASCII equivalent number. Use the while
loop for checking ASCII equivalent numbers for
20. Write a program to display all ASCII numbers
different characters. When capital ‘E’ is pressed,
and their equivalent characters numbers and
the program should be terminated.
symbols. Use do–while loop. User should
prompt every time to press ‘Y’ or ‘N’. If user 31. Write a program to read a positive integer number
presses ‘Y’ display next alphabet otherwise ‘n’ and generate the numbers in the following
terminate the program. way. If entered number is 4 the output will be as
follows. OUTPUT: 4! 3! 2! 1! 0 1! 2! 3! 4! 5!.
21. Accept any five two numbers. If the first number
is smaller than the second then display sum of 32. Write a program to read a positive integer
their squares, otherwise sum of cubes. number ‘n’ and generate the numbers in the
different ways as given below. If the entered
22. Evaluate the following series. Use do-while
number is 4 the output will be as follows.
loop.
(a) 2 4 6 8 10 . . . n (provided n is even).
(a) 1+3+5+7. . . . n(b) 1+4+25+36 . . . n
(b) 1 3 5 7 9. . . . n (provided n is odd).
(c) x+x2/2!+x3/3!+ . . n
(d) 1+x+x2+x3+. . . . xn 33. Write a program to read a positive integer
number ‘n’ and perform the squares of individual
23. Write a program to display the following, using
digits. For example n=205 then the output will be
do-while loop.
25 0 4.
AnsWers
I True or false:
Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.
1. T 2. F 3. T 4. F 5. T
6. F 7. T 8. T 9. T 10. T
1.
Q. Ans. Q. Ans. Q. Ans.
1. C 2. A 3. B
2.
Q. Ans. Q. Ans. Q. Ans.
1. B 2. C 3. A
III Select the appropriate option from the multiple choices given below:
7 Data Structure:
Array
Chapter Outline
7.1 Introduction
7.2 Array Declaration
7.3 Array Initialization
7.4 Array Terminology
7.5 Characteristics of an Array
7.6 One-Dimensional Array
7.7 One-Dimensional Array and Operations
7.8 Operations with Arrays
7.9 Predefined Streams
7.10 Two-Dimensional Array and Operations
7.11 Three- or Multi-Dimensional Arrays
7.12 The sscanf() and sprintf() Functions
7.13 Drawbacks of Linear Arrays
7.1 Introduction
An array is a very popular and useful data structure used to store data elements in successive memory
locations. More than one element is stored in a sequence, so it is also called a composite data structure.
An array is a linear and homogeneous data structure. An array permits homogeneous data. It means
that similar types of elements are stored contiguously in the memory and that too under one variable
name. It can be combined with a non-homogeneous structure, and a complex data structure can be
created. We know that an array of structure objects can also be useful. An array can be declared of any
standard or custom data type. The array of character (strings) type works somewhat differently from
an array of integers, floating numbers.
Consider the following example. A variable a having data-type integer is initially assigned some
value and later on its value is changed. Later assigned value to the variable can be displayed.
void main()
{
int a=2;
a=4;
printf(“%d”,a);
}
OUTPUT:
4
In the above example, the value of a printed is 4. 2 is assigned to ‘a’ before assigning 4 to it. When
we assign 4 to a then the value stored in ‘a’ is replaced with the new value. Hence, ordinary variables
are capable of storing one value at a time. This fact is the same for all the data types. But in numerous
applications variables must be assigned more than one value. This can be obtained with the help of
arrays. An array variable allows the storing of more similar data type elements/values at a time.
Here, five elements are stored in an array ‘a’. List Table 7.1 Calling array elements
of elements initialized is shown within the braces. a[0] refers to 1st element i.e. 1
The array elements are stored sequentially in sepa-
a[1] refers to 2nd element i.e. 2
rate locations. Then, the question arises how to call
individually to each element from this bunch of inte- a[2] refers to 3rd element i.e. 3
ger elements. Reading of the array elements begins a[3] refers to 4th element i.e. 4
from ‘0’. By indicating the position of elements, one a[4] refers to 5th element i.e. 5
can retrieve any element of an array. Array elements
are called with array names followed by the element
numbers. Table 7.1 explains the same.
Example:
To store more than one value the programming languages have an in-built data structure called
an array.
1. int num[5];
In the above declaration, an integer array of five elements is declared. Memories for five
integers, i.e. successive 10 bytes, are reserved for the num array. To initialize the num array
following syntax can be used.
2. int num[5] = {1,2,4,2,5};
In the above statement, all elements are initialized. It is also possible to initialize individual
element by specifying the subscript number in the square bracket following the array name.
Array elements are accessed as follows:
num[0]=1;
num[1]=2;
num[2]=4;
num[3]=2;
num[4]=5;
The initialization can be done at the compile time or dynamically at the run time. The above is an example
of compile time initialization. In the statement (2), declaration and
initialization are done at once; in such type of declaration the number
1 num[0]
of elements (five) is not necessary to mention in the square bracket [].
The compiler automatically counts the value initialized and as-
2
sumes the number of elements initialized as the array size.
In the above array, the element num[0] i.e. 1 is the lowest
4
bound and num[4] i.e. 5 is the last element. In C and C++, there
is no bound checking. Hence, the programmer has to check it
2
while accessing or storing elements. Once the array is declared,
its lowest bound cannot be changed but the upper bound can be
expanded. The array name itself is a constant pointer, and there- 5 num[4]
fore we cannot modify it. Storing elements in contiguous memory
locations can expand the upper bound. Figure 7.2 Array of integers
The array name itself is a pointer. The array num is pointer to
the first element i.e. num contains address of memory location where element 1 is stored. The address
stored in the array name is called the base address. Figure 7.2 shows the pictorial representation. To
access individual elements, the following syntax is used.
num[0] refers to the 1
num[1] refers to the 2
num[2] refers to the 4
num[3] refers to the 2
num[4] refers to the 5
Thus, an array is a collection of elements of the same data type, stored in unique and successive
memory locations.
7.5 Characteristics of an Array
1. The Declaration int a[5] is nothing but creation of five variables of integer types in memory.
Instead of declaring five variables for five values, the programmer can define them in an array.
2. All the elements of an array share the same name, and they are distinguished from one an-
other with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other
elements.
int a[5]={1,2,3,4,8};
If a programmer needs to replace 8 with 10, then it need not require changing all other numbers except 8.
To carry out this task, the statement a[4]=10 can be used. Here, other four elements are not disturbed.
5. Any element of an array a[] can be assigned/equated to another ordinary variable or array
variable of its type.
Example:
b= a[2];
a[2]=a[3];
(a) In the statement b=a[2] or vice versa, the value of a[2] is assigned to ‘b’, where ‘b’
is an integer.
(b) In the statement a[2]=a[3] or vice versa, the value of a[2] is assigned to a[3],
where both the elements are of the same array.
(c) The array elements are stored in continuous memory locations.
6. Array elements are stored in contiguous memory locations.
A program on array initialization and determination of their memory locations is given below:
7.1 Write a program to display array elements with their addresses.
int main()
{
int num[5]={1,2,3,2,5};
clrscr();
printf(“\n num[0] = %d Address : %u”,num[0],&num[0]);
printf(“\n num[1] = %d Address : %u”,num[1],&num[1]);
printf(“\n num[2] = %d Address : %u”,num[2],&num[2]);
printf(“\n num[3] = %d Address : %u”,num[3],&num[3]);
printf(“\n num[4] = %d Address : %u”,num[4],&num[4]);
return 0;
}
OUTPUT:
num[0] = 1 Address : 65516
num[1] = 2 Address : 65518
num[2] = 3 Address : 65520
num[3] = 2 Address : 65522
num[4] = 5 Address : 65524
Explanation:
In the output of the program, elements and their addresses are displayed. Recall that integer
requires two bytes in memory. Hence, the memory locations displayed at the output have
a difference of two. From the above program, it is clear that array elements are stored in
contiguous memory locations. Figure 7.3 shows the memory location and values stored.
1 2 3 2 5
7. Once the array is declared, its lowest boundary cannot be changed but upper boundary can
be expanded. The array name itself is a constant pointer and we cannot modify it. Therefore,
the lowest boundary of an array cannot be expanded. In other words, even if the boundary
exceeds than specified, nothing happens. The compiler throws no errors.
The reader can execute the following program for verifying the above concept.
7.2 Write a program to exceed the upper boundary of an array and see the element after expan-
sion of an array.
void main()
{
int num[5]={1,2,3,2,5};
num[5]=6;
clrscr();
printf (“num[5]=%d”,num[5]);
getche();
}
OUTPUT:
Num[5]=6
Explanation:
In the above program, array num[5] is declared with array size 5 and it is initialized with 5
elements. In the next statement, 6th element is also initialized and displayed. Hence, we can
say that upper boundary of an array can be expanded.
8. We know that an array name itself is a pointer. Though it is a pointer, it does not need ‘ ’
operator. The brackets ([]) automatically denote that the variable is a pointer.
9. All the elements of an array share the same name, and they are distinguished from one
another with the help of the element number.
10. The amount of memory required for an array depends upon the data type and the number of
elements. The total size in bytes for a single dimensional array is computed as shown below:
Total bytes=sizeof(data type) X size of array
11. The operation such as insertion, deletion of an element can be done with the list but cannot
be done with an array. Once an array is created, we cannot remove or insert memory location.
An element can be deleted, replaced but the memory location remains as it is.
12. When an array is declared and not initialized, it contains garbage values. If we declared an
array as static, all elements are initialized to zero. However, the values of static type data
persist and remain in the memory as long as program executes. To overcome this problem,
initialize first element of an array with zero or any number. Remaining all elements are
automatically initialized to zero, provided the initialization is done in the declaration state-
ment of an array. The following program illustrates this.
7.3 Write a program to initialize the static array and display its elements.
void main()
{
int num[5]={0},j;
clrscr();
for(j=0;j<5;j++)
printf(“\nnum[%d]=%d”,j,num[j]);
getche();
}
OUTPUT:
num[0]=0
num[1]=0
num[2]=0
num[3]=0
num[4]=0
Explanation:
In the above program, an array num[5] is declared and the first element is initialized with
zero. The compiler automatically initializes all elements with zero. Using the for loop the
contents of an array are displayed and we can see that all elements have zero values.
7.6 One-Dimensional Array
Array elements are stored contiguously in sequence one after the other. The elements of an array are
just arranged in one-dimension. They can be shown in a row or column. Single subscript will be used
in one-dimensional array to represent its elements.
An example of initialization of an array: - int a[5]; in this initialization of an array is done.
The type of variable is integer; its variable name is a and 5 is the size of the array.
The elements of the integer array a[5] are stored in contiguous memory locations. It is as-
sumed that the starting memory location is 2000. Each integer element requires 2 bytes. Hence, sub-
sequent element appears after the gap of two locations. Table 7.2 shows the locations of elements of
integer array.
Similarly, the elements of arrays of any data type are stored in contiguous memory location. The only
difference is that the number of locations is different for different data types.
An example is illustrated below on the basis of this point.
7.4 Write a program to print bytes reserved for various types of data and space required for stor-
ing them in memory using arrays.
void main()
{
int i[10];
char c[10];
long l[10];
clrscr();
printf(“The type ‘int’ requires %d Bytes”,sizeof(int));
printf(“\nThe type ‘char’ requires %d Bytes”,sizeof(char));
printf(“\nThe type ‘long’ requires %d Bytes”,sizeof(long));
printf(“\n %d memory locations are reserved for ten ‘int’
elements”,sizeof(i));
printf(“\n %d memory locations are reserved for ten ‘char’
elements”,sizeof(c));
printf(“\n %d memory locations are reserved for ten ‘long’
elements”,sizeof(l));
}
OUTPUT:
The type ‘int’ requires 2 Bytes
The type ‘char’ requires 1 Bytes
The type ‘long’ requires 4 Bytes
20 memory locations are reserved for ten ‘int’ elements
10 memory locations are reserved for ten ‘char’ elements
40 memory locations are reserved for ten ‘long’ elements
Explanation:
The sizeof() function provides the size of data type in bytes. In the above example, int,
char and long type of data variables are supplied to this function which gives the results 2,
1 and 4 bytes, respectively. The required number of memory locations for int, char and
long will be 2, 1 and 4. Memory locations required for the arrays = argument of an ar-
ray × sizeof(data type). In the above example, an array int i[10] requires 20
memory locations, since each element requires two memory locations. Memory requirement
for various data types will be as given in Table 7.3.
Character arrays are called strings. There is a slight difference between an integer array and charac-
ter array. In character array, NULL (‘\0’) character is automatically added at the end, whereas in
integer or other types of arrays, no null/character is placed at the end.
The NULL character acts as the end of the character array. By using this NULL character compiler
detects the end of the character array. When compiler reads the NULL character ‘\0’, there is end
of character array.
Note: D
etailed information about strings (character array) is given in another chapter ‘Strings and
Standard functions.’ The explanation about strings is given in brief in this chapter.
Given below is an example of a string.
7.5 Write a program to display character array with their address.
void main()
{
char name[10]={‘A’,’R’,’R’,’A’,’Y’};
int i=0;
clrscr();
printf(“\n Character Memory Location \n”);
while(name[i]!=‘\0’)
{
printf(“\n [%c]\t\t [%u]”,name[i],&name[i]);
i++;
}
}
OUTPUT:
Character Memory Location
[A] 4054
[R] 4055
[R] 4056
[A] 4057
[Y] 4058
Explanation:
The elements of an array are stored in contiguous memory locations. In the above example,
elements of one-dimensional array ‘A’,‘R’,‘R’,‘A’,‘Y’ are stored from location 4054 to 4058.
One-dimensional character array elements will be stored in memory as per Table 7.4
Notes: In case a NULL ‘\0’ is initialized in the above example after ‘Y’, the result displayed will
be ‘ARRAY’.
A few programs are provided on one-dimensional array and they are as follows:
7.6 Write a program to add even and odd numbers from 1 to 10. Store them and display their
results in two separate arrays.
void main()
{
int sumo=0,sume=0,i=0,odd[5],even[5],a=-1,b=-1;
clrscr();
for (i=1;i<=10;i++)
{
if(i%2==0)
even[++a]=i;
else
odd[++b]=i;
}
printf(“\n\tEven \t\tOdd”);
for(i=0;i<5;i++)
{
printf(“\n\t %d\t\t %d”,even[i],odd[i]);
sume=sume+even[i];
sumo=sumo+odd[i];
}
printf(“\n\t=====================\n”);
printf(“Addition: %d %14d”,sume,sumo);
}
OUTPUT:
Even Odd
2 1
4 3
6 5
8 7
10 9
=============
Addition: 30 25
Explanation:
The for loop executes 10 times. In the for loop, the value of loop variable ‘i’ is tested for
‘even’ and ‘odd’ conditions. If the value of ‘i’ is even then it is assigned to array even[]
otherwise to odd[]. Thus, for 10 times this task is performed. Finally, the second for loop
displays both the even[] and odd[] arrays. In the same array, sum of even and odd ele-
ments is calculated and displayed.
7.7 Write a program to input five numbers through the keyboard. Compute and display the addi-
tion of even numbers and product of odd numbers.
void main()
{
int a=0,m=1,i,num[5];
clrscr();
for(i=0;i<5;i++)
{
printf(“\nEnter Number[%d]:”,i+1);
scanf(“%d”,&num[i]);
}
printf(“\n=================================”);
for(i=0;i<5;i++)
{
if(num[i]%2==0)
{
printf(“\n Even Number : %d”,num[i]);
a=a+num[i];
}
else
{
printf(“\n Odd Number : %d”,num[i]);
m=m*num[i];
}
}
printf(“\n=================================”);
printf(“\n Addition of Even Numbers : %d”,a);
printf(“\n Product of Odd Numbers :%d”,m);
printf(“\n=================================”);
}
OUTPUT:
Enter Number[1]: 1
Enter Number[2]: 2
Enter Number[3]: 3
Enter Number[4]: 4
Enter Number[5]: 5
================================
Odd Number : 1
Even Number : 2
Odd Number : 3
Even Number : 4
Odd Number : 5
=================================
Addition of Even Numbers : 6
Product of Odd Numbers : 15
=================================
Explanation:
In the above example, five integers are entered through the keyboard. To detect even and
odd numbers mod(%) operation is carried out and remainder of each number is obtained.
If the remainder is 0, then the number is even and added to variable ‘a’. If the remainder is
non-zero then this number is multiplied to ‘m’. Variables ‘a’ and ‘m’ are initialized with 0
and 1, respectively. Both the variables are printed through printf() function which gives
addition of even numbers and product of odd numbers, respectively.
7.8 Write and display a program to detect the occurrence of a character in a given string.
void main()
{
static char s[15];
int i,c=0;
char f;
clrscr();
puts(“Enter a String :”);
gets(s);
puts(“Enter a Character to Find :”);
f=getchar();
for(i=0;i<=15;i++)
{
if(s[i]==f)
c++;
}
printf(“The Character (%c) in a String (%s) occurs %d times.”,f,s,c);
}
OUTPUT:
Enter a String : programmer
Enter a Character to Find : r
The Character (r) in a String (programmer) occurs (3) times.
Explanation:
In this program, the string and a single character are entered through the keyboard. Inside the
for loop, the if statement checks each element of the string for the occurrence of the single
entered character. If the character (‘r’) is found then ‘c’ counter is incremented otherwise
without incrementing the counter loop continuous till ‘i’ reaches to 15. At last the value of
‘c’ gives the total occurrence of the given character.
7.9 Write a program to display the elements of two arrays in two separate columns and add their
corresponding elements. Display the result of addition in the third column.
void main()
{
int i,num[]={24,34,12,44,56,17};
int num1[]={12,24,35,78,85,22};
clrscr();
printf(“Element of Array 1st - 2nd Array Addtion\n”);
for(i=0;i<=5;i++)
{
printf(“\n\t\t %d + %d = \t%d”,num[i],num1[i],num[i]+num1[i]);
}
}
OUTPUT:
Element of Array 1st - 2nd Array Addition
24 + 12 = 36
34 + 24 = 58
12 + 35 = 47
44 + 78 = 122
56 + 85 = 141
17 + 22 = 39
Explanation:
In the above program, two integer arrays are initialized and the corresponding elements of
arrays are added through a simple arithmetic operation.
7.10 Write a program to enter a character and integer data type. Use the two-dimensional array.
Perform and display the addition of three numbers.
Tips: The Unsigned character data type is capable of performing mathematical operations on
numbers from 1 to 255.
void main()
{
static unsigned char l,r,i,real[3][5],ima[3][5];
long c;
clrscr();
for(l=0;l<3;l++)
{
printf(“Enter Number[%d] :”,1+l);
scanf(“%ld”,&c);
r=c/255;
i=c%255;
real[l][5]=r;
ima[l][5]=i;
}
c=0;
for(l=0;l<3;l++)
c=c+real[l][5]*255+ima[l][5];
printf(“\nSum of 3 Numbers :%3ld”,c);
getch();
}
OUTPUT:
Enter Number [1] : 5
Enter Number [2] : 4
Enter Number [3] : 3
Sum of 3 Numbers : 12
Explanation:
The unsigned character data type ranges from 0 to 255. In the above example, three numbers
are entered. They are divided and the mod operation is carried out with 255. If the numbers
are less than 255 neither division nor mod operations are carried out. Their sum is evalu-
ated and displayed on the screen. In case the entered numbers are greater than 255, real and
imaginary parts are computed and stored in the separate arrays. To obtain the whole number,
the real part is multiplied with 255 and added to imaginary part.
7.11 Write a program to display names of days of a week using single-dimensional array having
length of 7. (A week having seven days).
void main()
{
int day[7],i;
clrscr();
printf(“\nEnter numbers between 1 to 7 :\n”);
for(i=0;i<=6;i++)
scanf(“%d”,&day[i]);
for(i=0;i<=6;i++)
switch(day[i])
{
case 1:
printf(“\n%dst day of week is Sunday”,day[i]);
break;
case 2:
printf(“\n%dnd day of week is Monday”,day[i]);
break;
case 3:
printf(“\n%drd day of week is Tuesday”,day[i]);
break;
case 4:
printf(“\n%dth day of week is Wednesday”,day[i]);
break;
case 5:
printf(“\n%dth day of week is Thursday”,day[i]);
break;
case 6:
printf(“\n%dth day of week is Friday”,day[i]);
break;
case 7:
printf(“\n%dth day of week is Saturday”,day[i]);
break;
default :
printf(“\n %dth is Invalid day”,day[i]);
}
}
OUTPUT:
Enter numbers between 1 to 7 : 1 3 2 4 5 7 8
Explanation:
In the above example, depending upon the value entered by the user, the switch()
statement decides which day to print.
7.12 Write a program to display the contents of two arrays. The 1st array should contain the
string and 2nd numerical numbers.
void main()
{
char city[6]={‘N’,’A’,’N’,’D’,’E’,’D’};
int i,pin[6]={4,3,1,6,0,3};
clrscr();
for(i=0;i<6;i++)
printf(“%c”,city[i]);
printf(“-”);
for(i=0;i<6;i++)
printf(“%d”,pin[i]);
}
OUTPUT:
NANDED – 431603
Explanation:
In the above example, two arrays of different data types are printed through printf()
function. The two for loops are used for printing two arrays containing the first string and
second numerics.
7.13 Write a program to display the number of days of different months of year.
# include <process.h>
void main()
{
int month[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int i;
clrscr();
for(i=0;i<=11;i++)
{
printf(“\n Month [%d] of a year contains %d days.”,i+1,month[i]);
printf(“\n”);
}
getche();
}
OUTPUT:
Month [1] of a year contains 31 days.
Month [2] of a year contains 28 days.
Month [3] of a year contains 31 days.
Month [4] of a year contains 30 days.
Month [5] of a year contains 31 days.
Month [6] of a year contains 30 days.
Month [7] of a year contains 31 days.
Month [8] of a year contains 31 days.
Month [9] of a year contains 30 days.
Month [10] of a year contains 31 days.
Month [11] of a year contains 30 days.
Month [12] of a year contains 31 days.
Explanation:
In the above example, one-dimensional array month[12] is initialized with the number
of days of different months of a year from 1 to 12 as per their order. In prinf() function,
number of days of the months are printed. The value of ‘i’ is incremented by one for obtaining
the increasing order of the month of a year.
7.14 Write a program to display the number of days of a given month of a year.
# include <process.h>
void main()
{
int month[12]={1,3,5,7,8,10,12,4,6,9,11,2};
int i,mn;
clrscr();
printf(“Enter Number of Month :”);
scanf(“%d”,&mn);
for(i=0;i<=11;i++)
{
if(mn==month[i])
goto compare;
}
printf(“\n Invalid Month”);
exit(1);
compare:;
if(i+1==12)
printf(“Month (%d) Contains 28 days.”,month[i]);
if(i+1<8)
printf(“Month (%d) Contains 31 days.”,month[i]);
if(i+1>7 && i+1!=12)
printf(“Month (%d) Contains 30 days.”,month[i]);
getche();
}
OUTPUT:
Enter Number of Month : 2
Month (2) Contains 28 days.
Explanation:
This program is slightly different as compared to the last one. The numbers of days of dif-
ferent months of a year are sorted. For example, first seven (1,3,5,7,8,10,12) elements of an
array have month numbers having 31 days, next four 30 days and last one 28 days. The user
enters the month number and if statement checks where this month number appears in the
array. Whenever there is a match control goes to the compare statements. The if statements
print the number of days depending upon the conditions stated as above.
7.15 Write a program to find the average sales of an item out of 12 months sale.
void main()
{
float sum=0,avg=0;
int sale;
int item[12];
clrscr();
printf(“\tEnter Month No.-Sale of an Item/month\n”);
for(sale=0;sale<=11;sale++)
{
printf(“\t\t %d =”,sale+1);
scanf(“%d”,&item[sale]);
}
for(sale=0;sale<=11;sale++)
sum=sum+item[sale];
avg=sum/12;
printf(“\n\t Average Sale of an item /month=%f”,avg);
}
OUTPUT:
Enter Month No.-Sale of an Item/month
1 = 125
2 = 225
3 = 325
4 = 425
5 = 525
6 = 625
7 = 725
8 = 825
9 = 925
10 = 500
11 = 600
12 = 700
Average Sale of an item /month= 543.750000
Explanation:
In the above program, sales of 12 months are entered and stored in an array item[12].
By using the for loop the sum of sales of 12 months is calculated. Average of sales is then
computed and the result is displayed.
7.16 Write a program to calculate and display the total cost of four models of Pentium PCs. Use
the single-dimension arrays for PC codes, their price and quantity available.
void main()
{
int i,pccode[4]={1,2,3,4};
long t=0,price[4]={25000,30000,35000,40000};
int stock[4]={25,20,15,20};
clrscr();
printf(“\t Stock & Total Cost Details \n”);
printf(“=======================================\n”);
printf(“Model\t Qty.\tRate (Rs.) Total Value”);
printf(“\n=======================================”);
for(i=0;i<=3;i++)
{
printf(“\nPentium%d %d %8ld %15ld”,pccode[i],stock[i],price[i],
price[i]*stock[i]);
t=t+price[i]*stock[i];
}
printf(“\n=======================================\n”);
printf(“Total Value of All PCs in Rs. %ld”,t);
printf(“\n=======================================\n”);
}
OUTPUT:
Stock & Total Cost Details
=======================================
Model Qty. Rate (Rs.) Total Value
=======================================
Pentium1 25 25000 625000
Pentium2 20 30000 600000
Pentium3 15 35000 525000
Pentium4 20 40000 800000
=======================================
Total Value of All PCs in Rs.2550000
======================================
Explanation:
Here, in the above program, three integer arrays pccode[], price[] and stock[]
are initialized. After this the for loop is used for finding the total value of the available
stock of each model. The result is printed by using simple multiplication of price[] and
stock[]. This product is then added to variable ‘t’, which is the total value. The for loop
executes four times. At the end, variable ‘t’ gives us the total cost of all PCs. Total cost is
printed with printf() statement.
7.17 Write a program to display the given message by using putc() and stdout() functions.
void main(void)
{
char msg[ ] = “C is Easy”;
int i = 0;
clrscr();
while(msg[i])
putc(msg[i++], stdout);
}
OUTPUT:
C is Easy
Explanation:
A character array and integer variable are initialized. Array always begins with element
number 0. In case if ‘i’ is not initialized with 0 result provides garbage value. Standard
stdout() function prints the string on console. Here, the string is ‘C is Easy’.
void main()
{
int num[5],j;
clrscr();
printf(“\n Enter five elements :”);
for(j=0;j<5;j++)
scanf(“%d”,&num[j]);
printf(“\n Elements Address”);
for(j=0;j<5;j++)
printf(“\n%d %u”,num[j],&num[j]);
getche();
}
OUTPUT:
Enter five elements: 4 6 4 2 1
Elements Address
4 65516
6 65518
4 65520
2 65522
1 65524
Explanation:
In the above program, an array num[] is declared. The first for loop with the help of
scanf() statement reads the elements and places in the array. The element position is
indicated by the loop variable j. Same procedure is applied for displaying elements. The
printf() statement displays the elements and addresses on the screen.
From Figure 7.4, one can see that one-dimensional arrays are stored one after another in sequence
in the memory.
In an array, we can insert, delete or add any element but we cannot insert or delete the memory
location. We can change only values.
4 6 4 2 1
Base Address
7.19 Write a program to delete specified element from an array and rearrange the elements.
void main()
{
int num[20]={0},j,k,n,p,t;
clrscr();
printf(“\n Enter number of elements :”);
scanf(“%d”,&n);
printf(“\n Enter elements :”);
for(j=0;j<n;j++)
scanf(“%d”,&num[j]);
printf(“\n Elements are :”);
for(j=0;j<n;j++)
printf(“\n %d %u”,num[j],&num[j]);
printf(“\n Enter element number to delete :”);
scanf(“%d”,&p);
p–-;
for(j=0;j<n;j++)
{
if(j>=p)
num[j]=num[j+1];
}
for(j=0;j<n;j++)
if(num[j]!=0)
printf(“\n %d %u”,num[j], &num[j]);
getche();
}
OUTPUT:
Enter number of elements: 4
Enter elements: 5 4 1 2
Elements are:
5 65482
4 65484
1 65486
2 65488
Enter element number to delete: 3
5 65482
4 65484
2 65486
Explanation:
In the above program, an array num[20] is declared. The program asks for the number of
elements to be entered. User has to enter the following input.
(i) Number of elements to be entered and integers.
(ii) Element number to be erased from an array.
The first for loop and scanf() statement reads numbers from keyboard and places in the array.
In the second for loop onwards, the position of an element number is to be erased, the next array
element is replaced with the previous one. Thus, the specified element is removed from an array. The
third for loop and printf() statement display the elements of an array. You can see in the output
that the third memory location is the same only if its contents are changed (see Figure 7.6 for view).
5 5 5
4 4 4
1 1 2
2 2
(ii) I nsertion: This operation is used to insert an element at a specified position in an array. Consider
the following program.
7.20 Write a program to insert an element at a specified position in an array.
void main()
{
int num[20]={0},j,k,n,p,t,s;
clrscr();
OUTPUT:
Enter number of elements : 4
Enter elements: 1
2
3
4
Elements and their locations are:
1 65450
2 65452
3 65454
4 65456
Enter element and position to insert at: 9 2
1 65450
9 65452
2 65454
3 65456
4 65458
Explanation:
This program is somewhat like previous program. Here, an element is inserted. The array
elements are shifted to the next location and at a specified position and a space is created
as shown in Figure 7.7 (b); the new element is inserted as shown in Figure 7.7 (c). Here,
you can also see that though we inserted a new element, the memory location of the second
element is the same (65452). Once again, it is proved that in array operation only contents of
memory can change but the actual addresses remain as it is. The address of the first element,
i.e. num[0] (65450), is called the base address. This address can also be stored in another
pointer and array elements can be accessed. The next program is illustrated in this regard.
1 1 1
2 9
3 2 2
4 3 3
4 4