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
Summary 636
Exercises 637
Appendix A ................................................................................. 641
American Standard Code for Information Interchange 641
Appendix B ................................................................................. 649
Priority of Operators and Their Clubbing 649
Appendix C ................................................................................. 651
Header Files and Standard Library Functions 651
Appendix D ................................................................................. 655
ROM-BIOS Services 655
Appendix E ................................................................................. 657
Scan Codes of Keyboard Keys 657
Index ....................................................................................... 660
I am indeed very delighted to present the third edition of Programming in C with elaborated concepts
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 pr int f ( )
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
cl rscr ( ) and exi t ( ) 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 i f , i f-else, nested i f-else
statements and swi tch case. To change the flow of the program, the programmer can use keywords
such as break, cont inue 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, whi le and do-whi le programming examples. Syntaxes of these control statements are briefed
together with programming examples. The other statements such as the break , cont inue 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 spr int f ( )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 mal loc( ) and cal loc( ) 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, stat ic 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 #def ine, #undef, #include,
#l ine, token pasting and stringizing operations and conditional compilation through C are illustrated.
It covers #def ine 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 mal loc( ), cal loc( ),
corelef t ( ) and real loc( ) and release the allocated memory using f ree( ) function. The
linked list is described in brief in this chapter. In the linked list, creation of linked list, traversing,
searching, inserting and deleting an element are described with figures and programming examples.
Utmost care has been taken to write third edition of the book in order to make it error free. The
suggestions and feedback for the improvement of the book are always welcome, the readers can
directly mail me at ankamthane@gmai l . com.
Ashok N. Kamthane
I would like to thank all those who have encouraged me, especially Professor B.M. Naik, former
principal of Shri Guru Gobind Singhji Institute of Engineering and Technology, who has been
always a source of inspiration.
Special thanks are due to members of board of governors of SGGS institute who motivated
me for writing this book, Baba Kalyani, Chairman and Managing Director of Bharat Forge Ltd
Pune, Ram Bhogle, C.Y. Gavhane, Mr Kamlesh Pande, Sanjay Kumar, Dr Nirmal Singh Sehra, and
Director of our Institute Dr L.M. Waghmare.
My sincere thanks to Professor S.D. Mahajan, Director of Technical Education, Maharashtra
State, and ex-Board of Governors of this college, Dr M.B. Kinhalkar, Former Home Minister and
ex-Principal, Dr T.R. Sontakke for inspiring me to write this book.
I am grateful to all my colleagues, friends and students, who extended morale support,
Dr Y.V. Joshi, Dr R.R. Manthalkar, Dr S.S. Gajre, Dr S.V. Bonde, Dr P.G. Jadhav, Professor N.G.
Megde, Professor P.S. Nalawade, Dr A.R. Patil, Dr A.B. Gonde, Dr M.B. Kokre, Dr U.V. Kulkarni,
Dr P. Pramanik, Dr V.M. Nandedkar, Dr A.V. Nandedkar, Dr B.M. Patre, Dr S.T. Hamde, Dr R.C.
Thool, Dr V.R. Thool, Mrs U.R. Kamble, Dr D.D. Doye, Dr V.G. Asutkar, Professor R.K. Chavan,
Professor Ghanwat Vijay, Dr V.K. Joshi, Dr S.G. Kahalekar, Dr A. Chakraborty, Dr P. Kar, Dr P.G.
Solankar, Dr B.M. Dabde, Dr M.L. Waikar, Dr R.S. Holambe, Dr J.V.L. Venkatesh, Mrs S.S.
Kandhare, Professor S.S. Hatkar, Narayan Patil, Dr P.D. Dahe, Dr P.D. Ullagadi, Dr P.B. Londhe,
Dr A.S. Sontakke, Professor A.M. Bainwad, Professor Deepak Bacchewar, Professor R.P. Parvekar,
Professor N.M. Khandare, Dr V.B.Tungikar, Dr R.N. Joshi, Dr L.G. Patil, Professor A.I. Tamboli,
Mr Bhalerao M.V. and Professor S.B. Dethe.
I am also thankful to my friends, Professor S.L. Kotgire, Maruti Damkondawar, G.M. Narlawar,
Anil Joshi, D.V. Deshpande, Professor Balaji Bacchewar, M.M. Jahagirdar, L.M. Buddhewar,
K.M. Buddhewar, S.R. Kokane, Ganpat Shinde, M.G. Yeramwar, S.R. Tumma, S.P. Tokalwad,
P.R. Navghare, Somajawar H.S. and Annes for their morale support.
I am thankful to the wonderful editorial team of Pearson Education for specific invaluable inputs
and bringing this book out in a record time.
I also express my thanks to my son Lecturer Amit, students Jadhav Gopal and Wanjare Sainath
for their critical review and suggesting improvements.
Last but not the least, my thanks are due to my wife Surekha for her patience and support. My son
Amol, daughter Sangita and daughter-in-law Swaroopa were of great help and supported me all the
times.
Ashok N. Kamthane
1 Basics and
Introduction to C
Chapter Outline
1.1 Why to use Computers?
1.2 Basics of a Computer
1.3 Latest Computers
1.4 Introduction to C
1.5 About ANSI C Standard
1.6 Machine, Assembly and High-Level Language
1.7 Assembler, Compiler and Interpreter
1.8 Structure of a C Program
1.9 Programming Rules
1.10 Executing the C Program
1.11 Standard Directories
1.12 The First C Program
1.13 Advantages of C
1.14 Header Files
1.15 Algorithm
1.16 Classification of Algorithms
1.17 Flowcharts
1.18 Pseudocode
computer and quite often it called as microprocessor chip. Since it is a tiny chip hence called as mi-
croprocessor chip. This chip is produced from silicon vapor over which millions of transistors are
mounted with modern fabrication techniques.
The brain of the computer is CPU. This chip is responsible to interpret and execute the instruc-
tions. It comprises arithmetic and logical unit, registers and control unit. The arithmetic and logical
unit performs various arithmetic and logical operations on the data based upon the instructions. The
control unit generates the timing and control signals for carrying out operations within the processor.
Registers are used for holding the instructions and storing the results temporarily. Instructions are
stored in the memory and they are fetched one by one and executed by the processor.
Output Device: The output device is used to display the results on the screen or to send the data to
an output device. The processed data is ultimately sent to the output device by the computer. The out-
put device can be a monitor, a printer, an LED, seven-segment display, D to A converter, plotter, and
so on. Figure 1.4 shows different output devices of a computer.
Memory: Memory is used to store the program. There are two types of semi-conductor memories.
They are as follows:
(i) RAM (Random access memory)
(ii) ROM (Read only memory)
semi-conductor memory is used for storing the instructions and data in the form of ones and zeros.
The memory can be called user’s memory or read–write memory. Processor first reads the instructions
and data from the primary memory (semi-conductor memory). Then, it executes the instructions.
One more memory device used by a computer is called read only memory (ROM). This contains
a fixed software program for providing certain operations. This is non-volatile memory. Its contents
cannot be eliminated when power supply goes off. The basic input–output system (BIOS) is a soft-
ware used to control various peripheral devices such as a keyboard, a monitor, a printer, a mouse,
ports including serial and parallel ports. In fact, this is an operating system. It is possible to access the
users’ written programs, i.e. by loading a file, saving it and doing modifications to it in the later stage.
As soon as a personal computer is switched on, the software gets booted from ROM. Thus, various
functions are assigned to all supporting peripherals of a central processing unit (CPU) and easy inter-
actions are provided to the user by BIOS while booting the system.
For storing volumous data, secondery storage devices can be used. They are optical disk, magnetic
disc, tapes, etc.
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 ( i f–e l se)
and (sw i t ch-case) multi-choice statement. C supports for, wh i l e and do-wh i l e 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:
/* Thi s i s single comment */
/* Thi s i s an example of /* nes ted comments */*/
/* Thi s i s an example of
of comment s in
mul t iple l ines */ /* I t can be nes ted */
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).
void main( )
{
pr int f (“Hel lo! C Programmers”) ;
}
OUTPUT:
Hel lo! C Programmers
Explanation:
This program displays the message ‘Hel lo! C Programmers’ using the pr int f ( )
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( )
{
cl rscr ( ) ; /* clears the screen */
pr int f (“\Thi s program explains comments”) ;
/* How to use comment? */
}
OUTPUT:
Thi s program explains comment s
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 c l rscr ( ) clears the screen, defined in header file <con i o . 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.
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;
cl rscr ( ) ;
a=a+b;
b=a-b; Print values
a=a-b; of a & b
pr int f (“\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 pr int f ( ) 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) To 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.
(ii) Non-deterministic: In this type of algorithm to reach to the solution, we have one of the mul-
tiple paths.
Example:
To find a day of a week.
(iii) Random algorithm: After executing a few steps, the control of the program transfers to
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.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;
cl rscr ( ) ;
x=20;
y=2e1;
z=‘a’ ;
p=3 . 2e20;
pr int f (“\n%d %10 . 2f %c % . 2l f” , 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’ ;
cl rscr ( ) ;
pr int f (“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 pr int f ( ) 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”;
cl rscr ( ) ;
pr int f (“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.
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 f loat
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
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 var iable_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
void main( )
{
int r=2;
float area=3 . 14*r*r ;
cl rscr ( ) ;
pr int f (“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.
Example:
long l ; / int data type is applied /
int s ; / signed is default /
uns igned long int ; / int keyword is optional /
2.5 Write a program to declare different variables with type modifiers and display them.
void main( )
{
shor t t=1;
long k=54111;
uns igned u=10;
signed j=-10;
cl rscr ( ) ;
pr int f (“\n t=%d” , t ) ;
pr int f (“\n k=%ld” , k) ;
pr int f (“\n u=%u” , u) ;
pr int f (“\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
shor t and long type, whereas u and j are unsigned and signed integers, respectively.
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.
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( )
{
cl rscr ( ) ;
pr int f (“\n Divi s ion operat ion Resul t”) ;
pr int f (“\n Two Integers (5 & 2) : %d” , 5/2) ;
pr int f (“\n One int & one float (5 . 5 & 2) : %g” , 5 . 5/2) ;
pr int f (“\n Two Integers (5 & 2) : %g” , (float )5/2) ;
}
OUTPUT:
Divis ion operat ion Resul t
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
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( )
{
uns igned u=65537;
cl rscr ( ) ;
pr int f (“\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:
volat i le int d;
void main( )
{
volat i le int x;
volat i le cons t int y=10;
cl rscr ( ) ;
pr int f (“Enter an integer :”) ;
scanf (“%d” , &x) ;
pr int f (“Entered integer i s :%d” , x) ;
x=3;
pr int f (“\nChanged value of x is :%d” , x) ;
pr int f (“\nValue of y:%d” , y) ;
/* y=8;*/
getche( ) ;
}
OUTPUT:
Enter an integer :5
Entered integer i s :5
Changed value of x i s :3
Value of y:10
Explanation:
In the above example, the variable x is initialized with keyword volat i le and y is with
volatile constant. Value of x can be changed but volat i le 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 modi fy 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. shor t int and int are different from each
6. Identifiers are the name of variables, arrays, other.
functions, and so on. 16. int, shor t 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 (++)
9. An unsigned integer variable contains values 17. The word ‘cont inue’ is a
(a) greater or equal to zero (a) keyword
(b) less than zero (b) password
(c) only zeros (c) header file
(d) Both (a) and (b) (d) None of the above
10. The keyword ‘cons t’ keeps the value of a 18. The volatile variables are those variables that re-
variable main/can be
(a) constant (a) constant
(b) mutable (b) changed at any time
(c) variant (c) Both of the above
(d) None of the above (d) None of the above
11. Identifiers are 19. In C the statements following main( ) are en-
closed within
(a) user-defined names
(b) reserved keywords (a) {}
(c) C statements (b) ()
(d) None of the above (c) <>
(d) None of the above
12. In C every variable has
20. In C the maximum value of unsigned character is
(a) a type
(b) a name (a) 255
(c) a value (b) 127
(d) a size (c) 65535
(e) all of the above (d) none of the above
13. The range of character data type is 21. The range of long signed integer is
(a) −128 to 127 (a) −2147483648 to 2147483647
(b) 0 to 255 (b) 0 to 255
(c) 0 to 32767 (c) 0 to 4294967295
(d) None of the above (d) None of the above
14. An unsigned integer variable occupies memory 22. In C ‘sizeof ’ is a/an
(a) 2 byes (a) variable
(b) 4 bytes (b) operator
(c) 1 bytes (c) keyword
(d) 8 bytes (d) None of the above
15. In C double type data needs memory of size 23. Which is the incorrect variable name
(a) 4 bytes (a) el se
(b) 2 bytes (b) name
(c) 10 bytes (c) age
(d) None of the above (d) cha_r
16. In C main( ) is a 24. How many keywords are there in ANSI C?
(a) function (a) 32
(b) user created function (b) 33
(c) string function (c) 42
(d) any number of variables (d) 15
1. cl rscr ( ) ;
void main( ) pr int f (“\n u=%u l=%ld” ,
{ u, l);
char c=90; }
cl rscr ( ) ;
4.
pr int f (“%c” , c) ;
void main( )
}
{
2. float a=3e-1 , b=2e-2;
void main( ) cl rscr ( ) ;
{ pr int f (“a=%g b=%g” , a , b) ;
uns igned char c=65; }
cl rscr ( ) ;
5.
pr int f (“%d %c %d “ , c , c , c) ;
void main( )
}
{
3. int x , a=1e1 , b=0;
void main( ) cl rscr ( ) ;
{ b+=1e1;
uns igned u=2147483647; pr int f (“a= %d b=%d” , a , b) ;
long l=2147483647; }
1. 4.
void main( ) void main( )
{ {
cl rscr ( ) ; float d=65535 . 43;
pr int f (“\n %d” , 7/2) ; double p=65789 . 987654;
pr int f (“\n%g” , 7 . 0/2) ; cl rscr ( ) ;
pr int f (“\n%g” , float7/2) ; pr int f (“%d %d” , d , p) ;
getche( ) ; getche( ) ;
} }
5.
void main( )
2. {
void main( ) float d=1234567 . 43;
{ double p=987654321 . 1234567;
volat i le d=15; cl rscr ( ) ;
const p=25; pr int f (“\n%f %l f” , d , p) ;
cl rscr ( ) ; pr int f (“\n%d %d” , size
pr int f (“%d %d”d+10 , p+1) ; of (d) , size of (p) ) ;
getche( ) ; getche( ) ;
} }
6.
3. #define
#define N= 90
void main( ) main( )
{ {
uns igned int d=65535; int x=10 , p;
uns igned char p=65; cl rscr ( ) ;
cl rscr ( ) ; p=x*N;
pr int f (“%c %c” , d , p) ; pr int f (“\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
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.
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
main ( )
{
int a=1 , b=2 , c=3 , j ;
cl rscr ( ) ;
j=a+b*c;
pr int f (“\n j=%d” , j ) ;
j=(a+b)*c;
pr int f (“\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( )
{
cl rscr ( ) ;
pr int f (“Addi t ion = %d\nSubt ract ion = %d” , 2+3 , 5-4) ;
}
OUTPUT:
Addi t ion = 5
Subt ract ion = 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 pr int f ( ) 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:
Condi t ion ? (expression1) : (express ion2) ;
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( )
{
cl rscr ( ) ;
pr int f (“Resul t = %d” , 2==3 ? 4 : 5 ) ;
}
OUTPUT:
Resul t = 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( )
{
cl rscr ( ) ;
3>2 ? pr int f (“True . ”) : pr int f (“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 pr int f ( ) 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
s izeof 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;
cl rscr ( ) ;
z=x*y++;
a=x*y;
pr int f (“\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;
cl rscr ( ) ;
z=x*++y;
a=x*y;
pr int f (“\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;
cl rscr ( ) ;
pr int f (“\n sizeof (x)=%d bytes” , s izeof (x) ) ;
pr int f (“\n sizeof (y)=%d bytes” , s izeof (y) ) ;
pr int f (“\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.
== 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( )
{
cl rscr ( ) ;
pr int f (“\nCondi t ion : Return Values \n” ) ;
pr int f (“\n10!=10 : %5d” , 10!=10) ;
pr int f (“\n10==10 : %5d” , 10==10) ;
pr int f (“\n10>=10 : %5d” , 10>=10) ;
pr int f (“\n10<=100: %5d” , 10<=100) ;
pr int f (“\n10!=9 : %5d” , 10!=9) ;
}
OUTPUT:
Condi t ion: 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;
cl rscr ( ) ;
pr int f (“Enter Any Integer ei ther above 5 or below 5 : -”) ;
scanf (“%d” , &a) ;
b=(a>5 ? 3 : 4) ;
pr int f (“Calculated Value of b i s : - %d” , b) ;
}
OUTPUT:
Enter Any Integer ei ther above 5 or below 5: - 6
Calculated Value of b i s: - 3
OR
Enter Any Integer ei ther above 5 or below 5: - 3
Calculated Value of b i s: - 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;
cl rscr ( ) ;
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;
cl rscr ( ) ;
pr int f (“Enter Values of x , y , z : -”) ;
scanf (“%d %d %d” , &x , &y , &z) ;
a=(x>=5 ? 3 : 4) ;
pr int f (“\n Calculated value of a i s : - %d” , a) ;
b=(y<=8 ? 10 : 9) ;
pr int f (“\n Calculated value of b i s : - %d” , b) ;
c=(z==10 ? 20 : 30) ;
pr int f (“\n Calculated value of c i s : - %d” , c) ;
m=x+y+z;
n=a+b+c;
pr int f (“\nAddi t ion of x , y , z i s %d (m)” , m) ;
pr int f (“\nAddi t ion of a , b , c i s %d (n)” , n) ;
pr int f (“\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 i s: - 3
Calculated value of b i s: - 10
Calculated value of c i s: - 30
Addi t ion of x , y , z i s 14 (m)
Addi t ion of a , b , c i s 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.
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( )
{
cl rscr ( ) ;
pr int f (“\nCondi t ion : Return Values\n” ) ;
pr int f (“\n5>3 && 5<10 : %5d” , 5>3 && 5<10) ;
pr int f (“\n 8>5 | | 8<2 : %5d” , 8>5 | | 8<2) ;
pr int f (“\n ! (8==8) : %5d” , ! (8==8) ) ;
}
OUTPUT:
Condi t ion : 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;
cl rscr ( ) ;
pr int f (“\nEnter a Character :”) ;
scanf (“%c” , &x) ;
y=(x>=65 && x<=90 ? 1 : 0) ;
pr int f (“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;
cl rscr ( ) ;
pr int f (“\n Enter The Character or Integer :”) ;
scanf (“%c” , &x) ;
y=(x>=48 && x<=57 ? 1 : 0) ;
Pr int f (“\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;
cl rscr ( ) ;
pr int f (“Enter numbers :”) ;
scanf (“%d” , &x) ;
z=(x>=1 && x<=100 ? 1 : 0) ;
pr int f (“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;
cl rscr ( ) ;
pr int f (“Enter numbers :”) ;
scanf (“%d” , &x) ;
z=(x==1 | | x==100 ? 1 : 0) ;
pr int f (“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;
cl rscr ( ) ;
pr int f (“Enter number :”) ;
scanf (“%d” , &x) ;
z=(x!=100 ? 1 : 0) ;
pr int f (“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;
cl rscr ( ) ;
pr int f (“Read The Integer f rom keyboard (x) : -”) ;
scanf (“%d” , &x) ;
x>>=2;
y=x;
pr int f (“The Right shi f ted data is = %d” , y) ;
}
OUTPUT:
Read The Integer f rom keyboard (x) : - 8
The Right shi f ted data i s = 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;
cl rscr ( ) ;
pr int f (“Read The Integer f rom keyboard (x) : -”) ;
scanf (“%d” , &x) ;
x<<=3;
y=x;
pr int f (“The Right shi f ted data is = %d” , y) ;
}
OUTPUT:
Read The Integer f rom keyboard (x) : - 2
The Lef t shi f ted data i s = 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;
cl rscr ( ) ;
pr int f (“Read The Integers f rom keyboard (a & b) : -”) ;
scanf (“%d %d” , &a , &b) ;
c=a & b;
pr int f (“The Answer af ter ANDing is (C)= %d” , c) ;
}
OUTPUT:
Read The Integers f rom keyboard (a & b) : 8 4
The Answer af ter ANDing i s (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;
cl rscr ( ) ;
pr int f (“Read The Integer f rom keyboard (a & b) : -”) ;
scanf (“%d %d” , &a , &b) ;
c=a | b;
pr int f (“The Or ing operat ion bewteen a & b in c = %d” , c) ;
getche( ) ;
}
OUTPUT:
Read The Integer f rom keyboard (a & b) : - 8 4
The Or ing operat ion 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;
cl rscr ( ) ;
pr int f (“Read The Integers f rom keyboard (a & b) : -”) ;
scanf (“%d %d” , &a , &b) ;
c=a^b;
OUTPUT:
Read The Integers f rom keyboard (a & b) : 8 2
The data af ter Exclus ive OR operat ion i s 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;
cl rscr ( ) ;
pr int f (“\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;
pr int f (“\n %d” , k) ; x=2*(y++) ;
} z=2*(++y) ;
pr int f (“\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) ; {
cl rscr ( ) ; int x=!0*10;
pr int f (“\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) % ( i n t )
following program? 5.5 is
void main( ) (a) 2
{ (b) 1
int k=8; (c) 3
pr int f (“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 cl rscr ( ) ;
(c) Both (a) and (b) pr int f (“\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 let ter=‘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 s t d i o . 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 (“cont rol st r ing” , 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, pr inf ( ) formatted function is used. In Section 4.2, pr int f ( )
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’ ;
pr int f (“%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 pr int f ( ) 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;
cl rscr ( ) ;
pr int f (“%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;
cl rscr ( ) ;
pr int f (“%f” , y ) ;
return 0;
}
In the above example, it is attempted in the pr int f ( ) 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 pr int f ( ) function will produce an error
message ‘float ing points format s not l inked’.
The format string is nothing but a string that begins and ends with the double quote. The
pr int f() 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( )
{
cl rscr ( ) ;
pr int f (“\n% . 2s” , “abcdef”) ;
pr int f (“\n% . 3s” , “abcdef”) ;
pr int f (“\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 pr int f ( ) 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;
cl rscr ( ) ;
pr int f (“\n %3d” , x-y) ;
pr int f (“\n %6d” , x-y) ;
}
OUTPUT:
22
22
Explanation:
In this program, in the first pr int f ( ) 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;
cl rscr ( ) ;
pr int f (“\n %*d” , 15 , x-y) ;
pr int f (“\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 pr int f ( ) 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;
cl rscr ( ) ;
pr int f (“\n % . 1f” , g) ;
pr int f (“\n % . 2f” , g) ;
pr int f (“\n % . 3f” , g) ;
pr int f (“\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 pr int f ( ) 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( )
{
cl rscr ( ) ;
pr int f (“\n%5d” , 12) ;
pr int f (“\n%5d” , 123) ;
pr int f (“\n%5d” , 1234) ;
pr int f (“\n %4 . 5f” , 6 . 12) ;
pr int f (“\n %4 . 6f” , 16 . 12) ;
pr int f (“\n %4 . 7f” , 167 . 12) ;
pr int f (“\n %4 . 8f” , 1678 . 12) ;
pr int f (“\n %8s” , “Ami tkumar”) ;
pr int f (“\n %8 . 2s” , “Ami tkumar”) ;
getche( ) ;
}
OUTPUT:
12
123
1234
6 . 12000
16 . 120000
167 . 1200000
1678 . 12000000
Ami tkumar
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 pr int f ( ) except they work exactly
opposite of each other.
Syntax:
The syntax of the input function for inputting the data is scanf ( ).
Example:
scanf (“cont rol st r ing” , address of var iable 1 , address of var i -
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;
cl rscr ( ) ;
pr int f (“Enter value of ‘A’ : ”) ;
scanf (“%c” , &a) ;
pr int f (“A=%c” , a) ;
}
OUTPUT:
Enter value of ‘A’ : 8
A=8
Explanation:
In the above program, although the type of variable ‘a’ is i n t , 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;
cl rscr ( ) ;
pr int f (“Enter value of ‘A’ : ”) ;
scanf (“%d” , &a) ;
pr int f (“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 pr i n t f ( ) 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;
cl rscr ( ) ;
pr int f (“\nEnter values :”) ;
scanf (“%d , %d , %d” , &a , &b , &c) ;
pr int f (“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] ;
cl rscr ( ) ;
pr int f (“Enter two integers : - \n”) ;
scanf (“%4d %4d” , &a , &b) ;
pr int f (“\nEntered integers are”) ;
pr int f (“\n%4d %4d” , a , b) ;
pr int f (“\n”) ;
pr int f (“\nEnter a real number : - \n”) ;
scanf (“%f” , &x) ;
pr int f (“\n Entered float number is ”) ;
pr int f (“\n%f” , x) ;
pr int f (“\n”) ;
pr int f (“\nEnter a s t r ing : - \n”) ;
scanf (“%7s” , name) ;
pr int f (“\n Entered st r ing ”) ;
pr int f (“\n%7s” , name) ;
getche( ) ;
}
OUTPUT:
Enter two integers : -
1 2
Entered integers are
1 2
Enter a real number : -
12 . 3
Entered float number i s
12 . 300000
Enter a st r ing: -
Deel ipkumar
Entered st r ing
Deel ipk
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 pr inf ( ) 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 pr int f ( ) 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;
cl rscr ( ) ;
pr int f (“\ tA=%d\nB=%d \ ‘C=%d\ ’” , a , b , c) ;
pr int f (“\n\b***\D=%d**” , d) ;
pr int f (“\n*************”) ;
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 pr int f ( ) 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 pr int f() 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 pr int f ( ) statement only the sequences of ‘*’ are printed, but in the output only
half line is displayed because it is affected by the fourth pr int f ( ) statement.
(iv) In the fourth pr int f ( ) 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 pr int f ( ) and scanf ( ) statements.
4.11 Write a program to print the third power of 2 using pow( ) function. Assume the floating-
point numbers.
OUTPUT:
2 . 000000 rai sed to 3 . 000000 i s 8 . 000000
Explanation:
In the above program, two variables x and y are declared and initialized. In the pr int f ( )
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.
OUTPUT:
Ten rai sed 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 %l f 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;
cl rscr ( ) ;
pr int f (“Enter value of ‘A’ , ‘B’ & ‘C’ : ”) ;
v=scanf (“%d %d %d” , &a , &b , &c) ;
(v<3 ? pr int f (“\n Er ror In Input t ing . ”) : pr int f (“\n Values
Successful ly read . ”) ) ;
}
OUTPUT:
Enter value of ‘A’ , ‘B’ & ‘C’ : 1 2 3
Value Successful ly read .
Enter value of ‘A’ , ‘B’ & ‘C’ : 1 J 2
Er ror In Input t ing .
Explanation:
In the above program, the pr int f ( ) 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 pr int f ( ) function.
void main( )
{
char nm[20] ;
int l ;
cl rscr ( ) ;
pr int f (“Enter St r ing :”) ;
scanf (“%s” , nm) :
l=pr int f (nm) ;
pr int f (“\nLength = %d” , l ) ;
}
OUTPUT:
Enter St r ing : HELLO
Length = 5
Explanation:
The pr int f ( ) 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;
pr int f (“\n ENTER TWO VALUES\n”) ;
scanf (“\n %d %d” , &a , &b) ;
c=a+b;
pr int f (“\n Sum i s=%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;
pr int f (“\n ENTER ANY NUMBER\n”) ;
scanf (“\n %d” , &a) ;
c=a*a;
pr int f (“\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;
cl rscr ( ) ;
pr int f (“Enter any character :”) ;
scanf (“%c” , &ch) ;
pr int f (“\n Your Entered Character is : %c” , ch) ;
}
OUTPUT:
Enter any character : C
Your Entered Character i s: C
Explanation:
In the above program, a character is entered and stored in variable ch. The pr int f() 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;
cl rscr ( ) ;
pr int f (“\n A= %d B= %d” , a , b) ;
a=a+b;
b=a-b;
a=a-b;
pr int f (“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.
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;
cl rscr ( ) ;
pr int f (“\nEnter a char :”) ;
c=getchar ( ) ;
pr int f (“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 pr int f ( ) 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 (var iable name) ;
Example:
char c=‘C’ ;
putchar (c) ;
A program is provided on putchar ( ).
void main( )
{
char c=‘C’ ;
cl rscr ( ) ;
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( )
{
cl rscr ( ) ;
pr int f (“Enter any two alphabet ic”) ;
getche( ) ;
getch( ) ;
}
OUTPUT:
Enter any two alphabet ic 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;
cl rscr ( ) ;
pr int f (“Press any key to cont inue”) ;
ch=getch( ) ;
pr int f (“\n You Pressed :”) ;
putch(ch) ;
}
OUTPUT:
Press any key to cont inue
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.
get s ( ) :
This function is used for accepting any string through s tdin (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 st r [ length of st r ing in number ] ;
gets(st r )
A program is given on get s( ).
4.23 Write a program to accept string through the keyboard using the gets( ) function.
void main( )
{
char ch[30] ;
cl rscr ( ) ;
pr int f (“Enter the St r ing :”) ;
get s(ch) ;
pr int f (“\n Entered St r ing : %s” , ch) ;
}
OUTPUT:
Enter the St r ing : USE OF GETS( )
Entered St r ing : USE OF GETS( )
Explanation:
In the above program, gets( ) reads string through the keyboard and stores it in character
array ch[30]. The pr int f ( ) function displays the string on the console.
2.
put s( ) :
void main( )
{
char ch[30] ;
cl rscr ( ) ;
pr int f (“Enter the St r ing :”) ;
get s(ch) ;
put s(“Entered St r ing :”) ;
put s(ch) ;
}
OUTPUT:
Enter the St r ing: put s i s in use .
Entered St r ing:
put s i s 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 s t [2].
4.
cputs( ) :
Syntax:
cputs(char *st ) ;
4.25 Write a program to read string using cgets( ) and display it using cputs( ).
void main( )
{
stat ic char *t ;
cl rscr ( ) ;
pr int f (“\n Enter Text Here :”) ;
cgets( t ) ;
t+=2;
pr int f (“\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.
cl rscr ( )
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:
cl rscr ( ) ;
2.
exi t ( )
3.
s leep( )
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 s leep( ) function.
void main( )
{
stat ic char t [10] ;
cl rscr ( ) ;
pr int f (“\n Enter Text Here :”) ;
get s( t ) ;
pr int f (“\n Your Entered Text :”) ;
sleep(5) ;
put s( 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.
sys tem ( )
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 (“di r”) ;
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 pr int f ( ) 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 cl rscr ( ) ,
exi t ( ) 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) get s( )
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) pr int f ( )
2. ______functions does not convert data. (c) put s( )
(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) put s( )
the console_____
(c) accept ( )
(a) pr int f ( ) (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 ge t s( ) is defined in
2. The function get s( ) is an unformatted <s t r i ng . 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 cget s( ) and cput s( ) 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 %l f 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
pr int f (“\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; cl rscr ( ) ;
b=‘A’ * ‘B’ ; x+= . 2;
cl rscr ( ) ; pr int f (“%g” , x) ;
pr int f (“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) get s( ) 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 pr int f ( ) 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= ( ( t f -32)*5) /9 where tem( ) function to execute DOS commands.
tc and t f 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 i f Statement
5.3 The i f–else Statement
5.4 Nested i f–el se Statements
5.5 The i f -else- i f Ladder Statement
5.6 The break Statement
5.7 The cont inue Statement
5.8 The goto Statement
5.9 The swi tch Statement
5.10 Nested swi tch case
5.11 The swi tch case and nes ted i fs
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 i f statement
(ii) The i f–el se statement
(iii) The i f–el se–i f ladder statement
(iv) The swi tch case statement
(v) The goto unconditional jump
(vi) The loop statement
Besides, the C also supports other control statements such as cont inue , 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 i f , goto , break , cont inue , swi tch
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.
The i f 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 i f 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 i f statement are normally enclosed within curly braces. The curly braces indicate the
scope of the i f 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 i f condition.
Given below are simple programs that demonstrate the use of the i f 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;
cl rscr ( ) ;
pr int f (“Enter the number :”) ;
scanf (“%d” , &v) ;
i f (v<10)
pr int f (“\nNumber entered i s less than 10”) ;
sleep(2) ; /* process hal t s for given value in seconds */
}
OUTPUT:
Enter the number : 9
Number entered i s less than 10
Explanation:
In the above program, the user can enter the number. The entered number is checked with the
i f 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;
cl rscr ( ) ;
pr int f (“\n Enter age in the years :”) ;
scanf (“%d” , &age) ;
i f (age>17)
pr int f (“\n El igible for Vot ing . ”) ;
getch( ) ;
}
OUTPUT:
Enter age in the years : 20
El igible for Vot ing .
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 i f block. Enter only the three numbers and calcu-
late their sum and multiplication.
void main( )
{
int a , b , c , x;
cl rscr ( ) ;
pr int f (“\nEnter Three Numbers :”) ;
x=scanf (“%d %d %d” , &a , &b , &c) ;
i f (x==3)
{
pr int f (“\n Addi t ion : %d” , a+b+c) ;
pr int f (“\n Mul t ipl icat ion : %d” , a*b*c) ;
}
}
OUTPUT:
Enter Three Numbers : 1 2 4
Addi t ion : 7
Mul t ipl icat ion : 8
Af ter second t ime execut ion
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 i f
condition is false and no operation is performed. Here, the statements following the i f con-
dition is enclosed within curly braces.
Figure 5.3 The i f–e l se statements Figure 5.4 The i f–e l se statement
OR
float x1 , x2;
cl rscr ( ) ;
pr int f (“\n Enter Values for a , b , c :”) ;
scanf (“%d %d %d” , &a , &b , &c) ;
i f (b*b>4*a*c)
{
x1=-b+sqr t (b*b-4*a*c) /2*a;
x2=-b-sqr t (b*b-4*a*c) /2*a;
pr int f (“\n x1=%f x2=%f” , x1 , x2) ;
}
el se
pr int f (“\n Root s are Imaginary”) ;
getch( ) ;
}
OUTPUT:
Enter Values for a , b , c : 5 1 5
Root s 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 i f 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;
cl rscr ( ) ;
pr int f (“\n Enter a Number :”) ;
scanf (“%d” , &s) ;
d=s%10;
i f (d==5)
{
s=s /10;
pr int f (“\n Square = %d%d” , s*s++ , d*d) ;
}
el se
pr int f (“\n Inval id 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 i f 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 pr int f ( ) 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 . Bas ic=Rs . 3000 .
Hra=20% of basic . Hra=20% of basic .
Da=110% of basic . Da=110% of basic .
Conveyance=Rs . 500 . Conveyance=Rs . 500 .
Incent ive=10% of sales . Incent ive=5% of sales .
Bonus=Rs . 500 . Bonus=Rs . 200 .
void main( )
{
float bs , hra , da , cv , incent ive , bonus , sale , ts ;
cl rscr ( ) ;
pr int f (“\n Enter Total Sales in Rs . :”) ;
scanf (“%f” , &sale) ;
i f (sale>=100000)
{
bs=3000;
hra=20 * bs/100;
da=110 * bs/100;
cv=500;
incent ive=sale*10/100;
bonus=500;
}
el se
{
bs=3000;
hra=20 * bs/100;
da=110 * bs/100;
cv=500;
incent ive=sale*5/100;
bonus=200;
}
t s=bs+hra+da+cv+incent ive+bonus ;
pr int f (“\nTotal Sales : % . 2f” , sale) ;
pr int f (“\nBasic Salary : % . 2f”’ , bs)
pr int f (“\nHra : % . 2f” , hra) ;
pr int f (“\nDa : % . 2f” , da) ;
pr int f (“\nConveyance : % . 2f” , cv) ;
pr int f (“\nIncent ive : % . 2f” , incent ive) ;
pr int f (“\nBonus : % . 2f” , bonus) ;
pr int f (“\nGross Salary : % . 2f” , ts) ;
getch( ) ;
}
OUTPUT:
Enter Total Sales in Rs . 100000
Total Sales : 100000 . 00
Bas ic Salary: 3000 . 00
Hra: 600 . 00
Da: 3300 . 00
Conveyance: 500 . 00
Incent ive: 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 i f condition checks the given figure of sales. If sale is more than
Rs. 1,00,000, the first bock following the i f 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
i f (condi t ion)
{
/*Ins ide first i f block*/
i f (condi t ion)
{
s tatement 1; /*i f block*/
s tatement 2;
}
else
{
s tatement 3; /*el se block*/
s tatement 4;
}
}
else
{
/*Inside el se block*/
i f (condi t ion)
{
s tatement 5; /*i f block*/
s tatement 6;
}
else
{
s tatement 7; /*el se block*/
s tatement 8;
}
}
From the above block, following rules can be described for applying nested i f -else- i f
statements.
1. Nested i f -else can be chained with one another.
2. If the condition is true control passes to the block following first i f. In that case, we may
have one more i f statement whose condition is again checked. This process continues till
there is no i f statement in the last i f 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 i f -else- i f ladder because it forms a ladder like structure as shown
in Figure 5.6.
From Previous Statement
To Next Statement
i f (condi t ion)
{
s tatement 1; /*i f block*/
s tatement 2;
}
el se i f (condi t ion)
{
s tatement 3; /*second i f block*/
s tatement 4;
}
el se i f (condi t ion)
{
s tatement 5; /*thi rd i f block*/
s tatement 6;
}
el se
{
s tatement 7; /*el se block*/
s tatement 8;
}
From the above block, following rules can be described for applying nested i f -e l se- i f
statements:
1. Nested i f -else can be chained with one another.
2. If the first i f condition is false control passes to el se- i f block where condition is again
checked with the next i f statement. This process continues till there is no i f statement in
the last el se block.
3. If one of the i f statements satisfies the condition, other nested else- i f statement will not
be executed.
Given below programs are described on the bases on nested i f -el se and i f -else- i f 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 ini t ial , final , consumed;
float total ;
cl rscr ( ) ;
pr int f (“\n Ini t ial & Final Readings :”) ;
scanf (“%d %d” , &ini t ial , &final ) ;
consumed = final - ini t ial ;
i f (consumed>=200 && consumed<=500)
total=consumed * 3 . 50;
el se i f (consumed>=100 && consumed<=199)
total= consumed * 2 . 50;
el se i f (consumed<100)
total=consumed*1 . 50;
pr int f (“Total bi l l for %d uni t is %f” , consumed , total ) ;
getche( ) ;
}
OUTPUT:
Ini t ial & Final Readings : 800 850
Total bi l l for 50 uni t i s 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 ;
cl rscr ( ) ;
pr int f (“Enter 1st number :”) ;
scanf (“\n%d” , &a) ;
pr int f (“Enter 2nd number :”) ;
scanf (“\n%d” , &b) ;
pr int f (“Enter 3 rd number :”) ;
scanf (“\n%d” , &c) ;
pr int f (“Enter 4th number :”) ;
scanf (“\n%d” , &d) ;
pr int f (“Enter 5th number :”) ;
scanf (“\n%d” , &e) ;
pr int f (“Enter 6th number :”) ;
scanf (“\n%d” , &f ) ;
i f ( (a>b)&&(a>c)&&(a>d)&&(a>e)&&(a>f ) )
pr int f (“Maximum out of s ix Numbers is : %d” , a) ;
el se i f ( (b>c)&&(b>d)&&(b>e)&&(b>f ) )
pr int f (“Maximum out of s ix Numbers is : %d” , b) ;
el se i f ( (c>d)&&(c>e)&&(c>f ) )
pr int f (“Maximum out of s ix Numbers is :%d” , c) ;
el se i f ( (d>e)&&(d>f ) )
pr int f (“Maximum out of s ix Numbers is : %d” , d) ;
el se i f (e>f )
pr int f (“Maximum out of s ix Numbers is : %d” , e) ;
el se
pr int f (“Maximum out of s ix Numbers is : %d” , f ) ;
getch( ) ;
}
OUTPUT:
Enter 1s t 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 i s : 90
Explanation:
Six numbers are entered through the keyboard. All the values of variables are compared
with one another using && (AND) in nested i f–else–i f statements. When one of the i f
statements satisfies the condition that i f block is executed which prints the largest number
otherwise the control passes to another i f–else–i f 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;
cl rscr ( ) ;
pr int f (“\nEnter Three Numbers x , y , z :”) ;
scanf (“%d %d %d” , &x , &y , &z) ;
pr int f (“\nLargest out of Three Numbers is :”) ;
i f (x>y)
{
i f (x>z)
pr int f (“x=%d\n” , x) ;
el se
pr int f (“z=%d\n” , z) ;
}
el se
{
i f (z>y)
pr int f (“z=%d\n” , z) ;
el se
pr int f (“y=%d\n” , y) ;
}
}
OUTPUT:
Enter Three Numbers x , y , z : 10 20 30
Largest out of Three Numbers i s :z=30
Explanation:
This is also an example of the nested i fs. When the i f statement satisfies the condition,
control passes to another i f statement block. Three numbers are entered through keyboard.
The first i f statement compares the first number with the second number. If the condition is
a true, the block followed by first i f statement executes. Inside the block, the i f 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 i f statement fails to satisfy the condition, the else block with nested
i f 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 , smal lest ;
cl rscr ( ) ;
pr int f (“\n Enter Three Numbers :”) ;
OUTPUT:
Enter Three Numbers : 1 5 8
The smal les t of 1 5 8 i s 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 , t s;
cl rscr ( ) ;
pr int f (“\n Enter Basic Salary :”) ;
scanf (“%f” , &bs) ;
i f (bs=>5000)
{
hra=20 * bs /100;
da= 110 * bs/100;
cv=500;
}
el se
i f (bs=>3000 && bs<5000)
{
hra=15*bs /100;
da=100*bs /100;
cv=400;
}
el se
{
i f (bs<3000)
hra=10*bs /100;
da= 90*bs /100;
cv=300;
}
t s=bs+hra+da+cv;
pr int f (“\nBasic Salary : %5 . 2f” , bs) ;
pr int f (“\nHra : %5 . 2f” , hra) ;
pr int f (“\nDa : %5 . 2f” , da) ;
pr int f (“\nConveyance : %5 . 2f” , cv) ;
pr int f (“\nGross Salary : %5 . 2f” , ts) ;
getch( ) ;
}
OUTPUT:
Enter Basic Salary: 5400
Bas ic 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 i f–
e l se 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 pr inc , nyrs , rate , interes t ;
cl rscr ( ) ;
pr int f (“\n Enter Loan & No . of years : -”) ;
scanf (“%f %f” , &pr inc , &nyrs) ;
i f (pr inc>=10000)
rate=20;
el se
i f (pr inc>=8000 && pr inc<=9999)
rate=18;
el se
i f (pr inc<8000)
rate=16;
interes t = pr inc * nyrs * rate/100;
pr int f (“\nYears : %6 . 2f” , nyrs) ;
pr int f (“\nLoan : %6 . 2f” , pr inc) ;
pr int f (“\nRate : %6 . 2f” , rate) ;
pr int f (“\nInteres t : %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 i f 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 Thi rd Division
>=50 & <60 Second Divi sion
>=60 & <75 Fi rs t Division
>=75 & <=100 Di st inct ion
I f marks in any subject less than 35 Fai l
void main( )
{
int a , b , c , d , e , f ;
float sum=0;
float avg;
cl rscr ( ) ;
pr int f (“\nEnter Marks : \n”) ;
pr int f (“P C B M E H\n”) ;
scanf (“%d %d %d %d %d %d” , &a , &b , &c , &d , &e , &f ) ;
i f (a<35 | | b<35 | | c<35 | | d<35 | | e<35 | | f<35)
{
pr int f (“\nResul t : Fai l”) ;
exi t ( ) ;
}
sum=a + b + c + d + e + f ;
avg=sum/6;
pr int f (“Total : %g \nAverage : %g” , sum , avg) ;
i f (avg>=35 && avg<50)
pr int f (“\n Resul t : Thi rd Divi sion”) ;
el se
i f (avg>=50 && avg <60)
pr int f (“\n Resul t : Second Divis ion”) ;
el se
i f (avg>=60 && avg<75)
pr int f (“\n Resul t : Fi rs t Divi sion”) ;
el se
i f (avg>75 && avg <=100)
pr int f (“\nResul t : Di st inct ion”) ;
getche( ) ;
}
Enter Marks :
P C B M E H
56 57 56 89 78 45
Total : 381
Average : 63 . 5
Resul t : Fi rst Divi s ion
Explanation:
In the above program, marks of six subjects are entered through the keyboard. Their sum
and average are calculated. The first i f statement checks the condition whether the marks
in individual subjects are less than 35. If so, message displayed will be ‘Resul t : Fai l ’
and the program terminates. The logical OR ( | | ) is used here.
The average marks obtained are checked with different conditions. The i f -else blocks are
used. Based on the conditions the statements are executed.
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;
cl rscr ( ) ;
pr int f (“\nEnter Number of Cal ls :”) ;
scanf (“%d” , &nc) ;
i f (nc<100)
goto f ree;
el se i f (nc>99 && nc<200)
goto charge1;
el se i f (nc>199 && nc<300)
goto charge2;
el se
goto charge3;
f ree :
pr int f (“\n No charges . ”) ;
return;
charge1:
pr int f (“\n Total Charges : %d Rs . ” , nc*1) ;
return;
charge2:
pr int f (“\n Total Charges : %d Rs . ” , nc*2) ;
return;
charge3:
pr int f (“\n Total Charges : %d Rs . ” , nc*3) ;
}
OUTPUT:
Enter Number of Cal l s : 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 go t o
statement.
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.
break;
case constant B :
s tatement ;
break;
defaul t :
s tatement ;
}
void main( )
{
int ch;
cl rscr ( ) ;
pr int f (“\n[1] . . . . . . . . . ”) ;
pr int f (“\n[2] _________”) ;
pr int f (“\n[3] *********”) ;
pr int f (“\n[4] ==========”) ;
pr int f (“\n[5] EXIT”) ;
pr int f (“\n\n ENTER YOUR CHOICE :”) ;
scanf (“%d” , &ch) ;
swi tch(ch)
{
case 1 :
pr int f (“\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ”) ;
break;
case 2 :
pr int f (“\n ___________________________________________”) ;
break;
case 3 :
pr int f (“\n ********************************************”) ;
break;
case 4 :
pr int f (“\n ============================================”) ;
break;
case 5 :
pr int f (“\n Terminated by choice”) ;
exi t ( ) ;
break;
defaul t :
pr int f (“\n Inval id 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 swi tch statement. In the swi tch
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 defaul t is executed. The defaul t warns the user with a mes-
sage ‘ Inval id 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 swi tch statements.
void main( )
{
int a , b , c , ch;
cl rscr ( ) ;
pr int f (“\ t =================”) ;
pr int f (“\n\ t MENU”) ;
pr int f (“\n\ t =================”) ;
pr int f (“\n\ t [1] ADDITION”) ;
pr int f (“\n\ t [2] SUBTRACTION”) ;
pr int f (“\n\ t [3] MULTIPLICATION”) ;
pr int f (“\n\ t [4] DIVISION”) ;
pr int f (“\n\ t [5] REMAINDER”) ;
pr int f (“\n\ t [6] LARGER OUT OF TWO”) ;
pr int f (“\n\ t [0] EXIT”) ;
pr int f (“\n\ t=================”) ;
pr int f (“\n\n\ t ENTER YOUR CHOICE :”) ;
scanf (“%d” , &ch) ;
i f (ch<=6 & ch>0)
{
pr int f (“Enter Two Numbers :”) ;
scanf (“%d %d” , &a , &b) ;
}
swi tch ( ch)
{
case 1 :
c=a+b;
pr int f (“\n Addt ion : %d” , c) ;
break;
case 2 :
c=a-b;
pr int f (“\n Subt ract ion : %d” , c) ;
break;
case 3 :
c=a*b;
pr int f (“\n Mul t ipl icat ion : %d” , c) ;
break;
case 4 :
c=a/b;
pr int f (“\n Divis ion : %d” , c) ;
break;
case 5 :
c=a%b;
pr int f (“\n Remainder : %d” , c) ;
break;
case 6 :
i f (a>b)
pr int f (“\n\ t %d (a) i s larger than %d (b) . ” , a , b) ;
el se
i f (b>a)
pr int f (“\n\ t %d (b) i s larger than %d (a) . ” , b , a) ;
el se
pr int f (“\n\ t %d (a) & %d (b) are same . ” , a , b) ;
break;
case 0 :
pr int f (“\n Terminated by choice”) ;
exi t ( ) ;
break;
defaul t :
pr int f (“\n Inval id 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) i s 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 i f
statement. If it is in between 1 and 6 the i f block is executed which prompts the user to enter
two numbers. After this, the choice entered by the user is passed to the swi tch 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 swi tch statements.
void main( )
{
long ch , min , hrs , ds , mon , yrs , se;
cl rscr ( ) ;
pr int f (“\n[1] MINUTES”) ;
pr int f (“\n[2] HOURS”) ;
pr int f (“\n[3] DAYS”) ;
pr int f (“\n[4] MONTHS”) ;
pr int f (“\n[5] SECONDS”) ;
pr int f (“\n[0] EXIT”) ;
pr int f (“\n Enter Your Choice :”) ;
scanf (“%ld” , &ch) ;
i f (ch>0 && ch<6 )
{
pr int f (“Enter Years :”) ;
scanf (“%ld” , &yrs) ;
}
mon=yrs*12;
ds=mon*30;
ds=ds+yrs*5;
hrs=ds*24;
min=hrs*60;
se=min*60;
swi tch(ch)
{
case 1 :
pr int f (“\n Minutes : %ld” , min) ;
break;
case 2 :
pr int f (“\n Hours : %ld” , hrs) ;
break;
case 3 :
pr int f (“\n Days : %ld” , ds) ;
break;
case 4 :
pr int f (“\n Months : %ld” , mon) ;
break;
case 5 :
pr int f (“\n Seconds: %ld” , se) ;
break;
case 0 :
pr int f (“\n Terminated by choice”) ;
exi t ( ) ;
break;
defaul t :
pr int f (“\n Inval id 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 swi tch
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;
cl rscr ( ) ;
for ( i=0; i<=700; i++)
pr int f (“%d” , i ) ;
pr int f (“\n\n\ t \ tCLRAR SCREE MENU\n”) ;
pr int f (“\ t \ t1] Whole screen\n”) ;
pr int f (“\ t \ t2] Hal f Screen\n”) ;
pr int f (“\ t \ t3] Top 3 Lines \n”) ;
pr int f (“\ t \ t4] Bot tom 3 Lines \n”) ;
pr int f (“\ t \ t5] Exi t \n Enter Your Choice :”) ;
scanf (“%d” , &c) ;
swi tch(c)
{
case 1:
cl rscr ( ) ;
break;
case 2 :
for ( i=0; i<=189; i++)
{
gotoxy( i , 1) ;
pr int f (“\ t”) ;
}
break;
case 3 :
for ( i=1; i<=99; i++)
{
gotoxy( i , 1) ;
pr int f (“\ t”) ;
}
break;
case 4 :
for ( i=1; i<120; i++)
{
gotoxy( i , 21) ;
pr int f (“\ t”) ;
}
defaul t :
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 swi tch cases. While using swi tch 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;
cl rscr ( ) ;
pr int f (“\n FILE LISTING MENU”) ;
pr int f (“\n 1] . EXE”) ;
pr int f (“\n 2] . BAT”) ;
pr int f (“\n 3] . obj”) ;
pr int f (“\n 4] . bak\n Enter Your Choice - :”) ;
scanf (“%d” , &c) ;
swi tch(c)
{
case 1 :
sys tem(“di r . exe”) ;
break;
case 2:
sys tem(“\di r . c”) ;
break;
case 3:
sys tem(“\di r . obj”) ;
break;
case 4:
sys tem(“\di r . bak”) ;
break;
defaul t :
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 Sys tem 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;
cl rscr ( ) ;
pr int f (“\n Enter Month Number of the Year 2015 : “) ;
scanf (“%d” , &m) ; /* Program for finding days of any month of 2015*/
swi tch(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;
defaul t :
pr int f (“\a\a Inval id Month”) ;
exi t ( ) ;
}
/* s tar t ing day i s to be shown/adjusted as per calendar */
pr int f (“\n\n\n”) ;
pr int f (“\ t \ t \ tMonth - %d - 2015\n\n” , m) ;
pr int f (“ SUN MON TUE WED THU FRI SAT\n\n”) ;
swi tch (a)
{
case 1 :
pr int f (“\ t%d” , i ) ;
break;
case 2 :
pr int f (“\ t \ t%d” , i ) ;
break;
case 3 :
pr int f (“\ t \ t \ t%d” , i ) ;
break;
case 4 :
pr int f (“\ t \ t \ t \ t%d” , i ) ;
break;
case 5 :
pr int f (“\ t \ t \ t \ t \ t%d” , i ) ;
break;
case 6 :
pr int f (“\ t \ t \ t \ t \ t \ t%d” , i ) ;
break;
case 7 :
pr int f (“\ t \ t \ t \ t \ t \ t \ t%d” , i ) ;
break;
}
h=8-a; /* The s tar t ing day is subt racted f rom 8 */
for ( i=2; i<=h; i++) /* To display the first row */
pr int f (“\ t%d” , i ) ;
pr int f (“\n”) ;
for ( i=h+1; i<=j ; i++) /* To cont inue wi th second row onwards */
{
i f (b==8) /* To terminate the l ine af ter every week */
{
pr int f (“\n”) ;
b=1;
}
pr int f (“\ 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 swi tch 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
pr int f ( ) functions and second swi tch structure perform printing of dates in a column-
wise manner. The variables i , b are initialized to 1.
The second swi tch 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 i f 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.
Explanation:
In the above program, an infinite for loop is used. In the for loop, the sw i t ch 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;
cl rscr ( ) ;
pr int f (“\n Enter a Number :”) ;
scanf (“%d” , &x) ;
swi tch(x)
{
case 0 :
pr int f (“\n Number i s Even . ”) ;
break;
case 1 :
pr int f (“\n Number i s Odd . ”) ;
break;
defaul t :
y=x%2;
swi tch(y)
{
case 0:
pr int f (“\n Number i s Even . ”) ;
break;
defaul t :
pr int f (“\n Number i s Odd . ”) ;
}
}
getche( ) ;
}
OUTPUT:
Enter a Number : 5
Number i s Odd .
Explanation:
In the above-given program, the first swi tch 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 swi tch 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 swi tch statements are the same.
5.25 Write a program to count the number of 1s, 0s, blank spaces and others using nested
swi tch statement.
void main( )
{
stat ic int x , s , a , z , o;
char txt [20] ;
cl rscr ( ) ;
pr int f (“\nEnter Numbers :”) ;
gets( txt ) ;
whi le( txt [x] !=’ \0’ )
{
swi tch( txt [x] )
{
case ‘ ’ :
s++;
break;
defaul t :
swi tch( txt [x] )
{
case ‘1’ :
a++;
break;
case ‘0’ :
z++;
break;
defaul t :
o++;
}
}
x++;
}
pr int f (“\n Total Spaces : %d” , s) ;
pr int f (“\n Total 1s : %d” , a) ;
pr int f (“\n Total 0s : %d” , z) ;
pr int f (“\n Others : %d” , o) ;
pr int f (“\n St r ing Length: %d” , s+a+z+o) ;
}
OUTPUT:
Enter Numbers : 1110022 222
Total Spaces : 1
Total 1s : 3
Total 0s : 2
Others : 5
St r ing Length:11
Explanation:
In the above-mentioned program, the outer swi tch counts only spaces in a given text. For
other than spaces, the inner swi tch statement is used. The inner swi tch 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.
void main( )
{
int x;
cl rscr ( ) ;
pr int f (“\n Enter a Number : ) ;
scanf (“%d” , &x) ;
i f (x==‘A’ )
pr int f (“%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 i f statement. If there
is a match, the ASCII, value is displayed.
5.27 Write a program to use nested i f–el se statements in the swi tch statement. Also show
the effect of conversion of integer to character.
void main( )
{
int i ;
cl rscr ( ) ;
pr int f (“\n Enter Any ASCI I Number :”) ;
scanf (“%d” , &i ) ;
cl rscr ( ) ;
swi tch( i )
{
case ‘A’ :
pr int f (“Capi tal A\n”) ;
break;
case ‘B’ :
pr int f (“Capi tal B\n”) ;
break;
case ‘C’ :
pr int f (“Capi tal C\n”) ;
break;
defaul t :
i f ( i>47 && i<58)
pr int f (“\n Digi t : [ %c ]” , i ) ;
el se i f ( i>=58 && i<=64)
pr int f (“\nSymbol : [ %c ]” , i ) ;
el se i f ( i>64 && i<91)
pr int f (“\nCapi tal : [ %c ]” , i ) ;
el se i f ( i>96 && i<123)
pr int f (“\n Smal l : [ %c ]” , i ) ;
el se
pr int f (“\n Inval id Choice” , i ) ;
getche( ) ;
}
}
OUTPUT:
Enter Any ASCI I Number : 65
Capi tal A
Explanation:
An ASCII number is entered. In the outer sw i t ch 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 sw i t ch 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 i f and the i f–else state-
ments in the C programming. Also, the multi-way-decision statement swi tch case is also dis-
cussed. How nested i f–el se and swi tch 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 , cont inue 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 swi tch can only test for ________. (b) different constants
(c) variables
(a) equality
(b) non-equality 4. In swi tch , character constants are automatically
(c) None of them converted to ________
2. Only ______ values are applicable in the swi tch (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 i fs
switch. (b) swi tch case
(c) None of the them
(a) identical constants
II True or false:
1. The el se is associated with i f. 10. Like i f -el se the swi tch statement can be
nested.
2. The else block is executed when condition is false.
11. The default statement is compulsory for
3. The i f statement can have multiple else statements
swi tch statement
4. The statement i f (1) executes i f block.
12. The swi tch statement testes for equality only.
5. One swi tch statement can have multiple case
13. The i f statement can evaluate relational and
statements but only one default statement.
logical expressions.
6. The default statement can be written anywhere in
14. The i f statement works with expression as well
the swi tch block.
as constants.
7. The break statement is used to separate two
15. The defaul t is a keyword.
case statements.
16. The defaul t statement can be placed at the
8. The case statement is always terminated by a
beginning of swi tch , without any statement in
semi-colon.
its block
9. The swi tch statement accepts only constant as an
17. The swi tch block should be terminated by a
argument.
semi-colon.
III Select the appropriate option from the multiple choices given below:
1. The swi tch 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 e l se with i f state- 7. Is it possible to use the else statement in place
ment? of defaul t or vice versa?
2. Is it possible to use multiple defaul t statements 8. Can we put defaul t statement anywhere in the
in swi tch statement? swi tch case structure?
3. Write the use of else and defaul t statements in 9. What are the limitations of the swi tch case
i f–else and swi tch 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?
swi tch 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 whi le Loop
6.5 The do-whi le Loop
6.6 The whi le Loop within the do-whi le 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
The for loop statement comprises three actions. These actions are placed in the for statement
itself. The three actions are ini t ial ize counter , test condi t ion and Re-evalua-
t i on parame t ers, 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 whi le and do-whi le statements. The only difference between for and whi le 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–- )
pr int f (“%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-whi le 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 ;
cl rscr ( ) ;
for ( i=1; i<=5; i++)
pr int f (“\n Number : %5d i t ’s Square: %5d” , i , i*i ) ;
}
OUTPUT:
Number : 1 i t ’s Square: 1
Number : 2 i t ’s Square: 4
Number : 3 i t ’s Square: 9
Number : 4 i t ’s Square: 16
Number : 5 i t ’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 pr i n t f ( ) 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 pr int f ( ) 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 ;
cl rscr ( ) ;
for ( i=1; i<=15; i++)
pr int f (“%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 ;
cl rscr ( ) ;
for ( i=1; i<=15; i=i+1)
pr int f (“%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;
cl rscr ( ) ;
for ( i=0; i<=15; )
{
i++;
pr int f (“%5d” , i ) ;
i=i+1;
pr int f (“%5d” , i ) ;
c++;
}
pr int f (“\n\n The Body of the loop is executed for %d t imes . ” , c) ;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The Body of the loop i s executed for 8 t imes .
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 pr int f ( ) statement. After this operation, once again in the loop i is incremented
by 1 and the values are displayed using the second pr int f ( ) 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;
cl rscr ( ) ;
for ( ; i<=15; )
{
pr int f (“%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;
cl rscr ( ) ;
pr int f (“Numbers in Ascending Order :”) ;
for ( ;++i<=10; )
pr int f (“%3d” , i ) ;
pr int f (“\n\n”) ;
pr int f (“Numbers in Descending Order :”) ;
for ( ; i - ->1; )
pr int f (“%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 pr int f ( )
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;
cl rscr ( ) ;
for ( ; ; )
{
pr int f (“%5c” , i++) ;
i f ( 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;
cl rscr ( ) ;
pr int f (“\n Numbers f rom 1 to 100 not divis ible by 2 , 3 & 5\n\n”) ;
for (x=0 ;x<=100;x++)
{
i f (x%2!=0 && x%3!=0 && x%5!=0)
{
pr int f (“%d\ t” , x) ;
c++;
}
}
pr int f (“\nTotal Numbers : %d” , c) ;
}
OUTPUT:
Numbers f rom 1 to 100 not divi s ible 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;
cl rscr ( ) ;
pr int f (“Enter a number :”) ;
scanf (“%d” , &n) ;
a=b=n;
pr int f (“(++) (–- ) \n”) ;
pr int f (“============”) ;
for ( ; ; (a++ , b–- ) )
{
pr int f (“\n%d\ t%d” , a , b) ;
i f (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;
cl rscr ( ) ;
pr int f (“\n\ t \ t Table of Even numbers f rom 1 to 20”) ;
pr int f (“\n\ t \ t ===== == ==== ======= ==== = == ==\n”) ;
for ( ; ; )
{
i f ( i==21)
break;
el se i f ( i%2==0)
{
pr int f (“%d\ t” , i ) ;
i++;
cont inue;
}
el se
{
i++;
cont inue;
}
}
getche( ) ;
}
OUTPUT:
Table of Even numbers f rom 1 to 20
==== == ==== ======= === = == ==
2 4 6 8 10 12 14 16 18
Explanation:
In the above program, both break and cont inue 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-
t inue 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.
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 sqr t ( ) functions
return square root of a number. Each time value of variable ‘ i ’ is passed to sqr t ( ) 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.
Explanation:
In the above program, the for loop is initialized from 7 to 100. The i f 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;
cl rscr ( ) ;
pr int f (“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) ) ;
}
pr int f (“Value of x = %f” , x) ;
pr int f (“\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 , t r i_num=0;
cl rscr ( ) ;
pr int f (“What Tr iangular number do you want :”) ;
OUTPUT:
What Tr iangular number do you want? : 5
Tr iangular number of 5 i s 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 ‘ t r i_num’ variable. When the loop terminates the ‘ t r i_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 ;
cl rscr ( ) ;
pr int f (“Enter Number :”) ;
scanf (“%d” , &j ) ;
cl rscr ( ) ;
pr int f (“ Numbers :”) ;
for ( i=1; i<=j ; i++)
pr int f (“%5d” , i ) ;
pr int f (“\n\nSquares:”) ;
for ( i=1; i<=j ; i++)
{
pr int f (“%5d” , i*i ) ;
sum=sum+i ;
ssum=ssum+i*i ;
}
pr int f (“\n\nSum of Numbers f rom 1 to %d :%d” , j , sum) ;
pr int f (“\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 f rom 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.
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 sqr t () 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( )
exi t (0) ;
{
int a , b , c , d , e , sum=0 , i ;
cl rscr ( ) ;
pr int f (“\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–- )
{
i f ( i==a | | i==b | | i==c | | i==d | | i==e)
{
pr int f (“The Larges t Number : %d” , i ) ;
exi t (0) ;
}
}
}
OUTPUT:
Enter Five numbers : 5 2 3 7 3
The Larges t 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 ex i t ( ) 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 ;
cl rscr ( ) ;
pr int f (“\nEnter Five numbers :”) ;
scanf (“%d %d %d %d %d” , &a , &b , &c , &d , &e) ;
pr int f (“\n Numbers in ascending order :”) ;
sum=a+b+c+d+e;
for ( i=1; i<=sum; i++)
{
i f ( i==a | | i==b | | i==c | | i==d | | i==e)
{
pr int f (“%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 i f 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;
cl rscr ( ) ;
pr int f (“\n Enter two numbers :”) ;
scanf (“%d %d” , &a , &b) ;
for (c=1;c<=b;c++)
d=(d) - ( -a) ;
pr int f (“Mul t ipl icat ion of %d * %d :%d” , a , b , d) ;
getche( ) ;
}
OUTPUT:
Enter two numbers : 5 5
Mul t ipl icat ion 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;
cl rscr ( ) ;
pr int f (“\n Enter two numbers:”) ;
scanf (“%d %d” , &a , &b) ;
for ( ; ; )
{
d=d+a;
i f (c==b)
goto s top;
c++;
}
stop:
pr int f (“Mul t ipl icat ion of %d * %d :%d” , a , b , d) ;
getche( ) ;
}
OUTPUT:
Enter two numbers : 8 4
Mul t ipl icat ion 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;
cl rscr ( ) ;
pr int f (“\nEnter The Marks of Five Subject s”) ;
for ( i=1; i<=5; i++)
{
pr int f (“\n[%d] Student :” , i ) ;
i f (scanf (“%d %d %d %d %d” , &a , &b , &c , &d , &e)==5)
{
sum=a+b+c+d+e;
avg=sum/5;
pr int f (“\n Total Marks of Student [%d] %d” , i , sum) ;
pr int f (“\n Average Marks of Student [%d] %f \n” , i , avg) ;
}
else
{
cl rscr ( ) ;
pr int f (“\n Type Mismatch”) ;
}
}
}
OUTPUT:
Enter The Marks of Five Subject s
[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.
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;
cl rscr ( ) ;
pr int f (“\n Enter Number :”) ;
scanf (“%d” , &number ) ;
pr int f (“\n Enter Power :”) ;
scanf (“%d” , &power ) ;
ans=1;
for ( i=1; i<=power ; i++)
ans*=number ;
pr int f (“\n The Power of %d rai sed to %d is %ld\n” , number ,
power , ans) ;
getche( ) ;
}
OUTPUT:
Enter Number : 5
Enter Power : 3
The Power of 5 rai sed to 3 i s 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;
cl rscr ( ) ;
for (a=3;a>=1;a–- )
{
for (b=1;b<=2;b++)
{
sub=a-b;
pr int f (“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 ;
cl rscr ( ) ;
for ( i=1; i<=3; i++) /* outer loop */
{
for ( j=1; j<=2; j++) /* inner loop */
pr int f (“\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;
cl rscr ( ) ;
for (a=1;a<=2;a++) /* outer loop */
{
for (b=1;b<=2;b++) /* middle loop */
{
for (c=1;c<=2;c++) /* inner loop */
pr int f (“\n a=%d + b=%d + c=%d : %d” , a , b , c , a+b+c) ;
pr int f (“\n Inner Loop Over . ”) ;
}
pr int f (“\n Middle Loop Over . ”) ;
}
pr int f (“\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;
cl rscr ( ) ;
pr int f (“Enter a Number :”) ;
scanf (“%d” , &k) ;
for ( i=1; i<k; i++)
{
for ( j=1; j<=i ; j++)
{
i f ( i==pow( j , 3) )
pr int f (“\nNumber : %d & i t ’s Cube :%d” , j , i ) ;
}
}
}
OUTPUT:
Enter a Number : 100
Number : 1 & i t ’s Cube : 1
Number : 2 & i t ’s Cube : 8
Number : 3 & i t ’s Cube : 27
Number : 4 & i t ’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 i f 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;
cl rscr ( ) ;
pr int f (“\ t Table of 1 to 100 Numbers Us ing ASCI I Values \n”) ;
pr int f (“\ t ===== == = == === ======= ===== ===== ======\n”) ;
for ( i=48; i<=57; i++ , k++)
{
for ( j=49; j<=57; j++)
pr int f (“%5c%c” , i , j ) ;
i f (k!=1)
pr int f (“%5c%c” , i+1 , 48) ;
i f (k==0)
pr int f (“\b\b%d%d%d” , k+1 , k , k) ;
pr int f (“\n\n”) ;
}
getche( ) ;
}
OUTPUT:
Table of 1 to 100 Numbers Us ing ASCI I 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 pr int f ( ) statement. The first i f statement is
used for printing 10, 20, 30 up to 90 numbers. The second i f 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.
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.
int h , m , s ;
cl rscr ( ) ;
for (h=1;h<=12;h++)
{
cl rscr ( ) ;
for (m=1;m<=59;m++)
{
cl rscr ( ) ;
for (s=1; s<=59; s++)
{
gotoxy(8 , 8) ;
pr int f (“hh mm ss\n”) ;
gotoxy(8 , 9) ;
pr int f (“%d %d %d” , h , m , s) ;
s leep(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 ;
stat ic int s t [10] ;
cl rscr ( ) ;
pr int f (“\n Enter a Decimal Number :”) ;
scanf (“%d” , &n) ;
for ( l=1; l<=n; l++)
{
t=l ;
whi le( t !=0)
{
k=t%10;
t=t /10;
s t [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 wh i l e 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 ar ray s t [10] is initialized
to 0 using static storage class. The variable ‘k’ is used as an argument with s t [ ] , and it is
incremented. The value of ‘k’, whatever it contains when used in arrays s t [ ] 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;
cl rscr ( ) ;
pr int f (“\n Enter a Number :”) ;
scanf (“%d” , &n) ;
pr int f (“\n Sum of Digi t s t i l l a single digi t \n %d” , n) ;
for ( ; n!=0 ; )
{
s=s+n%10;
n=n/10;
i f (n==0 && s>9)
{
OUTPUT:
Enter a Number :4687
Sum of Digi t s t i l l a s ingle digi t
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;
cl rscr ( ) ;
pr int f (“ Binary Bi t s Par i ty Bi ts \n”) ;
pr int f (“ =========== ===========”) ;
for (x=0;x<8;x++)
{
k++;
j=12;
y=x;
for (a=0;a<3;a++)
{
b=y%2;
gotoxy( j -=3 , k) ;
pr int f (“%d” , b) ;
y=y/2;
i f (b==1)
c++;
}
i f (c%2==0)
{
gotoxy(25 , k) ;
pr int f (“%d” , 1) ;
}
else
{
gotoxy(25 , k) ;
pr int f (“%d” , 0) ;
}
c=0;
}
}
OUTPUT:
Binary Bi t s Par i ty Bi t s
=========== ===========
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! */
el se
{
for ( l=1; l<=i ; l++)
f=f*l ;
sum=sum+pow(x , i ) / f ;
}
c++;
}
pr int f (“\nSum of ser ies Numbers :%f” , sum) ;
getche( ) ;
}
OUTPUT:
Enter x & n : 2 5
Sum of ser ies 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 i f are used for
calculating the factorials. The i f 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! */
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).
cube=0;
x=1;
d=3;
n=k;
whi le(x<=d)
{
i=n%10;
cube=cube+pow( i , 3) ;
n=n/10;
x++;
}
i f (cube==k)
pr int f (“\n\ t \ %d” , k) ;
}
}
OUTPUT:
The Fol lowing Numbers are Armst rong 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 ;
cl rscr ( ) ;
pr int f (“How many l ines stars (*) should be pr inted ? :”) ;
scanf (“%d” , &x) ;
for ( i=1; i<=x; i++)
{
for ( j=1; j<=i ; j++)
{
pr int f (“*”) ;
}
pr int f (“\n”) ;
}
}
OUTPUT:
How many l ines s tars (*) should be pr inted ? : 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
pr int f ( ) 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;
cl rscr ( ) ;
pr int f (“Enter a Number :”) ;
scanf (“%d” , &i ) ;
for ( ; i>=0; i–- )
{
c=i ;
pr int f (“\n”) ;
for ( ; ; )
{
pr int f (“%3d” , c) ;
i f (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 i f 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;
pr int f (“\nEnter Value of x :”) ;
scanf (“%d” , &x) ;
cl rscr ( ) ;
for ( j=1; j<=x; j++)
{
for ( i=1; i<=j ; i++)
pr int f (“%3d” , i ) ;
pr int f (“\n”) ;
}
pr int f (“\n”) ;
for ( j=x; j>=1; j–- )
{
for ( i=j ; i>=1; i–- )
pr int f (“%3d” , i ) ;
pr int f (“\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;
pr int f (“\n Enter A number :”) ;
scanf (“%d” , &x) ;
cl rscr ( ) ;
for ( j=0; j<=x; j++)
{
gotoxy(p , j+1) ;
/* pos i t ion curosr on screen (x cordinate , y cordinate) */
for ( i=0- j ; i<=j ; i++)
pr int f (“%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 ;
cl rscr ( ) ;
pr int f (“\n Values in di f ferent I terat ions . \n”) ;
pr int f (“====== == ========= ===========\n”) ;
for ( i=0; i<4; i++)
{
y=y*2+x[ i+1] ;
pr int f (“[%d] %d\ t” , i+1 , y) ;
}
pr int f (“\nEquivalent of [”) ;
for ( i=0; i<5; i++)
pr int f (“%d” , x[ i ] ) ;
pr int f (“] in Decimal Number i s :”) ;
pr int f (“%d\ t” , y) ;
getche( ) ;
}
OUTPUT:
Values in di f ferent I terat ions .
=======================
[1] 3 [2] 7 [3] 15 [4] 31
Equivalent of [1 1 1 1 1] in Decimal Number i s : 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 bi t [5] , j , c=0;
cl rscr ( ) ;
pr int f (“\n Enter four bi t s :”) ;
for ( j=0; j<4; j++)
{
scanf (“%d” , &bi t [ j ] ) ;
i f (bi t [ j ]==1)
c++;
else
i f (bi t [ j ]>1 | | bi t [ j ]<0)
{
j–- ;
cont inue;
}
}
i f (c%2==0)
bi t [ j ]=0;
else
bi t [ j ]=1;
pr int f (“\n Message bi t s together wi th par i ty bi t :”) ;
for ( j=0; j<5; j++)
pr int f (“%d” , bi t [ j ] ) ;
}
OUTPUT:
Enter four bi t s : 1 1 1 1
Message bi t s together wi th par i ty bi t : 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 i f
statement.
6.44 Write a program to convert a binary to decimal number. Enter the binary bits by using the
for loop.
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] ;
cl rscr ( ) ;
pr int f (“Enter Four Bi t s :”) ;
for (x=0;x<4;x++)
{
scanf (“%d” , &a[x] ) ;
i f (a[x]>1 | | a[x]<0)
{
x–- ;
cont inue;
}
}
pr int f (“Enter Four Bi t s :”) ;
for (x=0;x<4;x++)
{
scanf (“%d” , &b[x] ) ;
i f (b[x]>1 | | b[x]<0)
{
x–- ;
cont inue;
}
}
pr int f (“\nA B C”) ;
for (x=0;x<4;x++)
{
i f (a[x]==1 && b[x]==1)
c[x]=1;
el se
c[x]=0;
pr int f (“\n%d %d %d” , a[x] , b[x] , c[x] ) ;
}
}
OUTPUT:
Enter Four Bi t s: 1 0 1 0
Enter Four Bi t s: 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 i f 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] ;
cl rscr ( ) ;
pr int f (“Enter Four Bi t s :”) ;
for (x=0;x<4;x++)
{
scanf (“%d” , &a[x] ) ;
i f (a[x]>1 | | a[x]<0)
{
x–- ;
cont inue;
}
}
pr int f (“Enter Four Bi t s :”) ;
for (x=0;x<4;x++)
{
scanf (“%d” , &b[x] ) ;
i f (b[x]>1 | | b[x]<0)
{
x–- ;
cont inue;
}
}
for (x=0;x<4;x++)
{
i f (a[x]==0 && b[x]==0)
c[x]=0;
el se
c[x]=1;
pr int f (“\n%d %d %d” , a[x] , b[x] , c[x] ) ;
}
}
OUTPUT:
Enter Four Bi t s: 1 1 1 0
Enter Four Bi t s: 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 i f 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] ;
cl rscr ( ) ;
pr int f (“Enter Four Bi t s :”) ;
for (x=0;x<4;x++)
{
scanf (“%d” , &a[x] ) ;
i f (a[x]>1 | | a[x]<0)
{
x–- ;
cont inue;
}
}
pr int f (“Enter Four Bi t s :”) ;
for (x=0;x<4;x++)
{
scanf (“%d” , &b[x] ) ;
i f (b[x]>1 | | b[x]<0)
{
x–- ;
cont inue;
}
}
pr int f (“\nA B C”) ;
for (x=0;x<4;x++)
{
i f (a[x]==0 && b[x]==1)
c[x]=1;
el se
i f (a[x]==1 && b[x]==0)
c[x]=1;
el se
c[x]=0;
pr int f (“\n%d %d %d” , a[x] , b[x] , c[x] ) ;
}
}
OUTPUT:
Enter Four Bi t s: 1 1 1 0
Enter Four Bi t s: 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 i f 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( )
{
stat ic int c[7] ;
int x , b[4] ;
cl rscr ( ) ;
pr int f (“\n Read the Binary Numbers :”) ;
for (x=0;x<4;x++)
scanf (“%d” , &b[x] ) ;
/* piece copy operat ion */
c[0]=b[0] ;
c[1]=b[1] ;
c[2]=b[2] ;
c[4]=b[3] ;
pr int f (“\n Before XOR operat ion :”) ;
for (x=0;x<=6;x++)
pr int f (“%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] ;
pr int f (“\n Hamming code af ter XOR operat ion :”) ;
for (x=0;x<=6;x++)
pr int f (“%3d” , c[x] ) ;
getche( ) ;
}
OUTPUT:
Read the Binary Numbers : 1 0 1 0
Before XOR operat ion : 1 0 1 0 0 0 0
Hamming code af ter XOR operat ion : 1 0 1 0 0 1 0
Explanation:
The hamming code that contains seven bits is initially assumed as zeros. This is declared
with s t a t i c i n t 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.
To t a l Ma r ks Re s u l t
>=420 Di st inct ion
>=360 Fi rs t Divi s ion
>=240 Second Divi s ion
Otherwi se Fai l
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
i f–el se 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.
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
whi le loop.
void main( )
{
int x=1;
whi le(x<10)
{
pr int f (“\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 ‘whi le’ 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 whi le 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
whi le 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 whi le loop.
void main( )
{
int a=1 , sum=0;
cl rscr ( ) ;
whi le(a<=10)
{
pr int f (“%3d” , a) ;
sum=sum+a;
a++;
}
pr int f (“\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 wh i l e 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 wh i l e loop ‘a’ is incremented
and added to ‘sum’. When the value of ‘a’ reaches 10, the condition given in wh i l e
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 whi le loop.
void main( )
{
int a , fact=1;
cl rscr ( ) ;
pr int f (“\n Enter The Number :”) ;
scanf (“%d” , &a) ;
whi le(a>=1)
{
pr int f (“ %d *” , a) ;
fact=fact*a;
a–- ;
}
pr int f (“ = %d” , fact ) ;
pr int f (“\n Factor ial of Given number is %d” , fact ) ;
}
OUTPUT:
Enter The Number : 5
5* 4 * 3 * 2 * 1 * = 120
Factor ial of Given number i s 120
Explanation:
In the above program, the working of the whi le 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 whi le 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 whi le
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;
cl rscr ( ) ;
pr int f (“\n Enter The Number :”) ;
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 whi le loop. Once
the value of the variable ‘b’ matches with the entered number ‘a’, the whi le 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;
cl rscr ( ) ;
pr int f (“Enter a Number :”) ;
scanf (“%d” , &x) ;
pr int f (“\n Binary Number :”) ;
whi le(x!=0)
{
gotoxy(y–- , 3) ;
pr int f (“%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 wh i l e loop is executed till the value of ‘x’ becomes non-zero. The
body of the wh i l e loop contains the mod (%) and d i v i de 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 go t oxy( ) function. In the statement go t oxy (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;
cl rscr ( ) ;
pr int f (“Enter the Decimal Number :”) ;
scanf (“%d” , &m) ;
pr int f (“Enter base of number System :”) ;
scanf “%d” , &b) ;
pr int f (“The Number Obtained :”) ;
whi le(m!=0)
{
gotoxy(y–- , 3) ;
pr int f (“%d” , m%b) ;
m=m/b;
}
getche( ) ;
}
OUTPUT:
Enter the Decimal Number : 50
Enter base of number Sys tem : 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.
x=n%10;
i f (x>1 | | x<0)
{
pr int f (“\n Inval id Digi t . ”) ;
exi t (1) ;
}
y=y+x*pow(2 , p) ;
n=n/10;
p++;
}
pr int f (“\n Equivalent Decimal Number is %d . ” , y) ;
getche( ) ;
}
OUTPUT:
Enter a Binary Number : 1111
Equivalent Decimal Number i s 15
Enter a Binary Number : 120
Inval id Digi t .
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.
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 whi le 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;
cl rscr ( ) ;
pr int f (“Enter a Number :”) ;
scanf (“%d” , &n) ;
whi le(n!=0)
{
k=n%10;
sum=sum+k;
k=n/10;
n=k;
}
pr int f (“Sum of digi ts %d “ , sum) ;
}
OUTPUT:
Enter a Number : 842
Sum of digi t s 14
Explanation:
In the above program, a number is entered by the user. It is assigned to variable ‘ n ’. In
the wh i l e loop mod and d i v i s i on operations are done on the entered number. At each
rotation of wh i l e 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 wh i l e 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;
cl rscr ( ) ;
pr int f (“\n Enter Numbers (0) Exi t :”) ;
whi le( j !=0)
{
Explanation:
Numbers are entered through the keyboard. The i f statement checks whether the entered
numbers are greater or less than zero. If the numbers are greater than zero the i f block is
executed otherwise the el se block is executed. The output shows the number of positive
and negative numbers and their sums. When 0 is entered whi le loop terminates.
6.60 Read an integer through the keyboard. Sort odd and even numbers by using whi le 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;
cl rscr ( ) ;
pr int f (“Enter a Number :”) ;
scanf (“%d” , &a) ;
pr int f (“ODD EVEN”) ;
pr int f (“\n”) ;
whi le(c<=a) /* A
{
b=c%2;
whi le(b==0){/* B
pr int f (“\ t%d “ , c) ;
even=even+c;
b=1;}
b=c%2;
whi le(b!=0){ /*c
pr int f (“\n%d” , c) ;
odd=odd+c;
b=0;}
c++;
}
pr int f (“\n===============”) ;
pr int f (“\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 whi le loops. When the entered number is even
the first loop (B loop) is executed and number is added to variable ‘even’, otherwise the
whi le 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 ;
cl rscr ( ) ;
pr int f (“Enter the number of digi ts : -”) ;
scanf (“%d” , &d) ;
pr int f (“\nEnter the number which i s to be reversed: -”) ;
scanf (“%d” , &n) ;
pr int f (“\nThe Reversed Number i s : -”) ;
whi le(x<=d)
{
i=n%10;
pr int f (“%d” , i ) ;
n=n/10;
x++;
}
getche( ) ;
}
OUTPUT:
Enter the number of digi t s : - 4
Enter the number which i s to be reversed: - 5428
The Reversed Number i s : - 8245
Explanation:
The statements following the whi le 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.
Explanation:
The array scan[40] contains the string. The string is to be entered by the user. The arrays
smal l [20] , num[20] and oth[20] are used at run time in the program. The whi le loop
reads the array scan[] character by character. The i f–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.
ASCI I values Cor responding Symbol s
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;
cl rscr ( ) ;
pr int f (“NUMBERS \n”) ;
whi le( i<=57)
{
pr int f (“%c” , i ) ;
i++;
}
i+=7;
pr int f (“\n\n CAPITAL ALPHABETS\n”) ;
whi le( i<=90)
{
pr int f (“ %c” , i ) ;
i++;
}
i+=6;
pr int f (“\n\n SMALL ALPHABETS \n”) ;
whi le( i<=122)
{
pr int f (“%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 whi le loops are used. These three whi le 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 whi le 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
pr int f (“%2c” , i ) ;
}
i++;
}
}
Explanation:
The output of the above program is the same as for the previous one. Instead of nested
whi le loop, nested i f–else statements are used.
6.65 Write a program to use three whi le nested loops. Print numbers after each iteration and
messages after termination of each loop.
void main( )
{
int i=1 , j=1 , k=1;
cl rscr ( ) ;
whi le( i<4)
{
whi le( j<3)
{
whi le(k<2)
{
pr int f (“\n\n i=%d j=%d k=%d” , i , j , k) ;
k++;
}
pr int f (“\n Inner Loop (k) Completed . ”) ;
k=1;
j++;
}
pr int f (“\n Middle Loop ( j ) Completed . ”) ;
j=1;
i++;
}
pr int f (“\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;
}
whi le(condi t ion) ;
The difference between the whi le and do-whi le loop is the place where the condition is to be
tested. In the whi le loops the condition is tested following the whi le statement, and then the body gets
executed, whereas in the do-whi le the condition is checked at the end of the loop. The do-whi le loop
will execute at least one time even if the condition is false initially. The do-whi le loop executes until the
condition becomes false. The comparison between the whi le and do-whi le loop is given in Table 6.6
Some programs are given on do-whi le loop.
6.66 Use the do–whi le loop and display a message ‘this is a program of do–whi le loop’ five
times.
void main( )
{
int i=1;
cl rscr ( ) ;
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-whi le loop.
Also perform sum and multiplication with their digits.
void main( )
{
int n , d , x=1 , mul=1 , sum=0;
int i ;
cl rscr ( ) ;
pr int f (“Enter the number of digi t s : -”) ;
scanf (“%d” , &d) ;
pr int f (“\nEnter the number which is to be reversed: -”) ;
scanf (“%d” , &n) ;
pr int f (“\n Reversed Number : -”) ;
do
{
i=n%10;
pr int f (“%d” , i ) ;
sum=sum+i ;
mul=mul*i ;
n=n/10;
x++;
}
whi le(x<=d) ;
pr int f (“\n Addi t ion of digi t s : - %4d” , sum) ;
pr int f (“\n Mul t ipl icat ion of digi ts : - %4d” , mul ) ;
getche( ) ;
}
OUTPUT:
Enter the number of digi t s : 4
Enter the number which i s 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–whi le 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;
cl rscr ( ) ;
pr int f (“Enter The number for test ing (pr ime or not ) :”) ;
scanf (“%d” , &n) ;
do
{
i f (n%x==0)
{
pr int f (“\n The number %d i s not pr ime . ” , n) ;
getch( ) ;
exi t (0) ;
}
x++;
}
whi le(x<n) ;
pr int f (“\n The number %d i s pr ime . ” , n) ;
getche( ) ;
}
OUTPUT:
Enter The number for test ing (pr ime or not ) : 5
The number 5 i s pr ime .
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 ;
cl rscr ( ) ;
pr int f (“\nEnter data of 5 boys\n”) ;
pr int f (“\nAge Weight \n”) ;
do
{
scanf (“%d %f” , &age , &wt ) ;
i f ( age<25 && wt<50)
{
count++;
}
x++;
}
whi le(x<=5) ;
pr int f (“\n Number of boys wi th age <25”) ;
pr int f (“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 wi th age <25 and weight <50 kgs = 2
Explanation:
In the above-given program, age and weight of five boys are entered. The i f 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–whi le loop.
void main( )
{
int a , fact=1;
cl rscr ( ) ;
pr int f (“\n Enter The Number :”) ;
scanf (“%d” , &a) ;
do
{
pr int f (“ %d *” , a) ;
fact=fact*a;
a- - ;
}
whi le(a>=1) ;
pr int f (“ = %d” , fact ) ;
pr int f (“\n Factor ial of Given number is %d” , fact ) ;
}
OUTPUT:
Enter The Number : 5
5 * 4 * 3 * 2 * 1 * = 120
Factor ial of Given number i s 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–whi le 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;
cl rscr ( ) ;
pr int f (“\n Enter a number :”) ;
scanf (“%d” , &i ) ;
do
{
pr int f (“%d +” , a) ;
s=s+a;
a++;
}
whi le(a<=i ) ;
pr int f (“\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-whi le 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.
{
s tatement / s ;
}
whi le(condi t ion) ;
6.73 Write a program to use whi le statement in do–whi le loop and print values from 1 to 5.
void main( )
{
int x=0;
cl rscr ( ) ;
do whi le(x<5)
{
x++;
pr int f (“\ t %d” , x) ;
}
whi le(x<1) ;
}
OUTPUT:
1 2 3 4 5
Explanation:
The specialty of using the second whi le loop in the above program is to know that the
programmer can take the second whi le 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 whi le loop and (iii) the do-wh i l e 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.
5. The whi le(1) is an infinite loop. 8. The do-whi le loop must be terminated by a
semi-colon.
6. The loop cannot be nested.
9. The { } defines the block of the statement.
7. Even if the condition is false the do-whi le
loop executes once. 10. In case { } is not defined, the default scope is one
statement
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;
cl rscr ( ) ; 3. What will be the value of ‘f’ after the execution of
whi le(d<=9) following program?
{
pr int f(“\n %d %d”,++d,++c) ; void main( )
} {
} char k;
(a) 11 float f=65;
(b) 10 cl rscr ( ) ;
(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? }
pr int f (“\nf=%g” , f ) ;
void main( )
{ }
int k; (a) f=64
float x=0;
cl rscr ( ) ; (b) f=-65
for (k=0;k<10;k++) (c) f=66
x+= . 1; (d) None of the above
pr int f (“\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-whi le 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-whi le 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-whi le 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 whi le 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–whi le loop. ing ASCII equivalent number. Use the whi le
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–whi le 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-whi le
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-whi le 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 spr int f ( ) 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;
pr int f (“%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.
int main( )
{
int num[5]={1 , 2 , 3 , 2 , 5};
cl rscr ( ) ;
pr int f (“\n num[0] = %d Address : %u” , num[0] , &num[0] ) ;
pr int f (“\n num[1] = %d Address : %u” , num[1] , &num[1] ) ;
pr int f (“\n num[2] = %d Address : %u” , num[2] , &num[2] ) ;
pr int f (“\n num[3] = %d Address : %u” , num[3] , &num[3] ) ;
pr int f (“\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;
cl rscr ( ) ;
pr int f (“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 ar ray
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 s tat ic, 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 ;
cl rscr ( ) ;
for ( j=0; j<5; j++)
pr int f (“\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.
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] ;
cl rscr ( ) ;
pr int f (“The type ‘ int ’ requi res %d Bytes” , sizeof ( int ) ) ;
pr int f (“\nThe type ‘char ’ requi res %d Bytes” , s izeof (char ) ) ;
pr int f (“\nThe type ‘ long’ requi res %d Bytes” , s izeof ( long) ) ;
pr int f (“\n %d memory locat ions are reserved for ten ‘ int ’
element s” , s izeof ( i ) ) ;
pr int f (“\n %d memory locat ions are reserved for ten ‘char ’
element s” , s izeof (c) ) ;
pr int f (“\n %d memory locat ions are reserved for ten ‘ long’
element s” , s izeof ( l ) ) ;
}
OUTPUT:
The type ‘ int ’ requi res 2 Bytes
The type ‘char ’ requi res 1 Bytes
The type ‘ long’ requi res 4 Bytes
20 memory locat ions are reserved for ten ‘ int ’ element s
10 memory locat ions are reserved for ten ‘char ’ elements
40 memory locat ions are reserved for ten ‘ long’ elements
Explanation:
The s izeof ( ) 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: Detailed 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;
cl rscr ( ) ;
pr int f (“\n Character Memory Locat ion \n”) ;
whi le(name[ i ] !=‘ \0’ )
{
pr int f (“\n [%c] \ t \ t [%u]” , name[ i ] , &name[ i ] ) ;
i++;
}
}
OUTPUT:
Character Memory Locat ion
[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;
cl rscr ( ) ;
for ( i=1; i<=10; i++)
{
i f ( i%2==0)
even[++a]=i ;
el se
odd[++b]=i ;
}
pr int f (“\n\ tEven \ t \ tOdd”) ;
for ( i=0; i<5; i++)
{
pr int f (“\n\ t %d\ t \ t %d” , even[ i ] , odd[ i ] ) ;
sume=sume+even[ i ] ;
sumo=sumo+odd[ i ] ;
}
pr int f (“\n\ t=====================\n”) ;
pr int f (“Addi t ion: %d %14d” , sume , sumo) ;
}
OUTPUT:
Even Odd
2 1
4 3
6 5
8 7
10 9
=============
Addi t ion: 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] ;
cl rscr ( ) ;
for ( i=0; i<5; i++)
{
pr int f (“\nEnter Number [%d] :” , i+1) ;
scanf (“%d” , &num[ i ] ) ;
}
pr int f (“\n=================================”) ;
for ( i=0; i<5; i++)
{
i f (num[ i ]%2==0)
{
pr int f (“\n Even Number : %d” , num[ i ] ) ;
a=a+num[ i ] ;
}
el se
{
pr int f (“\n Odd Number : %d” , num[ i ] ) ;
m=m*num[ i ] ;
}
}
pr int f (“\n=================================”) ;
pr int f (“\n Addi t ion of Even Numbers : %d” , a) ;
pr int f (“\n Product of Odd Numbers :%d” , m) ;
pr int f (“\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
=================================
Addi t ion 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 pr int f ( ) 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( )
{
s tat ic char s[15] ;
int i , c=0;
char f ;
cl rscr ( ) ;
put s(“Enter a St r ing :”) ;
get s(s) ;
put s(“Enter a Character to Find :”) ;
f=getchar ( ) ;
for ( i=0; i<=15; i++)
{
i f (s[ i ]==f )
c++;
}
pr int f (“The Character (%c) in a St r ing (%s) occurs %d t imes . ” , f , s , c) ;
}
OUTPUT:
Enter a St r ing : programmer
Enter a Character to Find : r
The Character ( r ) in a St r ing (programmer ) occurs (3) t imes .
Explanation:
In this program, the string and a single character are entered through the keyboard. Inside the
for loop, the i f 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};
cl rscr ( ) ;
pr int f (“Element of Ar ray 1st - 2nd Ar ray Addt ion\n”) ;
OUTPUT:
Element of Ar ray 1s t - 2nd Ar ray Addi t ion
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( )
{
s tat ic uns igned char l , r , i , real [3] [5] , ima[3] [5] ;
long c;
cl rscr ( ) ;
for ( l=0; l<3; l++)
{
pr int f (“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] ;
pr int f (“\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 ;
cl rscr ( ) ;
pr int f (“\nEnter numbers between 1 to 7 : \n”) ;
for ( i=0; i<=6; i++)
scanf (“%d” , &day[ i ] ) ;
for ( i=0; i<=6; i++)
swi tch(day[ i ] )
{
case 1:
pr int f (“\n%ds t day of week is Sunday” , day[ i ] ) ;
break;
case 2:
pr int f (“\n%dnd day of week is Monday” , day[ i ] ) ;
break;
case 3:
pr int f (“\n%drd day of week is Tuesday” , day[ i ] ) ;
break;
case 4:
pr int f (“\n%dth day of week is Wednesday” , day[ i ] ) ;
break;
case 5:
pr int f (“\n%dth day of week is Thursday” , day[ i ] ) ;
break;
case 6:
pr int f (“\n%dth day of week is Fr iday” , day[ i ] ) ;
break;
case 7:
pr int f (“\n%dth day of week is Saturday” , day[ i ] ) ;
break;
defaul t :
pr int f (“\n %dth i s Inval id 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 swi tch( )
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 ci ty[6]={‘N’ , ’A’ , ’N’ , ’D’ , ’E’ , ’D’};
int i , pin[6]={4 , 3 , 1 , 6 , 0 , 3};
cl rscr ( ) ;
for ( i=0; i<6; i++)
pr int f (“%c” , ci ty[ i ] ) ;
pr int f (“-”) ;
for ( i=0; i<6; i++)
pr int f (“%d” , pin[ i ] ) ;
}
OUTPUT:
NANDED – 431603
Explanation:
In the above example, two arrays of different data types are printed through pr int f ( )
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.
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 pr inf ( ) 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.
i f ( i+1==12)
pr int f (“Month (%d) Contains 28 days . ” , month[ i ] ) ;
i f ( i+1<8)
pr int f (“Month (%d) Contains 31 days . ” , month[ i ] ) ;
i f ( i+1>7 && i+1!=12)
pr int f (“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 i f statement checks where this month number appears in the
array. Whenever there is a match control goes to the compare statements. The i f 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 i tem[12] ;
cl rscr ( ) ;
pr int f (“\ tEnter Month No . -Sale of an I tem/month\n”) ;
for (sale=0; sale<=11; sale++)
{
pr int f (“\ t \ t %d =” , sale+1) ;
scanf (“%d” , &i tem[sale] ) ;
}
for (sale=0; sale<=11; sale++)
sum=sum+i tem[sale] ;
avg=sum/12;
pr int f (“\n\ t Average Sale of an i tem /month=%f” , avg) ;
}
OUTPUT:
Enter Month No . -Sale of an I tem/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 i tem /month= 543 . 750000
Explanation:
In the above program, sales of 12 months are entered and stored in an array i tem[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 , pr ice[4]={25000 , 30000 , 35000 , 40000};
int s tock[4]={25 , 20 , 15 , 20};
cl rscr ( ) ;
pr int f (“\ t Stock & Total Cos t Detai ls \n”) ;
pr int f (“=======================================\n”) ;
pr int f (“Model \ t Qty . \ tRate (Rs . ) Total Value”) ;
pr int f (“\n=======================================”) ;
for ( i=0; i<=3; i++)
{
pr int f (“\nPent ium%d %d %8ld %15ld” , pccode[ i ] , stock[ i ] , pr ice[ i ] ,
pr ice[ i ]*stock[ i ] ) ;
t=t+pr ice[ i ]*s tock[ i ] ;
}
pr int f (“\n=======================================\n”) ;
pr int f (“Total Value of Al l PCs in Rs . %ld” , t ) ;
pr int f (“\n=======================================\n”) ;
}
OUTPUT:
Stock & Total Cost Detai l s
=======================================
Model Qty . Rate (Rs . ) Total Value
=======================================
Pent ium1 25 25000 625000
Pent ium2 20 30000 600000
Pent ium3 15 35000 525000
Pent ium4 20 40000 800000
=======================================
Total Value of Al l PCs in Rs . 2550000
======================================
Explanation:
Here, in the above program, three integer arrays pccode[ ] , pr ice[ ] and s tock[ ]
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 pr ice[ ] 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 pr int f ( ) statement.
7.17 Write a program to display the given message by using putc( ) and stdout ( ) functions.
void main(void)
{
char msg[ ] = “C i s Easy”;
int i = 0;
cl rscr ( ) ;
whi le(msg[ i ] )
putc(msg[ i++] , s tdout ) ;
}
OUTPUT:
C i s 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’.