100% found this document useful (2 votes)
2K views689 pages

Programming in C

Uploaded by

zfgfxc9nkg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views689 pages

Programming in C

Uploaded by

zfgfxc9nkg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 689

PROGRAMMING IN C

THIRD EDITION

Ashok N. Kamthane
Associate Professor
Shri Guru Gobind Singhji Institute of Engineering
and Technology, Nanded, Maharashtra, India

A01_KAMT3553_02_SE_FM.indd 1 5/17/2015 8:59:35 AM


DEDI CAT I O N
To My Beloved Late Grandfather
Jagganath Kamthane

Associate Editor—Acquisitions: Neha Goomer


Editor—Production: G Sharmilee

Copyright © 2015 Pearson India Education Services Pvt. Ltd

Copyright © 2006, 2012 Dorling Kindersley (India) Pvt. Ltd


This book is sold subject to the condition that it shall not, by way of trade or otherwise, be lent, resold,
hired out, or otherwise circulated without the publisher’s prior written consent in any form of binding
or cover other than that in which it is published and without a similar condition including this condition
being imposed on the subsequent purchaser and without limiting the rights under copyright reserved
above, no part of this publication may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording or otherwise),
without the prior written permission of both the copyright owner and the publisher of this book.

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]

Compositor: Mukesh Technologies Pvt. Ltd


Printed in India

A01_KAMT3553_02_SE_FM.indd 2 5/17/2015 8:59:36 AM


CONTENTS

Preface xi
Acknowledgements xiv
About the Author xv

1 Basics and Introduction to C .............................................................. 2


1.1 Why to Use Computers? 3
1.2 Basics of a Computer 3
1.3 Latest Computers 5
1.4 Introduction to C 6
1.5 About ANSI C Standard 7
1.6 Machine, Assembly and High-Level Language 7
1.6.1 Assembly Language 8
1.6.2 High-Level Language 8

1.7 Assembler, Compiler and Interpreter 8


1.8 Structure of a C Program 10
1.9 Programming Rules 12
1.10 Executing the C Program 12
1.11 Standard Directories 16
1.12 The First C Program 16
1.13 Advantages of C 17
1.14 Header Files 17
1.15 Algorithm 18
1.15.1 Program Design 20

1.16 Classification of Algorithms 21


1.17 Flowcharts 22
1.18 Pseudocode 26
Summary 28
Exercises 28

2 The C Declarations ............................................................................ 32


2.1 Introduction 33
2.2 The C Character Set 33
2.3 Delimiters 34

A01_KAMT3553_02_SE_FM.indd 3 5/17/2015 8:59:36 AM


Contents v

4 Input and Output in C ........................................................................ 84


4.1 Introduction 85
4.2 Formatted Functions 86
4.3 Flags, Widths and Precision with Format String 88
4.4 Unformatted Functions 99
4.5 Commonly Used Library Functions 104
4.6 Strong Points for Understandability 105
Summary 106
Exercises 106

5 Decision Statements ....................................................................... 112


5.1 Introduction 113
5.2 The i f Statement 114
5.3 The i f–el se Statement 116
5.4 Nested i f–else Statements 120
5.5 The i f -el se- i f Ladder Statement 121
5.6 The break Statement 129
5.7 The cont inue Statement 130
5.8 The goto Statement 130
5.9 The swi tch Statement 132
5.10 Nested swi tch case 144
5.11 The swi tch case and nested i fs 146
Summary 147
Exercises 148

6 Loop Control .................................................................................... 154


6.1 Introduction
6.1.1 What is a Loop?
155
155

6.2 The for Loop 156


6.3 Nested for Loops 172
6.4 The whi le Loop 194
6.5 The do-whi le Loop 207
6.6 The whi le Loop within the do-whi le Loop 212
6.7 Bohm and Jacopini’s Theory 213
Summary 213
Exercises 213

A01_KAMT3553_02_SE_FM.indd 5 5/17/2015 8:59:36 AM


Contents v

4 Input and Output in C ........................................................................ 84


4.1 Introduction 85
4.2 Formatted Functions 86
4.3 Flags, Widths and Precision with Format String 88
4.4 Unformatted Functions 99
4.5 Commonly Used Library Functions 104
4.6 Strong Points for Understandability 105
Summary 106
Exercises 106

5 Decision Statements ....................................................................... 112


5.1 Introduction 113
5.2 The i f Statement 114
5.3 The i f–el se Statement 116
5.4 Nested i f–else Statements 120
5.5 The i f -el se- i f Ladder Statement 121
5.6 The break Statement 129
5.7 The cont inue Statement 130
5.8 The goto Statement 130
5.9 The swi tch Statement 132
5.10 Nested swi tch case 144
5.11 The swi tch case and nested i fs 146
Summary 147
Exercises 148

6 Loop Control .................................................................................... 154


6.1 Introduction
6.1.1 What is a Loop?
155
155

6.2 The for Loop 156


6.3 Nested for Loops 172
6.4 The whi le Loop 194
6.5 The do-whi le Loop 207
6.6 The whi le Loop within the do-whi le Loop 212
6.7 Bohm and Jacopini’s Theory 213
Summary 213
Exercises 213

A01_KAMT3553_02_SE_FM.indd 5 5/17/2015 8:59:36 AM


vi Contents

7 Data Structure: Array ...................................................................... 220


7.1 Introduction 221
7.2 Array Declaration 221
7.3 Array Initialization 222
7.4 Array Terminology 223
7.5 Characteristics of an Array 224
7.6 One-Dimensional Array 226
7.7 One-Dimensional Array and Operations 238
7.8 Operations with Arrays 240
7.9 Predefined Streams 246
7.10 Two-Dimensional Array and Operations 251
7.10.1 Insert Operation with Two-Dimensional Array 253
7.10.2 Delete Operation with Two-Dimensional Array 255

7.11 Three- or Multi-Dimensional Arrays 269


7.12 The sscanf ( ) and spr int f ( ) Functions 274
7.13 Drawbacks of Linear Arrays 276
Summary 276
Exercises 277

8 Strings and Standard Functions ........................................................ 286


8.1 Introduction 287
8.2 Declaration and Initialization of String 287
8.3 Display of Strings with Different Formats 289
8.4 String Standard Functions 291
8.5 String Conversion Functions 315
8.6 Memory Functions 316
8.7 Applications of Strings 318
Summary 328
Exercises 328

9 Pointers ........................................................................................... 336


9.1 Introduction 337
9.2 Features of Pointers 338
9.3 Pointers and Address 338
9.4 Pointer Declaration 339
9.5 The Void Pointers 345
9.6 Wild Pointers 346
9.7 Constant Pointers 347
9.8 Arithmetic Operations with Pointers 348

A01_KAMT3553_02_SE_FM.indd 6 5/17/2015 8:59:36 AM


Contents vii

9.9 Pointers and Arrays 352


9.10 Pointers and Two-Dimensional Arrays 357
9.11 Pointers and Multi-Dimensional Arrays 358
9.12 Array of Pointers 360
9.13 Pointers to Pointers 362
9.14 Pointers and Strings 364
Summary 371
Exercises 371

10 Functions ......................................................................................... 378


10.1 Introduction 379
10.2 Basics of a Function 379
10.2.1 Why Use Functions? 379
10.2.2 How a Function Works? 380

10.3 Function Definition 380


10.4 The return Statement 384
10.5 Types of Functions 386
10.6 Call by Value and Reference 393
10.7 Function Returning More Values 395
10.8 Function as an Argument 396
10.9 Function with Operators 399
10.10 Function and Decision Statements 406
10.11 Function and Loop Statements 409
10.12 Functions with Arrays and Pointers 412
10.13 Passing Array to a Function 418
10.14 Nested Functions 420
10.15 Recursion 422
10.16 Types of Recursion 424
10.17 Rules for Recursive Function 425
10.18 Direct Recursion 427
10.19 Indirect Recursion 428
10.20 Recursion Versus Iterations 430
10.21 The Towers of Hanoi 432
10.22 Advantages and Disadvantages of Recursion 435
10.23 Efficiency of Recursion 436
10.24 Library Functions 437
Summary 438
Exercises 438

A01_KAMT3553_02_SE_FM.indd 7 5/17/2015 8:59:36 AM


viii Contents

11 Storage Classes .............................................................................. 446


11.1 Introduction
11.1.1 Lifetime of a Variable
447
447
11.1.2 Visibility of a Variable 448

11.2 Automatic Variables 448


11.3 External Variables 450
11.4 Stat ic Variables 453
11.5 Stat ic External Variables 454
11.6 Regi ster Variables 455
Summary 456
Exercises 456

12 Preprocessor Directives ................................................................. 462


12.1 Introduction 463
12.2 The #def ine Directive 463
12.3 Undefining a Macro 466
12.4 Token Pasting and Stringizing Operators 467
12.5 The #include Directive 468
12.6 Conditional Compilation 469
12.7 The #i fndef Directive 471
12.8 The #er ror Directive 472
12.9 The #l ine Directive 473
12.10 The #pragma inl ine Directive 473
12.11 The #pragma saveregs 473
12.12 The #pragma Directive 473
12.13 The Predefined Macros in ANSI and TURBO-C 475
12.14 Standard I/O Predefined Streams in s tdio.h 478
12.15 The Predefined Marcos in ctype . h 478
12.16 Assertions 480
Summary 481
Exercises 481

13 Structure and Union ........................................................................ 490


13.1 Introduction 491
13.2 Features of Structures 491
13.3 Declaration and Initialization of Structures 492
13.4 Structure within Structure 496

A01_KAMT3553_02_SE_FM.indd 8 5/17/2015 8:59:36 AM


Contents ix

13.5 Array of Structures 498


13.6 Pointer to Structure 501
13.7 Structure and Functions 504
13.8 typedef 506
13.9 Bit Fields 510
13.10 Enumerated Data Type 513
13.11 Union 517
13.12 Calling BIOS and DOS Services 518
13.13 Union of Structures 524
Summary 524
Exercises 525

14 Files ................................................................................................. 532


14.1 Introduction of a File 533
14.2 Definition of File 533
14.3 Streams and File Types 534
14.3.1 File Types 534
14.4 Steps for File Operations 535
14.4.1 Opening of File 536
14.4.2 Reading a File 536
14.4.3 Closing a File 536
14.4.4 Text Modes 537
14.4.5 Binary Modes 543
14.5 File I/O 545
14.6 Structures Read and Write 553
14.7 Other File Function 558
14.8 Searching Errors in Reading/Writing Files 561
14.9 Low-Level Disk I/O 572
14.10 Command Line Arguments 576
14.11 Application of Command Line Arguments 577
14.12 Environment Variables 579
14.13 I/O Redirection 580
Summary 582
Exercises 582

15 Graphics .......................................................................................... 590


15.1 Introduction 591
15.2 Initialization of Graphics 591
15.3 Few Graphics Functions 591

A01_KAMT3553_02_SE_FM.indd 9 5/17/2015 8:59:36 AM


x Contents

15.4 Programs Using Library Functions 593


15.4.1 Program on Moving Moon 596

15.5 Working with Text 598


15.5.1 Stylish Lines 599

15.6 Filling Patterns with Different Colours and Styles 600


15.7 Mouse Programming 604
15.8 Drawing Non-common Figures 607
Summary 608
Exercises 608

16 Dynamic Memory Allocation and Linked List ................................ 612


16.1 Dynamic Memory Allocation 613
16.2 Memory Models 613
16.3 Memory Allocation Functions 614
16.4 List 621
16.5 Traversal of a List 621
16.6 Searching and Retrieving an Element 622
16.7 Predecessor and Successor 623
16.8 Insertion 624
16.9 Linked Lists 626
16.10 Linked List with and without Header 627
16.10.1 Linked List with Header 627

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

A01_KAMT3553_02_SE_FM.indd 10 5/17/2015 8:59:36 AM


PREFACE

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.

A01_KAMT3553_02_SE_FM.indd 11 5/17/2015 8:59:36 AM


xii Preface

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.

A01_KAMT3553_02_SE_FM.indd 12 5/17/2015 8:59:37 AM


Preface xiii

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

A01_KAMT3553_02_SE_FM.indd 13 5/17/2015 8:59:37 AM


ACKNOWLEDGEMENTS

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

A01_KAMT3553_02_SE_FM.indd 14 5/17/2015 8:59:37 AM


ABOUT THE AUTHOR

Ashok N. Kamthane is presently working as an associate professor in Department of Electronics and


Telecommunication Engineering at Shri Guru Gobind Singhji Institute of Engineering and Technology,
Nanded, Maharashtra. He has over 32 years of teaching experience. He was associated with the
development of hardware and software using 8051 on acoustic transceiver system for submarines.
Professor Kamthane is also the author of bestselling books Object-Oriented Programming with
ANSI and Turbo C++; Introduction to Data Structures in C; and C Programming: Test Your Skills,
published by Pearson Education.

A01_KAMT3553_02_SE_FM.indd 15 5/17/2015 8:59:37 AM


This page is intentionally left blank
CHAPTER

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

M01_KAMT3553_02_SE_C01.indd 2 5/17/2015 9:04:16 AM


Basics and Introduction to C 3

1.1 WHY TO USE COMPUTERS?


Computers play a vital role in the socioeconomic progress of a country. Every nation is paying much
importance to computer literacy. Progress of individuals, surrounding region, nation and of the world
is ensured only with the introduction and use of computers. In every walk of life, computers are being
used increasingly. In every part of the world, computers are employed to increase the overall produc-
tivity. Moreover, the quality of the products due to application of computers is substantially improved.
The impact of computers is very high on mass education, entertainment and productivity in all fields.
With the use of computers the cost of production reduces drastically, a lot of time is saved and the best
quality is ensured.
With the adoption of the policy of liberalization, privatization and globalization by the govern-
ments all over the world, it is necessary to become competitive in the market. Luxurious survival is
not easy as was possible in ancient days. With land, labour, muscle power and capital, economy can
certainly be boosted to a certain degree, but the intellectual power is highly superior to all these assets.
With some know-how (for the common users) and a lot of technical innovations (by the developers),
numerical problems, business transactions and scientific applications, can be computed in almost no
time. A computer does various tasks on the basis of programs. Intellectual computer is certainly a
powerful gadget but human intellectual capability is much higher than that of a computer. Thus, com-
puter does not have its own brain. Brainpower of computer is limited. Thus, human intellectual power
is further reinforced by the use of computers frequently in the day-to-day life. By learning program-
ming languages, developing software packages and using hardware of computers, one can make his/
her life and nation prosperous.

1.2 BASICS OF A COMPUTER


Data to be processed by a computer appears in different forms, such as numeric, alphabetical char-
acters either in uppercase or in lowercase, special characters and multimedia. Research applications
in universities and colleges frequently use numeric data on large scales, whereas businessmen and
people in the corporate sector use both numeric and
character data. However, in animation multimedia is
used which include text, video and audio. Central
A computer is a programmable electronic Input Processor Output
machine that accepts instructions and data through Unit
input devices, manipulating data according to
instructions and finally providing result to the
output device. The result can be stored in memo-
ry or sent to the output device. Figure 1.1 shows Memory
the conventional block diagram of a conventional
computer.
Figure 1.2 shows a computer system contain- Figure 1.1 Block diagram of a conventional computer
ing a monitor, a keyboard and a rectangular box
comprising CPU on the motherboard.
In brief, the various blocks of a computer are described as follows.
Input Device: Input device is used to accept the data and instructions in to the computer. Through
the input device, i.e. keyboard, instructions and data are stored in a computer’s memory. Stored
instructions are further read by the computer from its memory and thus a computer manipulates
the data according to the instructions. The various input devices that can be used in a computer are

M01_KAMT3553_02_SE_C01.indd 3 5/17/2015 9:04:17 AM


4 Programming in C

keyboards, mouse, analog-to-digital converters,


light pen, track ball, optical character reader and
Interface
scanner. Figure 1.3 shows the input devices of
a computer. Floppy, compact disc, etc. can be
used as input or output device.
Central Processor Unit: CPU is the abbrevia-
tion for central processor unit. It is the heart of the
computer system. It is a hardware device in the
Figure 1.2 computer system

CD Keyboard Mouse Floppy Microphone Pen Drive

Figure 1.3 Input devices of a computer

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.

Printer CD Floppy Monitor Speaker Hard-Disk

Figure 1.4 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)

M01_KAMT3553_02_SE_C01.indd 4 5/17/2015 9:04:18 AM


Basics and Introduction to C 5

semi-conductor memory is used for storing the instructions and data in the form of ones and zeros.
The memory can be called user’s memory or read–write memory. Processor first reads the instructions
and data from the primary memory (semi-conductor memory). Then, it executes the instructions.
One more memory device used by a computer is called read only memory (ROM). This contains
a fixed software program for providing certain operations. This is non-volatile memory. Its contents
cannot be eliminated when power supply goes off. The basic input–output system (BIOS) is a soft-
ware used to control various peripheral devices such as a keyboard, a monitor, a printer, a mouse,
ports including serial and parallel ports. In fact, this is an operating system. It is possible to access the
users’ written programs, i.e. by loading a file, saving it and doing modifications to it in the later stage.
As soon as a personal computer is switched on, the software gets booted from ROM. Thus, various
functions are assigned to all supporting peripherals of a central processing unit (CPU) and easy inter-
actions are provided to the user by BIOS while booting the system.
For storing volumous data, secondery storage devices can be used. They are optical disk, magnetic
disc, tapes, etc.

1.3 LATEST COMPUTERS


The discussion on the various types of computers existing in the market is beyond the scope in this book.
Latest computers available in the market are in various shapes and sizes. These computers are just like
notebooks or even require lesser space than the notebook. They are handy, light weighted and portable.
Because of these reasons many computer users now carry laptops while travelling for their day-to-day
work. In the next couple of years, it is predicted that every school-going child would be using a laptop or
palmtop, and these devices would be sold just like hot cakes in the market with affordable prizes. A lot
of research work is going on in the foreign and Indian Universities, institutes and industries on the reduc-
tion of the size of a computer, building more functions in it with low cost, minimum battery power for
operating it for large duration in the absence of A.C. mains power supply. In a couple of years, laptops and
palmtops would be flooded in the market. These notebook-shaped laptops are as powerful as desktop com-
puters. In other words, the computing power of a laptop would be advancing to that of desktop computers
and minicomputers. They are used for the purpose of text processing, web surfing, multimedia operation,
image processing and so on. Performances of these computers are constantly improving, and the cost is
drastically reducing. A wireless network can be formed easily with laptops with the Bluetooth technology.
Wifi wireless network is quite popular nowadays, and there we use these computers quite often.
Typical specifications of a laptop computer are as follows,
• Processor: Intel Core i7 ( 8M cache,2.80GHz) OR AMD
• RAM: Minimum 2 GB to Maximum 16 GB
• Hard disk: Minimum 320 GB up to 1 TB or higher
• CD/DVD Drive: Dual Layer DVD+/-RW Drive, SuperDrive, Bluetooth and Camera
• Screen Size: 15.6” up to 23” Flat screen with LCD/LED display
• Ethernet: 10/100/1000 Mbps Ethernet
• Port: USB 3.0
• Graphics Card: From 520 MB or higher
• Rechargeable Battery back up
• Operating system such as windows XP/ windows 7/ Linux
For simpler application, one can go for Celeron-based laptop where heat
generated by the processor is little. Pentium processors are used only for
dedicated applications. Heat generated by this kind of laptop is more and
battery is to be frequently charged (Figure 1.5). Figure 1.5 The laptop

M01_KAMT3553_02_SE_C01.indd 5 5/17/2015 9:04:18 AM


6 Programming in C

1.4 INTRODUCTION TO C BCPL B


C is one of the most popular general-purpose programming languages.
C language has been designed and developed by Dennis Ritchie at
Bell Laboratories, USA, in 1972. Several important concepts of C C
are drawn from ‘Basic combined programming language’ and ‘B’
language. Figure 1.6 shows the development of C language from the Figure 1.6 Evolution of C
two languages. Martin Richards developed BCPL in 1967. The impact
of BCPL on C is observed indirectly through the language B, which
was developed by Ken Thompson in 1970. C is also called an offspring of the BCPL. Table 1.1
illustrates the evolution of languages and their inventors of programming language.

Table 1.1 Languages and their inventors


Sr. No. Language Inventor Year
1. BCPL Martin Richards 1967
2. B Ken Thompson 1970
3. C Dennis Ritchie 1972

The C language is not tied to any particular


operating system. It can be used to develop new UNIX MS-DOS
operating systems. Refer to Figure 1.7 in which the
C language is shown associated with the various
operating systems. The C language is closely associat-
ed with the UNIX operating system. The source code WINDOWS
C OTHER
for the UNIX operating system is in C. C runs under OS......
a number of operating systems including MS-DOS.
The C programs are efficient, fast and highly portable, Figure 1.7 C and operating systems
i.e. C programs written on one computer can be run on
another with mere or almost no modification.
The C programming language contains modules called functions. The C functions are the basic
building blocks and the most programmers take its benefit. Programmers include these functions in
their program from the C standard library.
C language is a middle-level computer language. It does not mean that C is not powerful and
rugged for writing programs like in Fortran and Pascal. It also does not mean that it is troublesome
like assembly level languages. It combines the features of a high-level language and functionality like
assembly languages. In C, one can develop a program fast and execute fast. It reduces the gap between
high- and low-level languages; that is why it is known as a middle level language. It is well suited for
writing both application and system softwares.
C is a structural language. It has many similarities with the other structural languages such as
Pascal and Fortran. Structured language facilitates the development of a variety of programs in small
modules or blocks. Lengthy programs can be divided into shorter programs. The user requires think-
ing of a problem in terms of functional blocks. With appropriate collection of different modules, the
programmer can make a complete program.
It is easy for writing, testing, debugging and maintenance with structured programming. In case
some changes are to be done in a program, the programmer can refer to the earlier written module
with editor and incorporate the appropriate changes. Hence, structured languages are easier and most
of the developers prefer these languages, than the non-structured languages like BASIC and COBOL.
Programming with non-structured languages is tough in comparison to structured languages.

M01_KAMT3553_02_SE_C01.indd 6 5/17/2015 9:04:19 AM


Basics and Introduction to C 7

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.

1.5 ABOUT ANSI C STANDARD


For many years, there was no standard version of C language, and the definition provided in reference
manual was followed. Due to this reason portability feature of C language was not provided from one
computer to another. To overcome this discrepancy, a committee was set up in the summer of 1983 to
create a standard C version which is popularly known as American National Standard Institute (ANSI)
standard.
This committee had defined once and for all a standard C language. The standardization process
took about six years for defining the C language. The ANSI C standard was adopted in 1989, and its
first copy of C language was introduced in the market in 1990.
Thus, ANSI C is internationally recognized as a standard C language. The purpose of this stan-
dard is to enhance the portability and efficient execution of C language programs on different com-
puters. Today, all compilers of C support the ANSI standard. In other words, almost all C compilers
available in the market have been designed to follow ANSI C standard. ANSI C and other C compilers
such as turbo-C version 2 support programs developed in this book.

1.6 MACHINE, ASSEMBLY AND HIGH-LEVEL LANGUAGE


It is a computer’s natural language, which can be directly understood by the system. This language
is machine dependent, i.e. it is not portable. A program written in 1’s and 0’s is called a machine
language. A binary code is used in a machine language for a specific operation. A set of instructions
in binary pattern is associated with each computer. It is difficult to communicate with a computer in
terms of 1s and 0s. Hence, writing a program with a machine language is very difficult. Moreover,
speed of writing, testing and debugging is very slow in machine language. Chances of making careless
errors are bound to be there in this language. The machine language is defined by the hardware design
of that hardware platform. Machine languages are tedious and time consuming.

M01_KAMT3553_02_SE_C01.indd 7 5/17/2015 9:04:19 AM


8 Programming in C

1.6.1 | Assembly Language


Instead of using a string of binary bits in a machine language, programmers started using English-
like words as commands that can be easily interpreted by programmers. In other words, the computer
manufacturers started providing English-like words abbreviated as mnemonics that are similar to
binary instructions in machine languages. The program is in alphanumeric symbols instead of 1s and
0s. The designer chooses easy symbols that are to be remembered by the programmer, so that the
programmer can easily develop the program in assembly language. The alphanumeric symbols are
called mnemonics in the assembly language. The ADD , SUB , MUL , DIV , RLC and RAL are some
symbols called mnemonics.
The programs written in other than the machine language need to be converted to the machine
language. Translators are needed for conversion from one language to another. Assemblers are used
to convert assembly language program to machine language. Every processor has its own assembly
language. For example, 8085 CPU has its own assembly language. CPUs such as 8086, 80186, 80286
have their own assembly languages.
Following disadvantages are observed with the assembly languages:
(i) It is time consuming for an assembler to write and then test the program.
(ii) Assembly language programs are not portable.
(iii) It is necessary to remember the registers of CPU and mnemonic instructions by the
programmer.
(iv) Several mnemonic instructions are needed to write in assembly language than a single line
in high-level language. Thus, assembly language programs are longer than the high language
programs.

1.6.2 | High-Level Language


Procedure-oriented languages are high-level languages. These languages are employed for easy and
speedy development of a program. The disadvantages observed with assembly languages are over-
come by high-level languages. The programmer does not need to remember the architecture and reg-
isters of a CPU for developing a program. The compilers are used to translate high-level language
program to machine language. Examples of HLL are COBOL, FORTRAN, BASIC, C and C++. The
following advantages are observed with HLL languages:
(i) Fast program development.
(ii) Testing and debugging a program is easier than in the assembly language.
(iii) Portability of a program from one machine to other.

1.7 ASSEMBLER, COMPILER AND INTERPRETER


A program is a set of instructions for performing a particular task. These instructions are just like
English words. The computer interprets the instructions as 1’s and 0’s. A program can be written in
assembly language as well as in high-level language. This written program is called the source pro-
gram. The source program is to be converted to the machine language, which is called an object pro-
gram. A translator is required for such a translation.
Program translator translates source code of programming language into machine language-
instruction code. Generally, computer programs are written in languages like COBOL, C, BASIC
and ASSEMBLY LANGUAGE, which should be translated into machine language before execution.

M01_KAMT3553_02_SE_C01.indd 8 5/17/2015 9:04:19 AM


Basics and Introduction to C 9

Programming language translators are classified as


Translator
follows. A list of translators is given in Figure 1.8.
Translators are as follows:
(i) Assembler
(ii) Compiler Assembler Compiler Interpreter
(iii) Interpreter
Figure 1.8 Translators
Assembler: An assembler translates the symbolic
codes of programs of an assembly language into
machine language instructions (Figure 1.9). The symbolic language is translated to the machine code
in the ratio of one is to one symbolic instructions to one machine code instructions. Such types of

Mnemonic Machine
Assembler
language codes

Figure 1.9 Assembler

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.

M01_KAMT3553_02_SE_C01.indd 9 5/17/2015 9:04:20 AM


10 Programming in C

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.

1.8 STRUCTURE OF A C PROGRAM


Every C program contains a number of building blocks known as functions. Each function of
it performs a specific task independently. A C program comprises different sections shown in
Figure 1.11.
(i) Include Header File Section: C program
depends upon some header files for function
definition that are used in the program. Each Include header file
header file has extension ‘ . h’. The header Global Declarat ion
files are included at the beginning of the /* comments */
program in the C language. These files should /*Funct ion name */
be included using # include directive as given main ( )
below. {
/* comments */
Example:
Declarat ion par t
# include <stdio . h> or Executable par t
# include “stdio . h” Funct ion cal l
In this example, <s tdio . h> file is included,
i.e. all the definitions and prototypes of function }
defined in this file are available in the current
program. This file is also compiled with the orig- User -defined funct ions
inal program. The programmer can include the
appropriate header files while executing solved
Figure 1.11 Structure of a C program
or unsolved programming examples given in this
book.
(ii) Global Declaration: This section declares some variables that are used in more than one func-
tion. These variables are known as global variables. This section must be declared outside of
all the functions.
(iii) Function main( ): Every program written in C must contain main( ) and its execution starts
at the beginning of this function. In ASCII C standard, first line of C program from where
program execution begins is written as follows.
int main(void)
This is the function definition for main( ). Parenthesis followed to main is to tell the user
again that ma i n( ) is a function. The i n t ma i n(vo i d) is a function that takes no argu-
ments and returns a value of type int. Here in this line, int and void are keywords and they
have special meanings assigned by the compiler. In case int is not mentioned in the above
statement, by default the function returns an integer.

M01_KAMT3553_02_SE_C01.indd 10 5/18/2015 12:14:34 PM


Basics and Introduction to C 11

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.

M01_KAMT3553_02_SE_C01.indd 11 5/17/2015 9:04:20 AM


12 Programming in C

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 */

1.9 PROGRAMMING RULES


A programmer while writing a program should follow the following rules:
(i) Every program should have main( ) function.
(ii) C statements should be terminated by a semi-colon. At some places, a comma operator is per-
mitted. If only a semi-colon is placed it is treated as a statement. For example:
whi le(condi t ion)
;
The above statement generates infinite loop. Without semi-colon the loop will not execute.
(iii) An unessential semi-colon if placed by the programmer is treated as an empty statement.
(iv) All statements should be written in lowercase letters. Generally, uppercase letters are used
only for symbolic constants.
(v) Blank spaces may be inserted between the words. This leads to improvement in the readability
of the statements. However, this is not applicable while declaring a variable, keyword, constant
and function.
(vi) It is not necessary to fix the position of statement in the program; i.e. a programmer can write
the statement anywhere between the two braces following the declaration part. The user can
also write one or more statements in one line separating them with a semi-colon (;). Hence, it
is often called a free-form language. The following statements are valid:
a=b+c;
d=b*c;
or
a=b+c; d=b*c;
(vii) The opening and closing braces should be balanced, i.e. if opening braces are four; closing
braces should also be four.

1.10 EXECUTING THE C PROGRAM


A C program must go through various phases such as creating a program with editor, execution of
preprocessor program, compilation, linking, loading and executing the program. The following steps
are essential in C when a program is to be executed in MS-DOS mode:
(i) Creation of a Program: The program should be written in C editor. The file name does not
necessarily include extension ‘ . C’. The default extension is ‘ . C’. The user can also specify
his/her own extension. The C program includes preprocessor directives.
(ii) Execution of a Preprocessor Program: After writing a program with C editor the program-
mer has to compile the program with the command (Alt-C). The preprocessor program executes

M01_KAMT3553_02_SE_C01.indd 12 5/17/2015 9:04:20 AM


Basics and Introduction to C 13

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

Source program editor

Pre-processor

Compile source program

Is syntax
error? Yes

No

System library Linking process

Input again Execute object code

Input error Is logic and data Logic error


Yes error? Yes

No
Run time error Compile time error

Output

Figure 1.12 Flow chart of a program in C

M01_KAMT3553_02_SE_C01.indd 13 5/17/2015 9:04:21 AM


14 Programming in C

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):

Figure 1.13 Window to Turbo C editor

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).

M01_KAMT3553_02_SE_C01.indd 14 5/17/2015 9:04:21 AM


Basics and Introduction to C 15

Figure 1.14 Opening a new file

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).

Figure 1.15 Compilation of program


On compilation, the same program is to be run with Alt+R keys. The screen appears as shown below. Of
course, this step is adapted when there are no errors after compilation. After running the program, answer
appears on the other screen. The programmer can try a simple program as cited below in the window.
Executable file is created after running the program file. The .exe file created can be observed (Figure 1.16).

Figure 1.16 Running a program


It is expected to edit, compile and run a program given in the above snapshot by the user in the C editor.

M01_KAMT3553_02_SE_C01.indd 15 5/17/2015 9:04:22 AM


16 Programming in C

1.11 STANDARD DIRECTORIES


The turbo-C has three standard directories; they are i nc l ude, sys and l i b. The Sys is the
sub-directory of i nc l ude. The i nc l ude directory contains all the header files and l i b con-
tains all the library files. Before executing the program the path setting should be done. In turbo-
c edit, select Option menu Directories option. Here, set the path of i nc l ude, l i brary and
turbo-c-directories.

1.12 THE FIRST C PROGRAM


1.1 Write a program to display message “Hello! C Programmers”.

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.

M01_KAMT3553_02_SE_C01.indd 16 5/17/2015 9:04:22 AM


Basics and Introduction to C 17

1.3 Write a program to return the value from main( ).

main( )
{
return 0;
}

Explanation:
The above program produces no output. The main( ) should return a value of either 0 or 1.
Some operating systems check the return value of main( ). If main( ) returns 0, i.e. pro-
gram executed successfully; else for other value OS assumes the opposite. If user fails to put
the return statement, the compiler would not complain.

1.13 ADVANTAGES OF C
(i) It contains a powerful data definition. The data type supported are characters, alphanumeric,
integers, long integer, floats and double. It also supports string manipulation in the form of
character array.
(ii) C supports a powerful set of operators.
(iii) It also supports powerful graphics programming and directly operates with hardware. Execu-
tion of program is faster.
(iv) An assembly code is also inserted into C programs.
(v) C programs are highly portable on any type of OS platforms.
(vi) System programs such as compilers, operating systems can be developed in C. For example,
the popular operating system UNIX is developed in C.
(vii) The C language has 32 keywords and about 145 library functions and near about 30 header
files.
(viii) C works closely with machines and matches assembly language in many ways.

1.14 HEADER FILES


stdio . h: Standard input and output files. All formatted and unformatted functions include file
operation functions defined in this file. The most useful formatted pr i n t f ( ) and scanf ( ) are
defined in this file. This file must be included at the top of the program. Most useful functions from
this header files are pr int f ( ), scanf ( ), getchar ( ), gets( ), putc( ) and putchar ( ).
conio . h: Console input and output. This file contains input and output functions along with a few
graphic-supporting functions. The getch( ) , getche( ) and cl rscr ( ) functions are defined in
this file.
math . h: This file contains all mathematical and other useful functions. The commonly useful func-
tions from this files are floor(), abs(), cei l (), pow() , sin(), cos() and tan(). The list
of commonly used header files are given in Table 1.2

M01_KAMT3553_02_SE_C01.indd 17 5/17/2015 9:04:22 AM


18 Programming in C

Table 1.2 Commonly useful header files


Sr. No. Header File Functions Function Examples
1. stdio . h Input, output and file operation functions pr int f ( ) , scanf ( )
2. conio . h Console input and output functions cl rscr ( ) , getche( )
3. al loc . h Memory allocation-related functions mal loc( ) , real loc( )
4. graphics . h All graphic-related functions ci rcle( ) , bar3d( )
5. math . h Mathematical functions abs( ) , sqr t ( )
6. st r ing . h String manipulation functions st rcpy( ) , st rcat ( )
7. bios . h BIOS accessing functions biosdi sk( )
8. asser t . h Contains macros and definitions void asser t ( int )
9. ctype . h Contains prototype of functions which test i salpha(char )
characters
10. t ime . h Contains date- and time-related functions asct ime( )

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

M01_KAMT3553_02_SE_C01.indd 18 5/17/2015 9:04:22 AM


Basics and Introduction to C 19

(v) Conversation begins between them


(vi) After the conversation, both disconnect the call
Another real life example is to access Internet through Internet service provider with dial up facility.
To log on to the Internet, the following steps are to be followed:
(i) Choose the Internet service provider for accessing the Internet.
(ii) Obtain from service provider a dial up number.
(iii) Acquire IP address of the service provider.
(iv) Acquire login ID and password.
(v) Run the Internet browsing software.
When one writes an algorithm, it is essential to know how to analyse the algorithm. Analysing al-
gorithm refers to calculating or guessing resources needed for an algorithm. Resources mean com-
puter memory, processing time, logic gates. In all the above factors, time is the most important factor
because the program developed should be faster in processing. The analysis can also be made by
reading the algorithm for logical accuracy, tracing the algorithm, implementing it, and checking with
some data and with mathematical techniques to confirm its accuracy.
Algorithms can also be expressed in a simple method. It will help the user to put into operation
easily. However, this approach has a few drawbacks. It requires more space and time. It is very essen-
tial to consider the factors such as time and space of an algorithm. With minimum resources of system
such as CPU’s time and memory, an efficient algorithm must be developed.
Practically, it is not possible to do a simple analysis of an algorithm to conclude the execution time of an
algorithm. The execution time is dependent upon the machine and the way of implementation. The timing
analysis depends upon the input required. To accurately carry out the time analysis, it is also very essential
to know the exact directives executed by the hardware and the execution time passed for each statement.
1.4 Write a program to swap two numbers using a third variable.
Flowchart for swapping
Algorithm for swapping two numbers:
two numbers:
STEP 1: Start.
STEP 2: Declare variables a, b, & c. START
STEP 3: Read values of a & b.
STEP 4: Copy value of a to c; b to a; & c to b.
Declare variables a, b, c.
STEP 5: Print swapped values of a & b.
STEP 6: Exit.
Program:
Enter the values of
void main( )
a&b
{
int a , b , c;
cl rscr ( ) ;
c = a;
pr int f (“\nEnter two numbers for A & B:”) ; a = b;
scanf (“%d %d” , &a , &b) ; b = c;
c=a;
a=b;
b=c;
Print a, b
pr int f(“\nAf ter swaping the values
are:A=%d & B=%d.”,a,b) ;
getch( ) ;
END
}

M01_KAMT3553_02_SE_C01.indd 19 5/17/2015 9:04:23 AM


20 Programming in C

Hint: Copy value of a in third variable c, value of b in a, and value of c in b.


Explanation:
In the above cited program, first three variables a, b, & c are declared. The program invokes
two values of a & b from user. The user assigns values to the variables a & b.
Now copy the value of a in third variable c, value of b in a, and value of c in b.
Here, when we assign the value of a to c (c = a), the value of a is copied in variable c. When we
assign (a = b), the value of b is copied in variable a and the previous value is replaced. Now,
b holds the value of variable c in statement (b = c).
The pr int f ( ) statement prints the values of a & b.
1.5 Write a program to swap two numbers without using a third variable.

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.

1.15.1 | Program Design


When you have thoroughly studied the program and examined the requirement of the program, the
next step is to design the program. To make the programs simple, divide the program into smaller
modules. This makes thinking process easy and you can separately apply logic on each portion. After
dividing the program, according to priority and importance write the code.

M01_KAMT3553_02_SE_C01.indd 20 5/17/2015 9:04:23 AM


Basics and Introduction to C 21

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.

1.16 CLASSIFICATION OF ALGORITHMS


The classification of algorithm is based on repetitive steps and on control transfer from one statement
to another. Figure 1.17 shows the classification of Algorithms.

Algorithms

Based on repetitive Based on control


steps transfer

Direct Indirect Deterministic Non-deterministic Random

Figure 1.17 Classifications of 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.

M01_KAMT3553_02_SE_C01.indd 21 5/17/2015 9:04:24 AM


22 Programming in C

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

Figure 1.18 Start/stop symbol

M01_KAMT3553_02_SE_C01.indd 22 5/17/2015 9:04:24 AM


Basics and Introduction to C 23

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

Figure 1.19 Single alternative decision

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

Execution of action 1 Execution of action 2

Exit

Figure 1.20 Two alternative decisions

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.

M01_KAMT3553_02_SE_C01.indd 23 5/17/2015 9:04:24 AM


24 Programming in C

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

Figure 1.21 Multiple alternative decisions

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.

Connector for connecting Connector that comes from the


to the next block previous block

Figure 1.22 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

Figure 1.23 Process symbol

M01_KAMT3553_02_SE_C01.indd 24 5/17/2015 9:04:25 AM


Basics and Introduction to C 25

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

Figure 1.24 For loop

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

Figure 1.25 Input/output symbol

Figure 1.26 Delay symbol

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.

M01_KAMT3553_02_SE_C01.indd 25 5/17/2015 9:04:26 AM


26 Programming in C

Figure 1.27 Manual input symbol

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.

Alternate process Predefined process Internal storage

Manual operation Off-page connector Card Flow lines

Punched tape Summing junction Or Collate

Sort Extract Merge Stored data

Sequential access Display Direct access


storage storage

Figure 1.28 Some other symbols used in the flowchart

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.

M01_KAMT3553_02_SE_C01.indd 26 5/17/2015 9:04:27 AM


Basics and Introduction to C 27

This can be represented as follows.

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

Figure 1.29 Input symbol

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

Figure 1.30 Processing symbol

The output statement, that is, ‘Display number’ can be represented as per Figure 1.31.

Display
number

Figure 1.31 Output symbol

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.

M01_KAMT3553_02_SE_C01.indd 27 5/17/2015 9:04:28 AM


28 Programming in C

Begin

Begin
Accept
number 1. Accept number

Calculate square
of the number 2. Calculate square of
the number

Display 3. Display number


number

End End

Figure 1.32 Pseudocode and flowchart of a program

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.

M01_KAMT3553_02_SE_C01.indd 28 5/17/2015 9:04:28 AM


Basics and Introduction to C 29

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

(a) 1972 (a) only UNIX operating system


(b) 1980 (b) only LINUX operating system
(c) 1975 (c) only MS-DOS operating system
(d) 1971 (d) All the above

5. The C language has been developed at 11. The C language is closely associated with

(a) AT & T Bell Labs, USA (a) MS-DOS


(b) IBM, USA (b) LINUX
(c) Borland International, USA (c) UNIX
(d) Sun Microsystems (d) MS-windows

6. The C language is an offspring of the 12. The C programs are highly portable means

(a) ‘BPCL’ language (a) same programs execute on different computers


(b) ‘ALGOL’ language (b) program executes only on the same computer
(c) ‘Basic’ language (c) program needs a lot of modification to run
(d) None of the above (d) None of the above

M01_KAMT3553_02_SE_C01.indd 29 5/17/2015 9:04:28 AM


30 Programming in C

13. Each instruction in C program is terminated by (a) anywhere in the program


(b) in declaration part
(a) dot (.)
(c) in executable part
(b) comma (,)
(d) at the end of program
(c) semi-colon (;)
(d) curly brace ({}) 22. Variables must begin with character without
spaces but it permits
14. Which one of the following statements is incorrect?
(a) an underscore symbol ( _ )
(a) a compiler compiles the source program (b) an asterisk symbol ( )
(b) an assembler takes as assembly program as (c) an ampersand symbol ( & )
input (d) None of the above
(c) interpreter executes the complete source
code just like compiler 23. In C, the statements following main( ) are
(d) None of the above enclosed within

15. ANSI committee was set up in (a) {}


(b) ()
(a) 1983 (c) <>
(b) 1985 (d) None of the above
(c) 1990
24. CPU generates
(d) 1976
(a) timing signals
16. The program which translates high-level program
(b) control signals
into its equivalent machine language program is
(c) analog signals
called
(d) both a & b
(a) a translator 25. The structural languages are
(b) a language processor
(c) a converter (a) C
(d) None of the above (b) Pascal
(c) Fortan
17. C is an offspring of the
(d) All the above
(a) basic combined programming language 26. Data type-less languages are
(b) basic computer programming language
(c) basic programming language (a) C
(d) None of the above (b) BCPL
(c) B
18. An interpreter reads the source code of a program (d) Both c & b
(a) one line at a time 27. Input device/s of a computer
(b) two lines at a time
(c) complete program in one stroke (a) Printer
(d) None of the above (b) Speaker
(c) Monitor
19. A compiler reads the source code of a program (d) None of the above
(a) complete program in one stroke 28. Output device/s of the computer
(b) one line at a time
(a) Monitor
(c) two lines at a time
(b) Speaker
(d) None of the above
(c) Printer
20. C keywords are reserved words by (d) All the above
(a) a compiler 29. CPU comprises of the
(b) an interpreter (a) Arithmetic and Logical unit
(c) a header file (b) Registers
(d) Both (a) and (b) (c) Control Signals
21. The declaration of C variable can be done (d) All the above

M01_KAMT3553_02_SE_C01.indd 30 5/17/2015 9:04:28 AM


Basics and Introduction to C 31

30. Advantages of high level language are (c) portable


(d) All the above
(a) fast Program Development
(b) testing and Debugging of program is easier

III Answer the following questions:


1. Why to use a computer? Brief its benefits. 11. What is ANSI C standard?
2. Illustrate the functions of various parts of a 12. What are the user-defined functions?
computer. 13. Explain the assembly-language and machine-lan-
3. Why is the C language called a middle-level guage concepts.
language? 14. Write details on header files stdio . h and
4. What are the functions of an interpreter and a conio . h.
compiler? 15. Which are the standard directories? Where are . h
5. What is the difference between an interpreter and files kept?
a compiler? 16. Write any three advantages of a C language.
6. What is meant by compilation? Explain in detail. 17. What is an algorithm? Explain in short.
7. Write the rules for writing a C program. 18. Mention and explain two types of algorithms.
8. Elaborate different sections of a C program. 19. Show the flowchart for finding cube of a number.
9. Explain the functions of a linker. 20. Write the pseudo code for finding largest out of
10. What is the role of curly braces ({}) in a three numbers.
C program?

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

M01_KAMT3553_02_SE_C01.indd 31 5/17/2015 9:04:29 AM


CHAPTER

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

M02_KAMT3553_02_SE_C02.indd 32 5/17/2015 9:05:07 AM


The C Declarations 33

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.

2.2 THE C CHARACTER SET


A character is a part of a word, sentence or paragraph. By using different characters, words, expres-
sions and statements can be created on the basis of the requirement. This creation depends upon the
computer on which a program runs.
ALPHABETS
A character is represented by any al-
phabets in lowercase or uppercase, digits DIGITS
or special characters.
C character set WHITE SPACES AND
Figure 2.1 presents valid C character ESCAPE SEQUENCES
set which are as follows: (i) Letters
SPECIAL CHARACTERS
(ii) Digits (iii) White Spaces & Escape
Sequences and (iv) Special Characters.
Figure 2.1 C character set
As C character set consists of escape
sequences so each escape sequence begins with back slash (\) and it represents a single character. Any
character can be represented as character constant using escape sequence.
The complete character set is listed in Tables 2.1 and 2.2.

Table 2.1 Character set


Letters Digits White Spaces and Escape Sequences
Uppercase A to Z All decimal digits 0 to 9 Back space \b
Lowercase a to z Horizontal tab \t
Vertical tab \v
New line \n
Form feed \f
Backslash \\
Alert bell \a
Carriage return \r
Question mark \?
Single quote \’
Double quote \”
Octal number \o or \oo or \ooo
Hexadecimal number \xhh

M02_KAMT3553_02_SE_C02.indd 33 5/17/2015 9:05:07 AM


34 Programming in C

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).

Table 2.2 List of special characters


, Comma & Ampersand
. Period or dot ^ Caret
; Semi-colon * Asterisk
: Colon _ Minus sign
‘ Apostrophe + Plus sign
“ Quotation mark < Less than
! Exclamation mark > Greater than
| Vertical bar () Parenthesis (left/right)
/ Slash [] Brackets (left/right)
\ Back slash {} Curly braces (left/right)
˜ Tilde % Percent sign
_ Underscore # Number sign or hash
$ Dollar = Equal to
? Question mark @ At the rate

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.

Table 2.3 Delimiters


Delimiters Symbols Uses
Colon : Useful for label
Semi-colon ; Terminates statements
Parenthesis () Used in expression and function
Square brackets [] Used for array declaration
Curly braces {} Scope of statement
Hash # Preprocessor directive
Comma , Variable separator
Angle brackets <> Header file

M02_KAMT3553_02_SE_C02.indd 34 5/17/2015 9:05:07 AM


The C Declarations 35

2.4 TYPES OF TOKENS


A compiler designer prescribes rules for making a program using statements. The smallest unit in a
program/statement is called a token. The compiler identifies them as tokens. Tokens are classified in
the following types. Figure 2.2 shows the types of tokens supported by C.
The tokens are as follows:
(i) Keywords: Key words are reserved by
the compiler. There are 32 keywords Keywords
(ANSI Standard).
Variables
(ii) Variables: These are user defined. Any
number of variables can be defined. Tokens Operators

(iii) Constants: Constants are assigned to Constants


variables.
Special
(iv) Operators: Operators are of different Characters
types and are used in expressions.
Strings
(v) Special Characters: These characters
are used in different declarations in C.
Figure 2.2 Types of tokens
(vi) Strings: A sequence of characters.

2.5 THE C KEYWORDS


The C keywords are reserved words by the compiler. All the C keywords have been assigned fixed
meanings and they cannot be used as variable names. However, few C compilers allow constructing
variable names, which exactly coincide with the keywords. It is suggested that the keywords should
not be mixed up with variable names. For utilizing the keywords in a program, no header file is
required to be included. The descriptions of the keywords are explained in the different programs/
chapters. The 32 C keywords provided in ANSI C are listed in Table 2.4.

Table 2.4 C keywords


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Additional Keywords for Borland C


asm cdecl far huge interrupt near pascal

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.

M02_KAMT3553_02_SE_C02.indd 35 5/17/2015 9:05:08 AM


36 Programming in C

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

Invalid identifiers are as follows: Pointer


Length of line, S+um, year’s
Structure
Example: Identfier
Union
User-defined identifiers are as follows:
Array
(i) #define N 10
(ii) #define a 15 Function

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

Numeric Constant Character Constant

Integer Constant Character Constant


Real Constant String Constant

Figure 2.4 C constants

Table 2.5 Constant types


Example Constant Type
542 Integer constant
35.254 Floating-point constant
0 × 54 Hexadecimal integer constant
0171 Octal integer constant
‘C’ Character constant
“cpp” String constant

M02_KAMT3553_02_SE_C02.indd 36 5/17/2015 9:05:09 AM


The C Declarations 37

2.7.1 | Numerical Constants


(a) Integer Constants: These constants are represented with whole numbers. They require a
minimum of 2 bytes and a maximum of 4 bytes of memory.

The following concepts are essential to follow the numerical constants:


(a) Numerical constants are represented with numbers. At least one digit is needed for
representing the number.
(b) The decimal point, fractional part, or symbols are not permitted. Neither blank spaces nor
commas are permitted.
(c) Integer constant could be either positive or negative or may be zero.
(d) A number without a sign is assumed as positive.

Some valid examples: 10, 20, +30, –15, etc.


Some invalid integer constants: 2.3, .235, $76, 3 ^6, etc.
Besides representing the integers in decimal, they can also be represented in octal or hexadeci-
mal number system based on the requirement.
Octal number system has base 8 and the hexadecimal number system has base 16. The octal
numbers are 0, 1, 2, 3, 4, 5, 6, and 7 and the hexadecimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
A, B, C, D, E, and F.
The representation of octal numbers in C would be done with leading digit 0 and for hex rep-
resentation, with leading OX or OX.
Examples of octal and hexadecimal numbers:
Octal numbers – 027, 037, 072
Hexadecimal numbers – 0X9, 0Xab, 0X4

(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.

Examples of real numbers are 2.5, 5.521, 3.14, etc.


The real constants can be written in exponential notation, which contains fractional and expo-
nential parts. For example, the value 2456.123 can be written as 2.4561 X e+3.
The part that precedes e is called mantissa and the part that follows it is an exponent. In this
example, 2.4561 is the mantissa and +3 is the exponent.

M02_KAMT3553_02_SE_C02.indd 37 5/17/2015 9:05:09 AM


38 Programming in C

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.

Some valid examples are 5.2e2,–2, 5.0e–5, 0.5e–3, etc.

In double type also the real numbers can be expressed with mantissa and exponent parts.

2.7.2 | Character Constant


(i) Single Character Constants: A character constant is a single character. It can also be
represented with single digit or a single special symbol or white space enclosed within a pair
of single quote marks or character constants are enclosed within single quotation marks.
Example:
‘a’ , ‘8’ , ‘ - ’
Length of a character, at the most, is one character.
Character constants have integer values known as ASCII values. For example the statement
pr int f (“%c %d” , 65 , ‘B’) will display character ‘A’ and 66.
(ii) String Constants: String constants are a sequence of characters enclosed within double quote
marks. The string may be a combination of all kinds of symbols.
Example:
“Hel lo” , “India” , “444” , “a” .
A programming example is given for various constants.
2.1 Write a program on various constants.

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

M02_KAMT3553_02_SE_C02.indd 38 5/17/2015 9:05:09 AM


The C Declarations 39

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.9 RULES FOR DEFINING VARIABLES


(i) A variable must begin with a character or an underscore without spaces. The underscore is
treated as one type of character. It is very useful to increase readability of variables having long
names. It is advised that the variable names should not start with underscore because library
routines mostly use such variable names.
(ii) The length of the variable varies from compiler to compiler. Generally, most of the compil-
ers support eight characters excluding extension. However, the ANSI standard recognizes the
maximum length of a variable up to 31 characters. Names of functions and external variables
length may be less than 31 because external names may be used by assemblers and loaders
over which language has no control. For external names, the variable names should be of six
characters and in single case.

M02_KAMT3553_02_SE_C02.indd 39 5/17/2015 9:05:09 AM


40 Programming in C

(iii) The variable should not be a C keyword.


(iv) The variable names may be a combination of uppercase and lowercase characters. For
example, suM and sum are not the same. The traditional practice is to use lowercase characters
for variable names and uppercase letters for symbolic constants.
(v) The variable name should not start with a digit.
(vi) Blanks and commas are not permitted within a variable name.

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.

2.10 DATA TYPES


All C compilers support a variety of data types. This enables the programmer to select the appro-
priate data type as per the need of the application. Generally, data is represented using numbers or
characters. The numbers may be integers or real. The basic data types are char , i n t , floa t and
doub l e.
The C supports a number of qualifiers that can be applied to these basic data type. The short and
long qualifiers provide different length to int. The short is always 16 bits and long is 32 bits, i.e. int
is either 16 or 32 bits. The compiler is free to choose a suitable size depending upon the hardware.
However, the restriction is that shor t or int is at least of 2 bytes and long is at least of 4 bytes.
The shor t should not be longer than int and int should not be longer than long.
The unsigned and signed qualifiers can be applied to char, int and long. The unsigned data
types are always zero or positive. They follow the law of arithmetic modulo 2n, where n is the number of
bits in the type. For example, char are 8 bits with combination of negative and positive values (−128
to 127) (two’s complement). The unsigned char supports values 0 to 255. The characters are signed or
unsigned, the printable char are always positive (see Figure 2.5 for a detailed classification).

M02_KAMT3553_02_SE_C02.indd 40 5/17/2015 9:05:09 AM


The C Declarations 41

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

Figure 2.5 C data types

C data type can be classified as follows:


(i) Basic Data Type:
(a) Integer ( int ), (b) character (char), (c) floating point (float ), (d) double floating point
(double).
(ii) Derived Data Type: Derived data types are pointers, functions and arrays. Pointers are
explained in Chapter 9, functions are explained in Chapter 10 and arrays are explained in
Chapter 7.
(iii) User-defined Type: St ruct , union and typedef are user-defined data types, which are
explained in Chapter 13.
(iv) void Data Type: This data type is explained in Chapter 10.

2.11 C DATA TYPES


(1) Integer Data Type
(a) int , shor t and long
All C compilers offer different integer data types. They are shor t and long. Short integer
requires half the space in memory than the long. The short integer requires 2 bytes and long
integers 4 bytes. Brief description on them is given in Table 2.6.
Table 2.6 Difference between short and long integers
Short Integer Long Integer
Occupies 2 bytes in memory Occupies 4 bytes in memory
Range: −32,768 to 32,767 Range: −2147483648 to 2147483647
Program runs faster Program runs slower
Format specifier is %d or %i Format specifer is %ld

(Continued)

M02_KAMT3553_02_SE_C02.indd 41 5/17/2015 9:05:09 AM


42 Programming in C

Table 2.6 Difference between short and long integers (Continued )


Short Integer Long Integer
Example: Example:
int a=2; long b=123456;
shor t int b=2; long int c=1234567;
When variable is declared without shor t or long keyword, the
default is short-signed int.

(b) Integers Signed and Unsigned


The difference between the signed integers and unsigned is given in Table 2.7.

Table 2.7 Difference between signed and unsigned integers


Signed Integer Unsigned Integer
Occupies 2 bytes in memory Occupies 2 bytes in memory
Range: −32,768 to 32,767 Range: 0 to 65535
Format specifier is %d or %i Format specifier is %u
By default signed int is shor t signed int By default unsigned int is shor t unsigned int
There are also long signed integers having Range There are also long unsigned int with range 0 to
from −2147483648 to 2147483647. 4294967295
Example: Example:
int a=2; unsigned long b=567898;
long int b=2; unsigned shor t int c=223;
When a variable is declared as unsigned the negative
range of the data type is transferred to positive, i.e.
doubles the largest size of the possible value. This is due
to declaring unsigned int; the 16th bit is free and not
used to store the sign of the number.

(2) char, signed and unsigned: Brief description on these data types is given in Table 2.8

Table 2.8 Difference between signed and unsigned char


Signed Character Unsigned Character
Occupies 1 bytes in memory Occupies 1 bytes in memory
Range: −128 to 127 Range: 0 to 255
Format specifier: %c Format specifier: %c
When printed using %d format specifier, When printed using %d format specifier,
prints ASCII character. prints ASCII character
char ch=‘b’ ; uns igned char =‘b’ ;

(3) Floats and Doubles: Table 2.9 shows the description of floats and double floats.

M02_KAMT3553_02_SE_C02.indd 42 5/17/2015 9:05:09 AM


The C Declarations 43

Table 2.9 Difference between floating and double floating


Floating Double Floating
Occupies 4 bytes in memory Occupies 8 bytes in memory
Range: 3.4e−38 to +3.4e+38 Range: 1.7 e−308 to +1.7e+308
Format string: %f Format string: %l f
Example: Example:
float a; double y;
There also exist long double having ranged 3.4e −
4932 to 1.1e + 4932 and occupies 10 bytes in memory.
Example:
long double k;

(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.

Table 2.10 Data types and their control strings


Data Type Size (bytes) Range Format String
char 1 −128 to 127 %c
uns igned char 1 0 to 255 %c
shor t or int 2 −32,768 to 32,767 %i or %d
uns igned int 2 0 to 65535 %u
long 4 −2147483648 to 2147483647 %ld
uns igned long 4 0 to 4294967295 %lu
float 4 3.4 e−38 to 3.4 e + 38 %f or %g
double 8 1.7 e−308 to 1.7 e + 308 %l f
long double 10 3.4 e−4932 to 1.1 e + 4932 %l f
enum 2 −32768 to 32767 %d

The size may vary according to the number of variables used with enum data type.

2.12 INTEGER AND FLOAT NUMBER REPRESENTATIONS


2.12.1 | Integer Representation
Recall that an integer with sign is called a signed integer. The signed integer has signs positive
or negative. The signs are represented in the computer in the binary format as 1 for − (minus)
and 0 for + (plus) or vice versa. The sign bit is always coded as leftmost bit. At the time of
storing the signed number, system reserves the leftmost bit for the representation of the sign
of the number.
For example, positive signed numbers are represented in the form called signed magnitude
form. In this form, the sign is represented by a binary 0 and the remaining magnitude by equivalent
binary form.
+7 is represented as 0 0000111

M02_KAMT3553_02_SE_C02.indd 43 5/17/2015 9:05:10 AM


44 Programming in C

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

2.12.2 | Floating-Point Representation


In most of the applications, fractions are often used. The system of the number representation that
keeps track of the position of binary and decimal point is better than the fixed-point representation.
This system is called floating-point representation.
The real number is integer part as well as fractional part. The real number is also called
floating-point number. These numbers are either positive or negative. The real number 454.45 can
be written as 4.5445 × 102 or 0.45445 × 103. This type of representation of number is called the
scientific representation. Using this scientific form, any number can be expressed as combination
of mantissa and an exponent or we can say the number ‘n’ can be expressed as n=mre where m is
the mantissa and r is the radix of the number system and e is the exponent. Mantissa is the fixed-
point number. The exponent indicates the position of the binary or decimal point. For example,
the number 454.45
0.45445 3
Mantissa Exponent
The zero in the left most position of the mantissa and exponent indicates the plus sign. The mantissa
can be a fraction or integer depending upon make of a computer. Most of the computers use mantissa
for fractional system representation.

Example in C:
1.2 E + 12, 2.5E − 2

2.13 DECLARING VARIABLES


The declaration of variables should be done in declaration part of the program. The variable must be de-
clared before they are used in the program. Declaration ensures the following two things: (i) compiler
obtains the variable name and (ii) it tells to the compiler data type of the variable being declared and

M02_KAMT3553_02_SE_C02.indd 44 5/17/2015 9:05:10 AM


The C Declarations 45

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.

Table 2.11 Data types and keywords


Data Types Keyword
Character char
Signed character signed char
Unsigned character uns igned char
Integer int
Signed integer signed int
Unsigned integer uns igned int
Unsigned short integer uns igned shor t int
Signed long integer signed long int
Unsigned long integer uns igned long int
Floating point float
Double floating point double
Extended double point long double

2.14 INITIALIZING VARIABLES


Variables declared can be assigned or initialized using assignment operator ‘=’. The declaration and
initialization can also be done in the same line.
Syntax:
var iable_name = cons tant ;
or
data_type var iable_name= constant ;

Example:
x=5; where x is an integer variable.

M02_KAMT3553_02_SE_C02.indd 45 5/17/2015 9:05:10 AM


46 Programming in C

Example:
int y=4;

Example:
int x , y , z; / Declaration of variables /

The third example as cited above for dec- Data-type Variable-Name Operator Value
laration of variables is also a valid state-
ment. Illustration of the initialization of a
variable is shown in Figures 2.6 and 2.7. int y = 2
In Figure 2.7, the variable z is assigned
a value 1, and z then assigns its value to Figure 2.6 Value assignment
y and again y to x. Thus, initialization in
chain system is done. However, note that x y z 1
following declarations are invalid:
int x=y=z=3; / invalid statement /
Figure 2.7 Multiple assignment

2.15 DYNAMIC INITIALIZATION


The initialization of variable at run time is called dynamic initialization. Dynamic refers to the process
during execution. In C initialization can be done at any place in the program; however the declaration
should be done at the declaration part only. Consider the following program.
2.4 Write a program to demonstrate dynamic initialization.

void main( )
{
int r=2;
float area=3 . 14*r*r ;
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.

2.16 TYPE MODIFIERS


The keywords signed, unsigned, shor t and long are type modifiers. A type modifier changes
the meaning of basic data type and produces a new data type. Each of these type modifiers is appli-
cable to the basic data type int. The modifiers signed and unsigned are also applicable to the type
char. The long type modifier can be applicable to double type.

M02_KAMT3553_02_SE_C02.indd 46 5/17/2015 9:05:10 AM


The C Declarations 47

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.

2.17 TYPE CONVERSION


In C, it is possible to convert one data type to another. This process can be done either explicitly or
implicitly. The following section describes explicit type conversion.
(i) Explicit type conversion
a) Sometimes a programmer needs the result in certain data type, for example division of
5 with 2 should return float value. Practically the compiler always returns integer values
because both the arguments are of integer data type.
(ii) Implicit type conversion
In C automatically ‘lower’ data type is promoted to ‘upper’ data type. For example, data type
char or shor t i s converted to int. This type of conversion is called as automatic unary
conversion. Even when binary operator has different data types, ‘lower’ data type is converted
to ‘upper’ data type.
In case an expression contains one of the operands as unsigned operands and another non-
unsigned, the latter operand is converted to unsigned.
Similarly, in case an expression contains one of the operands as float operands and another
non-float, the latter operand is converted to float.

M02_KAMT3553_02_SE_C02.indd 47 5/17/2015 9:05:10 AM


48 Programming in C

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.

Expression Operator Operand 1 Operand 2 Outcome


a unary shor t – int
a/b binary int float float
a/b-c binary float long int float
(a/b-c) d binary float double double

2.6 The following program explains the above concepts.

#include <s tdio . h>


#include <conio . h>
int main( )
{
shor t a=5;
long int b=123456;
float c=234 . 56;
double d=234567 . 78695;
cl rscr ( ) ;

pr int f (“%l f” , ( (a+b)*c) /d) ;


return 0;
}

OUTPUT:
123 . 456900

Explanation:
In the above program, we have taken the variable ‘a’ as short int, ‘b’ as long, c as float and
‘d’ as double. The expression ((a + b) c)/d) gives the result as double float.
Sometimes a programmer needs the result in a certain data type, for example division of 5 with 2
should return float value. Practically, the compiler always returns integer values because both the
arguments are of integer data type. This can be followed by the execution of the following program.

2.7 Write a program to change data type of results obtained by division operations.

void main( )
{
cl rscr ( ) ;
pr int f (“\n Divi s ion operat ion Resul t”) ;
pr int f (“\n Two Integers (5 & 2) : %d” , 5/2) ;

M02_KAMT3553_02_SE_C02.indd 48 5/17/2015 9:05:10 AM


The C Declarations 49

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

2.18 WRAPPING AROUND


When the value of variable goes beyond its limit, the compiler would not flag any error message. It
just wraps around the value of a variable. For example, the range of unsigned integer is 0 to 65535. In
this type, negative values and values greater than 65535 are compatible.
unsigned int x=65536;

M02_KAMT3553_02_SE_C02.indd 49 5/17/2015 9:05:11 AM


50 Programming in C

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.

2.19 CONSTANT AND VOLATILE VARIABLES


2.19.1 | Constant Variable
If we want the value of a certain variable to remain the same or unchanged during the program
execution, it can be done by declaring the variable as a constant. The keyword cons t is then prefixed
before the declaration. It tells the compiler that the variable is a constant. Thus, constant declared
variables are protected from modification.
Example:
const int m=10;
Where const is a keyword, m is variable name and 10 is a constant.
The compiler protects the value of ‘m’ from modification. The user cannot assign any value to
‘m’, but using pointer the value can be changed. When user attempts to modify the value of con-
stant variable, the message ‘canno t mod i fy t he cons t an t ob j ec t ’ will be displayed.

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;

M02_KAMT3553_02_SE_C02.indd 50 5/17/2015 9:05:11 AM


The C Declarations 51

A program on the above concepts is given below.


2.9 Write a program to demonstrate wrapping around.

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.

M02_KAMT3553_02_SE_C02.indd 51 5/17/2015 9:05:11 AM


52 Programming in C

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.

8. ‘A’ is a character constant. 17. int occupies 4 bytes in memory.

9. “India” is a string constant. 18. const int a=10; value of a cannot


bechanged during program execution.
10. A variable is a data name used for storing data
values. 19. _abc is a valid variable name.

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 (++)

M02_KAMT3553_02_SE_C02.indd 52 5/17/2015 9:05:11 AM


The C Declarations 53

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

M02_KAMT3553_02_SE_C02.indd 53 5/17/2015 9:05:11 AM


54 Programming in C

25. Integer constants in C can be (c) five


(d) any number of variables
(a) positive
(b) negative 30. What is the output of the following program?
(c) positive or negative
void main( )
(d) None of the above
{
26. Which of the following statement is wrong? unsigned long v=-1;
cl rscr ( ) ;
(a) 5+5=a; pr int f (“\n %lu” , v) ;
(b) ss=12 . 25; }
(c) s t=‘m’ * ‘b’ ;
(d) is =‘A’+10; (a) 4294967295
(b) 0
27. The ANSI C standard allows a minimum of (c) –1
(a) 31significant characters in identifier (d) None of the above
(b) 8 significant characters in identifier 31. What would be the values of variables c and u?
(c) 25 significant characters in identifier
(d) unlimited characters void main( )
{
28. In C the first character of the variable should be char c=-127;
(a) an integer unsigned char u=-127;
(b) an alphabet cl rscr ( ) ;
(c) a floating number pr int f (“\n c=%d u= %d” , c , u) ;
(d) None of the above }
(a) c=127 u=127
29. How many variables can be initialized at a time?
(b) c= –127 u=129
(a) one (c) c=127 u=128
(b) two (d) None of the above

III What will be the output/s of the following program/s?

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; }

M02_KAMT3553_02_SE_C02.indd 54 5/17/2015 9:05:11 AM


The C Declarations 55

IV Find the bug/s in the following program/s:

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( ) ;
} }

V Answer the following questions:


1. What are the different data types? 11. What are the delimiters? Explain their uses.
2. What are the differences between signed and 12. Is ‘main’ a keyword? Explain.
unsigned data types?
13. List any three keywords with their use.
3. What does we mean by a variable and constant?
14. What is the difference between %f and %g control
4. Explain different types of constants in C. strings? Whether both can be used for represent-
5. What are the C keywords? Elaborate them. ing float numbers?
6. List the rules for declaring a variable. 15. What do you mean by type conversion? Why is it
necessary?
7. What are the identifiers?
16. What is wrapping around?
8. Explain the methods for initialization of variables.
9. Explain constants and volatile variables. 17. List the name of type modifiers.

10. Write about space requirement for variables of 18. What is dynamic initialization?
different data types.

M02_KAMT3553_02_SE_C02.indd 55 5/17/2015 9:05:11 AM


56 Programming in C

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

III What will be the output/s of the following program/s?


Q. Ans. Q. Ans.
1. Z 4. a=0.3 b=0.02
2. 65 A 65 5. a=10 b=10
3. u=65535 l=2147483647

IV Find the bug/s in the following program/s:


Q. Ans.
1. Float must be enclosed with bracket, then answer will be
3
3.5
3.5
2. Missing comma (,) in the pr int f ( ).
Answer after correction 25 26
3. First %c is to be replaced by %u and then answer will be 65535 A. However,
with %c also program runs.

M02_KAMT3553_02_SE_C02.indd 56 5/17/2015 9:05:11 AM


The C Declarations 57

4. Control string provided is wrong. %f and %l f are needed. Answer would be


65535.429688 65789.987654. However, with %d & %d answers obtained would
be wrong.
5. Space between size and of should be removed. The answer will be
1234567.375000 987654321.123457
48
6. Syntex error in first line #define. Remove = . Answer will be 900

M02_KAMT3553_02_SE_C02.indd 57 5/17/2015 9:05:11 AM


CHAPTER

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

M03_KAMT3553_02_SE_C03.indd 58 5/17/2015 9:06:37 AM


Operators and Expressions 59

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.

Table 3.1 Types of operators


Type of Operator Symbolic Representation
Arithmetic operators + , – , * , / and %
Relational operators > , < , == , >= , <= and !=
Logical operators && , | | and !
Increment and Decrement operators ++ and ––
Assignment operator = , *= , /= , %= , += , –= ,
&= , ^= , | = , <<= , >>=
Bitwise operators & , | , ^ , >> , << and ˜
Comma operator ,
Conditional operators ?:

3.2 OPERATOR PRECEDENCE


Precedence means priority. Every operator in C has assigned precedence (priority). An expression
may contain a lot of operators. The operations on the operands are carried out according to the prior-
ity of the operators. The operators having higher priority are evaluated first and then lower priority.
(i) For example, in arithmetic operators, the operators , / and % have assigned highest priority
and of similar precedence. The operators + and – have the lowest priority as compared to the
above operators.
Example:
8+9 2–10
The operator is the highest priority. Hence, the multiplication operation is performed first.
The above expression becomes
8+18 –10
In the above expression, + and – have the same priority. In such a situation, the left most
operation is evaluated first. With this the above expression becomes
26−10
At last the subtraction operation is performed and answer of the expression will be as follows:
16
(ii) When the operators of the same priority are found in the expression, precedence is given to
the left most operators.

M03_KAMT3553_02_SE_C03.indd 59 5/17/2015 9:06:37 AM


60 Programming in C

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

The execution of the above equation is self-explanatory.


The following program is provided for understanding the concepts of precedence of operators.

M03_KAMT3553_02_SE_C03.indd 60 5/17/2015 9:06:38 AM


Operators and Expressions 61

3.1 Write a program to demonstrate the precedence of operators.

# include <s tdio . h>


# include <conio . h>

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.

The list of operators according to priority (Hierarchical) is given in Table 3.2

Table 3.2 Prioritywise list of operators


Associativity or
Operators Operation Clubbing Priority

() Function call Left to right 1st


[] Array expression or square
bracket
–> Structure operator
. Structure operator

+ Unary plus Right to left 2nd


– Unary minus
++ Increment
–– Decrement
! Not operator
˜ One’s complement
* Pointer operator
& Address operator
s izeof Size of an object
Type Type cast

(Continued)

M03_KAMT3553_02_SE_C03.indd 61 5/17/2015 9:06:38 AM


62 Programming in C

Table 3.2 Prioritywise list of operators (Continued )


Associativity or
Operators Operation Clubbing Priority

* Multiplication Left to right 3rd


/ Division
% Modular division

+ Addition (Binary plus) Left to right 4th


- Subtraction (Binary minus)

<< Left shift Left to right 5th


>> Right shift

< Less than Left to right 6th


<= Less than or equal to
> Greater than
>= Greater than or equal to

== Equality Left to right 7th


! = Inequality (Not equal to)

& Bitwise AND Left to right 8th

^ Bitwise XOR Left to right 9th

| Bitwise OR Left to right 10th

&& Logical AND Left to right 11th

|| Logical OR Left to right 12th

?: Conditional operator Right to left 13th

= , *= , /= , %= , Assignment operators Right to left 14th


+= , –= , &= , ^= ,
| = , <<= , >>=

, Comma operator Right to left 15th

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).

M03_KAMT3553_02_SE_C03.indd 62 5/17/2015 9:06:38 AM


Operators and Expressions 63

= 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.

3.4 COMMA AND CONDITIONAL OPERATOR


(i) Comma Operator (,): The comma operator is used to separate two or more expressions. The
comma operator has the lowest priority among all the operators. It is not essential to enclose
the expressions with comma operators within the parentheses. For example, the following
statements are valid.
Example:
a=2 , b=4 , c=a+b;
(a=2 , b=4 , c=a+b; )

3.2 Write a program to illustrate the use of comma (,) operator.

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.

M03_KAMT3553_02_SE_C03.indd 63 5/17/2015 9:06:38 AM


64 Programming in C

The below mentioned program illustrates the use of conditional operator.


3.3 Write a program to use the conditional operator with two values.

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.

3.5 ARITHMETIC OPERATORS


There are two types of arithmetic operators. These are (i) binary operator and (ii) unary operator.
As shown in Figure 3.1, the unary and binary operators are defined in the following section and
the ternary operator is described in Section 3.4. The conditional operator is nothing but the ternary
operator.
Unary

Operators Binary

Ternary

Figure 3.1 Operators

(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.

M03_KAMT3553_02_SE_C03.indd 64 5/17/2015 9:06:39 AM


Operators and Expressions 65

C evaluates arithmetic operations as follows.


(a) Division, multiplication and remainder operations are solved first. When an expression con-
tains many operators such as multiplication, division and modular division operations, expres-
sion evaluation starts from left to right. Multiplication, division and modular division operators
are having equal level of precedence.
(b) The addition and subtraction operations are solved after division, multiplication and modular
division operations. Evaluation starts from left to right. Addition and subtraction have equal
level of precedence.
From Table 3.3, the modular division operator cannot be applied to float and double data
types.

Table 3.3 Arithmetic operators


Arithmetic Operators Operator Explanation Examples
+ Addition 2+2=4
- Subtraction 5−3=2
* Multiplication 2 5=10
/ Division 10/2=5
% Modular division 11%3=2 (Remainder 2)

(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.

M03_KAMT3553_02_SE_C03.indd 65 5/17/2015 9:06:39 AM


66 Programming in C

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;

M03_KAMT3553_02_SE_C03.indd 66 5/17/2015 9:06:39 AM


Operators and Expressions 67

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.

3.6 RELATIONAL OPERATORS


These operators are used to distinguish between two values depending on their relations. These op-
erators provide the relationship between two expressions. If the relation is true then it returns a value
1 otherwise 0 for false. The relational operators together with their descriptions, example and return
value are described in Table 3.5.

M03_KAMT3553_02_SE_C03.indd 67 5/17/2015 9:06:39 AM


68 Programming in C

Table 3.5 Relational operators


Operator Description or Action Example Return Value
> Greater than 5>4 1

< Less than 10<9 0

<= Less than or equal to 10<=10 1

>= Greater than equal to 11>=5 1

== Equal to 2==3 0

!= Not equal to 3!=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.

3.7 ASSIGNMENT OPERATORS AND EXPRESSIONS


Assigning a value to a variable is very simple. For example, int x=5; here, 5 is assigned to x and
this is carried out by the operator =. The equal sign (=) is used for assignment and hence, the name
assignment operator has been given. The list of assignment operators is given in Table 3.6.

M03_KAMT3553_02_SE_C03.indd 68 5/17/2015 9:06:39 AM


Operators and Expressions 69

Table 3.6 Assignment operators


= *= /= %=
+= -= <<= >>=
>>>= &= ^= !=

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 ( ) ;

M03_KAMT3553_02_SE_C03.indd 69 5/17/2015 9:06:39 AM


70 Programming in C

pr int f (“Enter Any Integer whose value i s 5 or any other : -”) ;


scanf (“%d” , &a) ;
b=(a==5 ? 3: 4) ;
pr int f (“Calculated Value of b i s : - %d\n” , b) ;
}
OUTPUT:
Enter Any Integer whose value i s 5 or any other : - 3
Calculated Value of b i s: - 4

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

M03_KAMT3553_02_SE_C03.indd 70 5/17/2015 9:06:39 AM


Operators and Expressions 71

Explanation:
In the above given program, three integers are entered through the keyboard (x , y and z).
Using conditional statements, values of a, b and c are obtained. The sum of x, y and z is
stored in ‘m’ and the sum of a , b and c is stored in ‘n’. The variables ‘m’ and ‘n’ are com-
pared and appropriate messages are displayed.

3.8 LOGICAL OPERATORS


The logical relationship between the two expressions is tested with logical operators. Using these
operators, two expressions can be joined. After checking the conditions, it provides logical true (1) or
false (0) status. The operands could be constants, variables and expressions. Table 3.7 describes the
three logical operators together with examples and their return values.
Table 3.7 Logical operators
Operator Description or Action Example Return Value
&& Logical AND 5>3 && 5<10 1
|| Logical OR 8>5 | | 8<2 1
! Logical NOT 8!=8 0

From Table 3.7, following rules can be followed for logical operators:
(i) The logical AND (&&) operator provides true result when both expressions are true,
otherwise 0.
(ii) The logical OR ( | | ) operator provides true result when one of the expressions is true,
otherwise 0.
(iii) The logical NOT operator (!) provides 0 if the condition is true, otherwise 1.

3.12 Illustrate the use of logical operators.

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.

M03_KAMT3553_02_SE_C03.indd 71 5/17/2015 9:06:39 AM


72 Programming in C

3.13 Write a program to print logic 1 if input character is capital otherwise 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.

M03_KAMT3553_02_SE_C03.indd 72 5/17/2015 9:06:39 AM


Operators and Expressions 73

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.

M03_KAMT3553_02_SE_C03.indd 73 5/17/2015 9:06:39 AM


74 Programming in C

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.

3.9 BITWISE OPERATORS


C supports a set of bitwise operators for bit manipulation as listed in Table 3.8. C supports six bit opera-
tors. These operators can operate only on integer operands such as int , char , shor t , long.
Table 3.8 Bitwise operators
Operators Meaning
>> Right shift
<< Left shift
^ Bitwise XOR (exclusive OR)
˜ One’s complement
& Bitwise AND
| Bitwise OR

3.18 Write a program to shift inputted data by two bits right.

void main( )
{
int x , y;
cl rscr ( ) ;
pr int f (“Read The Integer f rom keyboard (x) : -”) ;
scanf (“%d” , &x) ;

M03_KAMT3553_02_SE_C03.indd 74 5/17/2015 9:06:39 AM


Operators and Expressions 75

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:

3.19 Write a program to shift inputted data by three bits left.

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

M03_KAMT3553_02_SE_C03.indd 75 5/17/2015 9:06:39 AM


76 Programming in C

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

M03_KAMT3553_02_SE_C03.indd 76 5/17/2015 9:06:39 AM


Operators and Expressions 77

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( ) ;
}

M03_KAMT3553_02_SE_C03.indd 77 5/17/2015 9:06:39 AM


78 Programming in C

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;

M03_KAMT3553_02_SE_C03.indd 78 5/17/2015 9:06:39 AM


Operators and Expressions 79

pr int f (“The data af ter Exclus ive OR operat ion is in c= %d” , c) ;


getche( ) ;
}

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).

Table 3.12 Table of inverter logic


Input (X) Output (X)
0 1
1 0

The operator ~ is used for inverting the bits with this operator 0 becomes 1 & 1 becomes 0.

3.23 Write a program to show the effect of ~ operator.

void main( )
{
unsigned int v=0;
cl rscr ( ) ;
pr int f (“\n %u” , ~v) ;
}

OUTPUT:
65535

M03_KAMT3553_02_SE_C03.indd 79 5/17/2015 9:06:39 AM


80 Programming in C

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

M03_KAMT3553_02_SE_C03.indd 80 5/17/2015 9:06:39 AM


Operators and Expressions 81

5. What is the value of !0? 11. What is the remainder of 8% 10?


(a) 1 (a) 8
(b) 0 (b) 2
(c) −1 (c) 1
(d) None of the above (d) 0
6. Hierarchy decides which operator 12. The result of the expression (10/3)*3+5%3 is
(a) is used first (a) 11
(b) is the most important (b) 10
(c) operates on large numbers (c) 8
(d) None of the above (d) 1

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

M03_KAMT3553_02_SE_C03.indd 81 5/17/2015 9:06:40 AM


82 Programming in C

II Attempt the following programming exercises:

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.

III Answer the following questions:

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 ‘= =’?

M03_KAMT3553_02_SE_C03.indd 82 5/17/2015 9:06:40 AM


Operators and Expressions 83

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

M03_KAMT3553_02_SE_C03.indd 83 5/17/2015 9:06:40 AM


CHAPTER

4 Input and Output


in C

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

M04_KAMT3553_02_SE_C04.indd 84 5/17/2015 9:12:11 AM


Input and Output in C 85

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.

M04_KAMT3553_02_SE_C04.indd 85 5/17/2015 9:12:12 AM


86 Programming in C

Input and Output Functions

Formatted Functions Unformatted Functions

printf()
getch() putch()
scanf ()
getche() putchar()
getchar() puts()
gets()

Figure 4.1 Formatted and unformatted functions

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.

4.2 FORMATTED FUNCTIONS


(i) The pr int f ( ) statement: The formatted output as per the programmers requirement
is displayed on the screen with pr int f ( ). The list of variables can be indicated in the
pr int f ( ). The values of variables are printed according to the sequence mentioned in
pr int f ( ). The pr int f ( ) function prints all types of data values to the console. It trans-
lates internal values to characters. It requires format conversion symbol or format string and
variable names to print the data. The format string symbol and variable names should be the
same in number and type. The syntax of pr int f ( ) statement is as follows:
pr int f (“Cont rol st r ing” , var iable1 , var iable2 , . . . var iable n) ;
The control string specifies the field format such as %d , %s , %g , %f , and variables as
taken by the programmer.

M04_KAMT3553_02_SE_C04.indd 86 5/17/2015 9:12:12 AM


Input and Output in C 87

The following are a few examples of the pr int f ( ) function.


Example:

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;
}

M04_KAMT3553_02_SE_C04.indd 87 5/17/2015 9:12:12 AM


88 Programming in C

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.

4.3 FLAGS, WIDTHS AND PRECISION WITH FORMAT STRING


The plain characters are straightforward and are used to write data on the screen. On the other hand,
the conversion specification retrieves arguments from the list of arguments and apply different format-
ting to them. All format specification starts with % and a format specification letter after this symbol.
It indicates the type of data and its format. In case the format string does not match the corresponding
variable, the result will not be correct.
Flags: Flags are used for output justification, numeric signs, decimal points, trailing zeros. The flag (-)
left justifies the result. If it is not given, the default is right justification. The plus (+) signed conversion
result always starts with a plus (+) or a minus (-) sign.
Width specifier : It sets the minimum field width for an output value. Width can be specified
through a decimal point or using an asterisk ‘*’.
Few programs are provided on width requirement.
4.1 Write a program to demonstrate the use of width specifier.

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;

M04_KAMT3553_02_SE_C04.indd 88 5/17/2015 9:12:12 AM


Input and Output in C 89

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) ;
}

M04_KAMT3553_02_SE_C04.indd 89 5/17/2015 9:12:12 AM


90 Programming in C

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.

Table 4.1 Formats for various outputs


Sr. No. Format Meaning Explanation
1 %wd Format for integer output w is width in integer and d is conversion
specification
2 %w . cf Format for float numbers w is width in integer, c specifies the number
of digits after decimal point and f specifies the
conversion specification
3 %w . cs Format for string output w is width for total characters, c are used
for displaying leading blanks and s specifies
conversion specification

A programming example is provided on the above formats for readers understanding.


4.5 Write a program to display the integers, float point numbers and string with different formats
as explained above.

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( ) ;
}

M04_KAMT3553_02_SE_C04.indd 90 5/17/2015 9:12:12 AM


Input and Output in C 91

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.

M04_KAMT3553_02_SE_C04.indd 91 5/17/2015 9:12:12 AM


92 Programming in C

4.6 Write a program to show the effect of mismatch of data types.

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.

M04_KAMT3553_02_SE_C04.indd 92 5/17/2015 9:12:12 AM


Input and Output in C 93

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.

Table 4.2 Formats for the various inputs


Sr. No. Format Meaning Explanation
1. %wd Format for integer input w is width in integer and d conversion
specification
2. %w . cf Format for float point input w is width in integer, c specifies the number of
digits after decimal point and f is conversion
specification
3. %w . cs Format for string input w is the width for total characters, c are used
for inserting blanks and s is conversion
specification

An example illustrating a few formatted input is as follows.


4.9 Write a program to demonstrate the use of scanf( ) with different formats.

void main( )
{
int a , b;
float x;

M04_KAMT3553_02_SE_C04.indd 93 5/17/2015 9:12:12 AM


94 Programming in C

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.

Table 4.3 Data types with conversion symbols


Data Type Format String
Short integer %d or %i
Short unsigned %u
Long signed %ld
Integer
Long unsigned %lu
Unsigned hexadecimal %x
Unsigned octal %o
(Continued)

M04_KAMT3553_02_SE_C04.indd 94 5/17/2015 9:12:12 AM


Input and Output in C 95

Table 4.3 Data types with conversion symbols (Continued )


Data Type Format String
Real Floating %f or %g
Double floating %l f
Signed character %c
Character Unsigned character %c
String %s
Octal number %o
Displays Hexa decimal number %hx
in lowercase
Displays Hexa decimal number %p
in uppercase
Aborts program with error %n

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.

Table 4.4 Escape sequences with their ASCII values


Escape Sequence Use ASCII Value
\n New line 10
\b Backspace 8
\f Form feed 12
\’ Single quote 39
\\ Backslash 92
\0 Null 0
\t Horizontal tab 9
\r Carriage return 13
\a Alert 7
\” Double quote 34
\v Vertical tab 11
\? Question mark 63

4.10 Write a program to show the effect of various escape sequences.

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*************”) ;

M04_KAMT3553_02_SE_C04.indd 95 5/17/2015 9:12:12 AM


96 Programming in C

pr int f (“\ rA=%d B=%d” , a , b) ;


}

OUTPUT:
A=1
B=2 ‘C=3’
***D=4**
A=1 B=2******

Explanation:
In the above program, a few commonly used escape sequences are described.
(i) In the first 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.

#include <math . h>


void main( )
{
double x = 2 . 0 , y = 3 . 0;
cl rscr ( ) ;
pr int f (“%l f rai sed to %l f i s %l f \n” , x , y , pow(x , y) ) ;
}

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.

#include <math . h>


void main
{
int p = 3;

M04_KAMT3553_02_SE_C04.indd 96 5/17/2015 9:12:13 AM


Input and Output in C 97

pr int f (“Ten raised to %l f i s %l f \n” , p , pow10(p) ) ;


}

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

M04_KAMT3553_02_SE_C04.indd 97 5/17/2015 9:12:13 AM


98 Programming in C

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;

M04_KAMT3553_02_SE_C04.indd 98 5/17/2015 9:12:13 AM


Input and Output in C 99

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.

4.4 UNFORMATTED FUNCTIONS


C has three types of I/O functions.
(i) Character I/O
(ii) String I/O
(iii) File I/O

M04_KAMT3553_02_SE_C04.indd 99 5/17/2015 9:12:13 AM


100 Programming in C

(i) Character I/O

1.
getchar ( ) -

This function reads a character-type data from standard input. It reads one character at a time
till the user presses the enter key. The syntax of the getchar ( ) is as follows:
Variable name=getchar ( ) ;
Example:
char c;
c=getchar ( ) ;
A program is supported for the following getchar ( ) function.
4.19 Write a program to accept characters through keyboard using getchar ( ) function.

void main( )
{
char c;
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 ( ).

M04_KAMT3553_02_SE_C04.indd 100 5/17/2015 9:12:13 AM


Input and Output in C 101

4.20 Write a program to use putchar ( ) in work.

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.

M04_KAMT3553_02_SE_C04.indd 101 5/17/2015 9:12:13 AM


102 Programming in C

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.

M04_KAMT3553_02_SE_C04.indd 102 5/17/2015 9:12:13 AM


Input and Output in C 103

2.
put s( ) :

This function prints the string or character array. It is opposite to gets( ).


char st r [ length of st r ing in number ] ;
gets(st r ) ;
puts(st r ) ;
A program is given on put s( ).
4.24 Write a program to print the accepted character using puts( ) function.

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( ) :

This function displays string on the console. The syntax is as follows.

M04_KAMT3553_02_SE_C04.indd 103 5/17/2015 9:12:13 AM


104 Programming in C

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.

4.5 COMMONLY USED LIBRARY FUNCTIONS

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 ( )

This function terminates the program. It is defined in process . h header file.


The syntax is as follows.
Syntax:
exi t ( ) ;

3.
s leep( )

M04_KAMT3553_02_SE_C04.indd 104 5/17/2015 9:12:13 AM


Input and Output in C 105

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.

4.6 STRONG POINTS FOR UNDERSTANDABILITY


Computer produces output, which is useful for the user. Therefore, the clarity and neatness of result
should appear in the output. The following are a few steps which can be followed to produce the
neatness output:
(i) Give space between numbers.
(ii) Provide suitable and problem-related variable names and headings.
(iii) Provide user prompt so that the user can understand what to do.

M04_KAMT3553_02_SE_C04.indd 105 5/17/2015 9:12:13 AM


106 Programming in C

(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.

M04_KAMT3553_02_SE_C04.indd 106 5/17/2015 9:12:13 AM


Input and Output in C 107

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

(a) 65666768 (a) tab


(b) ABCD (b) next line
(c) 91929394 (c) backspace
(d) None of the above (d) None of the above

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

M04_KAMT3553_02_SE_C04.indd 107 5/17/2015 9:12:13 AM


108 Programming in C

9. Which is the correct statement for finding the void main( )


cube of 2? {
char yourname[10]={“AJAY”};
(a) pow(2,3); cl rscr ( ) ;
(b) pow(3,2); pr int f (“\n Welcome %s to ‘C’
(c) pow(3); Programming Course”, yourname) ;
(d) None of the above }
10. The abs( ) function displays (a) Welcome AJAY to ‘C’ Programming Course
(a) an absolute value (b) Welcome to ‘C’ Programming Course
(b) a negative value (c) Welcome ‘C’ Programming Course
(c) a zero value (d) None of them
(d) None of the above 13. What will be the values of a and b after execution
11. What will be the output of the following program? of the following program?
void main( )
void main( ) {
{ int a , b;
pr int f (“\n %d%d%d%d” , ‘a’ , a=65*66;
‘b’ , ‘c’ , ‘d’ ) ; b=‘A’*‘B’ ;
} cl rscr ( ) ;
(a) 979899100 pr int f (“a=%d b=%d” , a , b) ;
(b) 87888990 }
(c) 90919293 (a) a=4290 b=4290
(d) None of them (b) a=4290 b=9506
12. What will be the output of the following pro- (c) a=4290 b=0
gram? (d) None of the above

IV Attempt the following programming exercises:

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.

M04_KAMT3553_02_SE_C04.indd 108 5/17/2015 9:12:13 AM


Input and Output in C 109

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.

V What will be the output/s of the following program/s?


1. 3.
void main( ) void main( )
{ {
cl rscr ( ) ; char st r=”C Programming”;
pr int f (“\n %o %hx %p” , 45 , cl rscr ( ) ;
65 , 65) ; put s(st r ) ;
} getche( ) ;
}
2.
void main( ) 4.
{ void main( )
int x=67 , y=68 , z=69; {
cl rscr ( ) ; int k=‘A’ ;
pr int f (“\n%c %c %c” , x , cl rscr ( ) ;
y , z) ; whi le (k<=‘K’ ) putch(k++) ;
getche( ) ;
}

VI Find the bug/s in the following program/s:


1. char x , d;
void main( ) cl rscr ( ) ;
{ pr int f(“Enter an
int x=2; alphabet :”) ;
char y=‘A’ ; x=getchar ( ) ;
float f=2 . 05; }
cl rscr ( ) ;
pr int f (“%d %c %f” , f , y , x) ; 4.
getche( ) ; void main( )
} {
cl rscr ( ) ;
2. pr int f (“I \nam /n an\ t
void main( ) Indian”) ;
{ }
int x;
cl rscr ( ) ; 5.
pr int f (“Enter a void main( )
Number :”) ; {
scanf (“%d” , x) ; putchar (“x”) ;
pr int f (“%d” , x) ; }
}
3.
void main( )
{

M04_KAMT3553_02_SE_C04.indd 109 5/17/2015 9:12:13 AM


110 Programming in C

VII Answer the following questions:


1. What are the formatted and unformatted 7. How cgets( ) is different from get s( )?
functions?
8. How will you execute a DOS command through
2. What is the difference between character I/O and C program?
string I/O?
9. What is the use of the exi t ( ) function?
3. What is the escape sequence? List and indicate the
10. What is a stream?
functions of escape sequences.
11. What are the tips to the design output?
4. List any three escape sequences with their uses.
5. What is the difference between put s( ) and
putch( )?
6. What is the difference between getch( ) and
getche( )?

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

V What will be the output/s of the following program/s?


Q. Ans.
1. 55 41 0041
2. CDE
3. No Output
4. ABCDEFGHIJK

M04_KAMT3553_02_SE_C04.indd 110 5/17/2015 9:12:14 AM


Input and Output in C 111

VI Find the bug/s in the following program/s:


Q. Ans.
1. Program runs but output will be 0 because formatted data cannot be displayed
through unformatted functions. After putting them in sequence output will be 2
A 2.050000.
2. In scanf ( ) & is not prefixed before variable name.
3. Header file <stdio . h> must be included
4. No bug
5. putchar ( ) cannot be used to display string. Instead of it use put s( ).

M04_KAMT3553_02_SE_C04.indd 111 5/17/2015 9:12:14 AM


CHAPTER

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

M05_KAMT3553_02_SE_C05.indd 112 5/17/2015 9:13:21 AM


Decision Statements 113

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

M05_KAMT3553_02_SE_C05.indd 113 5/17/2015 9:13:21 AM


114 Programming in C

Bohm and Jacopini demonstrated that all the programs could be written by using only three control
structures, i.e. sequence structure, selection structure and repetition structure by eliminating the goto
statement.

5.2 THE i f STATEMENT


void main ( )
C uses the keyword i f to execute a set of command
lines or one command line when the logical condition {
is true. It has only one option. The sets of command TRUE FALSE
lines are executed only when the logical condition is i f (expression)
true (see Figure 5.1). {
s tatement1;
s tatement2;
}
Syntax for the simplest i f statement : -
i f (condi t ion) /* no semi -colon */ s tatement3;
}
statement ;

Figure 5.1 The i f 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

M05_KAMT3553_02_SE_C05.indd 114 5/17/2015 9:13:22 AM


Decision Statements 115

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

Figure 5.2 The i f statement (flow of control)

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 .

M05_KAMT3553_02_SE_C05.indd 115 5/17/2015 9:13:22 AM


116 Programming in C

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.

5.3 THE i f–else STATEMENT


We observed the execution of the i f statement in the previous programs. We observed that the i f
block statements execute only when the condition in i f is true. When the condition is false, program
control executes the next statement which appears after the i f statement.
The i f–else statement takes care of the true and false conditions. It has two blocks. One block
is for i f and it is executed when the condition is true. The other block is of else and it is executed
when the condition is false. The el se statement cannot be used without i f. No multiple else state-
ments are allowed with one i f (see Figures 5.3 and 5.4).
The flow chart for the i f–el se statement is given in Figure 5.4.

M05_KAMT3553_02_SE_C05.indd 116 5/17/2015 9:13:22 AM


Decision Statements 117

From Previous statement

void main ( ) Is Condition No


Satisfied?
{
TRUE FALSE
Yes else block execution
i f (express ion)
{
statement1; i f block execution
statement2;
}
else
{
statement3; Next statement
statement4;
}
}
Stop

Figure 5.3 The i f–e l se statements Figure 5.4 The i f–e l se statement

The syntax of i f–el se statement is as follows:


i f ( the condi t ion i s t rue)
execute the Statement1;
else
execute the Statement2;

OR

Syntax of i f–el se statement can be given as follows:


i f ( expression i s t rue)
{
statement1; /* i f block */
statement2;
}
el se
{
statement3; /* el se block */
statement4;
}

The i f–el se statement is demonstrated in the following programs.


5.4 Write a program to find the roots of a quadratic equation by using i f -else condition.

# include <math . h>


void main( )
{
int b , a , c;

M05_KAMT3553_02_SE_C05.indd 117 5/17/2015 9:13:23 AM


118 Programming in C

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.

M05_KAMT3553_02_SE_C05.indd 118 5/17/2015 9:13:23 AM


Decision Statements 119

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( ) ;
}

M05_KAMT3553_02_SE_C05.indd 119 5/17/2015 9:13:23 AM


120 Programming in C

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.

5.4 NESTED i f–else STATEMENTS


In this kind of statement, a number of logical conditions are checked for executing various statements.
Here, if any logical condition is true the compiler executes the block followed by i f condition, other-
wise it skips and executes the else block. In the i f–else statement, the else block is executed
by default after failure of condition. In order to execute the else block depending upon certain con-
dition we can add, repetitively, i f statements in else block. This kind of nesting will be unlimited.
Figure 5.5 describes the nested i f–el se–i f blocks.
From Previous Statement

Is 1st
False True
Condition
Satisfied?

Is 3rd Is
False True
Condition False True
2nd Condition
Satisfied? Satisfied?

Statement 4 Statement 3 Statement 2 Statement 1

Next Statement

Figure 5.5 Nested i f–e l se statements

M05_KAMT3553_02_SE_C05.indd 120 5/17/2015 9:13:23 AM


Decision Statements 121

Syntax of nested i f -else statement can be given as follows.

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.

5.5 THE i f -else- i f LADDER STATEMENT


In this kind of statement, a number of logical conditions are checked for executing various statements.
Here, if the first logical condition is true the compiler executes the block followed by first i f condition,
otherwise it skips that block and checks for next logical condition followed by else- i f , if the condition
is true the block of statements followed by that i f condition is executed. The process is continued until a
true condition is occurred or an else block is occurred. If all i f conditions become false, it executes the
else block. In the i f-else- i f ladder statement, the else block may or may not have the else block.
In i f -else- i f ladder statement we do not have to pair i f statements with the else statements
that is we do not have to remember the number of braces opened like nested i f -else . So it is sim-
pler to code than nested i f -el se and having same effect as nested i f -else .

M05_KAMT3553_02_SE_C05.indd 121 5/17/2015 9:13:23 AM


122 Programming in C

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

True Is 1st i f False


Condition
True?
True Is 2nd i f False
Condition
True?
True Is 3rd i f False
Condition
True?
True Is 4th i f
Condition False
True?

Statement 1 Statement 2 Statement 3 Statement 4 Statement 5

To Next Statement

Figure 5.6 i f–e l se– i f ladder statement

Syntax of i f -el se- i f statement can be given as follows.

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;
}

M05_KAMT3553_02_SE_C05.indd 122 5/17/2015 9:13:24 AM


Decision Statements 123

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.

No . of uni t s consumed Rates in (Rs . )


200–500 3 . 50
100–200 2 . 50
Less than 100 1 . 50

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.

M05_KAMT3553_02_SE_C05.indd 123 5/17/2015 9:13:24 AM


124 Programming in C

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.

M05_KAMT3553_02_SE_C05.indd 124 5/17/2015 9:13:24 AM


Decision Statements 125

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 :”) ;

M05_KAMT3553_02_SE_C05.indd 125 5/17/2015 9:13:24 AM


126 Programming in C

scanf (“%d %d %d” , &a , &b , &c) ;


i f (a<b)
{
i f (a<c)
smal les t=a;
el se
smal les t=c;
}
el se
{
i f (b<c)
smal les t =b;
el se
smal les t =c;
}
pr int f (“The smal les t of %d %d %d i s %d \n” , a , b , c , smal lest ) ;
getche( ) ;
}

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.

Basic Salary (Rs . ) DA (Rs . ) HRA (Rs . ) Conveyance (Rs. )


BS>=5000 110% of Basic 20% of Bas ic 500
Bs=>3000 && bs<5000 100% of Basic 15% of Bas ic 400
bs<3000 90% of Bas ic 10% of Bas ic 300

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;

M05_KAMT3553_02_SE_C05.indd 126 5/17/2015 9:13:24 AM


Decision Statements 127

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.

PRINCIPLE AMOUNT (Rs . ) Rate of Interes t (Rs . )


>=10000 20%
>=8000 && <=9999 18%
<8000 16%

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;

M05_KAMT3553_02_SE_C05.indd 127 5/17/2015 9:13:24 AM


128 Programming in C

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 ( ) ;
}

M05_KAMT3553_02_SE_C05.indd 128 5/17/2015 9:13:24 AM


Decision Statements 129

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.

5.6 THE break STATEMENT


The keyword break allows the programmers to terminate the loop. The break skips from the loop
or block in which it is defined. The control then automatically goes to the first statement after the loop
or block. The break can be associated with all conditional statements.
We can also use the break statements in the nested loops. If we use the break statement in the
innermost loop, then the control of the program is terminated only from the innermost loop.
The difference between the break and exi t ( ) is provided in Table 5.1.

Table 5.1 Difference between break and ex i t ( )


Sr. No break exi t ( )
1. It is a keyword. It is a function.
2. No header file is needed. Header file process . h must be included.
3. It stops the execution of the loop. It terminates the program.

M05_KAMT3553_02_SE_C05.indd 129 5/17/2015 9:13:24 AM


130 Programming in C

5.7 THE cont inue STATEMENT


The cont inue statement is exactly opposite of the break statement. The cont inue statement is
used for continuing the next iteration of the loop statements. When it occurs in the loop, it dose not
terminate, but it skips the statements after this statement. It is useful when we want to continue the
program without executing any part of the program. Table 5.2 gives the differences between break
and cont inue.

Table 5.2 Difference between break and con t i nue


break cont inue
Exits from current block or loop. Loop takes the next iteration.
Control passes to the next statement. Control passes at the beginning of the loop.
Terminates the loop. Never terminates the program.

5.8 THE goto STATEMENT


This statement does not require any condition. This is an unconditional control jump. This statement
passes control anywhere in the program, i.e. control is transferred to another part of the program with-
out testing any condition. User has to define the goto statement as follows:
goto label ;
where, the label name must start with any character.
Here, the label is the position where the control is to be transferred. A few examples are described
for the sake of understanding.
5.14 Write a program to detect the entered number as to whether it is even or odd. Use the goto
statement.

# include <stdl ib . h>


void main( )
{
int x;
cl rscr ( ) ;
pr int f (“Enter a Number :”) ;
scanf (“%d” , &x) ;
i f (x%2==0)
goto even;
el se
goto odd;
even :
pr int f (“\n %d i s Even Number . ” , x) ;
return;
odd:
pr int f (“\n %d i s Odd Number . ” , x) ;
}
OUTPUT:
Enter a Number : 5
5 i s Odd Number .

M05_KAMT3553_02_SE_C05.indd 130 5/17/2015 9:13:24 AM


Decision Statements 131

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.

Telephone Cal l Rate in Rs .


<100 No Charges
>99 & <200 1
>199 & <300 2
>299 3

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.

M05_KAMT3553_02_SE_C05.indd 131 5/17/2015 9:13:24 AM


132 Programming in C

5.16 Write a program to check if the entered year is a leap year or not. Use the go t o
statement.

#include <s tdio . h>


#include <conio . h>
int main( )
{
int year ;
cl rscr ( ) ;
pr int f (“\nEnter Year :”) ;
scanf (“%d” , &year ) ;
i f (year%4==0 && year%100!=0 | | year%400==0)
goto leap;
el se
goto noleap;
leap:
pr int f (“%d is a leap year . ” , year ) ;
return 0;
noleap:
pr int f (“%d is not leap year . ” , year ) ;
getch( ) ;
return 0;
}
OUTPUT:
Enter Year : 2012
2012 is a leap year .

Explanation:
The entered year is divided using the modulus division operator 400. The condition is satis-
fied hence the year 2012 is the leap year.

5.9 THE swi tch STATEMENT


The swi tch statement is a multi-way branch statement. In the program, if there is a possibility to
make a choice from a number of options, this structured selection is useful. The swi tch statement
requires only one argument of any data type, which is checked with the number of case options.
The swi tch statement evaluates expression and then looks for its value among the case constants. If
the value matches with case constant, this particular case statement is executed. If not, defaul t
is executed. Here, swi tch , case and defaul t are reserved keywords. Every case statement
terminates with ‘:’. The break statement is used to exit from current case structure. The swi tch
statement is useful for writing the menu-driven program.
The syntax of the swi tch case statement is as follows.

swi tch(var iable or express ion)


{
case constant A :
s tatement ;

M05_KAMT3553_02_SE_C05.indd 132 5/17/2015 9:13:24 AM


Decision Statements 133

break;
case constant B :
s tatement ;
break;
defaul t :
s tatement ;
}

(a) The swi tch expression


In the block, the variable or expression can be a character or an integer. The integer expres-
sion following the keyword swi tch will yield an integer value only. The integer may be
any value 1, 2, 3, and so on. In case a character constant, the values may be given in the
alphabetic order such as ‘x’, ‘y’, ‘z’.
(b) The swi tch organization
The swi tch expression should not be terminated with a semi-colon and/or with any other
symbol. The entire case structure following swi tch should be enclosed with curly braces.
The keyword case is followed by a constant. Every constant terminates with a colon. Each
case statement must contain different constant values. Any number of case statements
can be provided. If the case structure contains multiple statements, they need not be enclosed
with curly braces. Here, the keywords case and break perform the job of opening and
closing curly braces, respectively.
(c) The swi tch execution
When one of the cases satisfies, the statements following it are executed. In case, there is no
match, the defau l t case is executed. The defau l t can be put anywhere in the sw i t ch
expression. The sw i t ch statement can also be written without the defau l t statement.
The break statement used in sw i t ch causes the control to go outside the sw i t ch
block. By mistake, if no break statements are given all the cases following it are executed
(see Figure 5.7).
5.17 Write a program to print lines by selecting the choice.

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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ”) ;

M05_KAMT3553_02_SE_C05.indd 133 5/17/2015 9:13:24 AM


134 Programming in C

Figure 5.7 swi tch statement

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”) ;

M05_KAMT3553_02_SE_C05.indd 134 5/17/2015 12:33:55 PM


Decision Statements 135

}
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)
{

M05_KAMT3553_02_SE_C05.indd 135 5/17/2015 9:13:25 AM


136 Programming in C

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) .

M05_KAMT3553_02_SE_C05.indd 136 5/17/2015 9:13:25 AM


Decision Statements 137

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”) ;

M05_KAMT3553_02_SE_C05.indd 137 5/17/2015 9:13:25 AM


138 Programming in C

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”) ;

M05_KAMT3553_02_SE_C05.indd 138 5/17/2015 9:13:25 AM


Decision Statements 139

}
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;

M05_KAMT3553_02_SE_C05.indd 139 5/17/2015 9:13:25 AM


140 Programming in C

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;

M05_KAMT3553_02_SE_C05.indd 140 5/17/2015 9:13:25 AM


Decision Statements 141

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;

M05_KAMT3553_02_SE_C05.indd 141 5/17/2015 9:13:25 AM


142 Programming in C

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.

M05_KAMT3553_02_SE_C05.indd 142 5/17/2015 9:13:25 AM


Decision Statements 143

5.23 Write a program to convert decimal to hexadecimal number.

# include <process . h>


void main( )
{
int x , y=30 , z;
cl rscr ( ) ;
pr int f (“\nEnter a number :”) ;
scanf (“%d” , &x) ;
pr int f (“\n Convers ion of Decimal to Hexadecimal Number \n”) ;
for ( ; ; )
{
i f (x==0)
exi t (1) ;
z=x%16;
x=x/16;
gotoxy(y- - , 5) ;
swi tch(z)
{
case 10 :
pr int f (“A”) ;
break;
case 11 :
pr int f (“%c” , ‘B’ ) ;
break;
case 12 :
pr int f (“%c” , “C”) ;
break;
case 13 :
pr int f (“D”) ;
break;
case 14 :
pr int f (“E”) ;
break;
case 15 :
pr int f (“F”) ;
break;
defaul t :
pr int f (“%d” , z) ;
}
}
}
OUTPUT:
Enter a number : 31
Conversion of Decimal to Hexadecimal Number
1F

Explanation:
In the above program, an infinite for loop is used. In the for loop, the 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.

M05_KAMT3553_02_SE_C05.indd 143 5/17/2015 9:13:25 AM


144 Programming in C

5.10 NESTED swi tch case


The C supports nested swi tch statements. The inner swi tch can be a part of an outer swi tch.
The inner and outer swi tch case constants may be the same. No conflicts arise even if they are the
same. A few examples are given below on the basis of nested swi tch statements.
5.24 Write a program to detect if the entered number is even or odd. Use nested swi tch case
statements.

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.

M05_KAMT3553_02_SE_C05.indd 144 5/17/2015 9:13:25 AM


Decision Statements 145

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.

M05_KAMT3553_02_SE_C05.indd 145 5/17/2015 9:13:25 AM


146 Programming in C

5.11 THE swi tch case AND nes ted i fs


The distinction between the swi tch case and the nested i fs is narrated in Table 5.3.

Table 5.3 Distinction between the sw i t ch case and nes t ed i fs


swi tch case nes ted i fs
The swi tch can only test for equality, i.e. only The i f can evaluate relational or logical expressions.
constant values are applicable.
No two case statements have identical constants in Same conditions may be repeated for the number of
the same swi tch. times.
Character constants are automatically converted to Character constants are automatically converted to
integers. integers.
In sw i t ch case statement nested i f can be In nested i f statement swi tch case can be used.
used.

5.26 Write a program to convert integer to character using i f condition.

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 ( ) ;

M05_KAMT3553_02_SE_C05.indd 146 5/17/2015 9:13:25 AM


Decision Statements 147

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.

M05_KAMT3553_02_SE_C05.indd 147 5/17/2015 9:13:25 AM


148 Programming in C

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

M05_KAMT3553_02_SE_C05.indd 148 5/17/2015 9:13:26 AM


Decision Statements 149

3. Each case statement in swi tch is separated by i f ( x==‘B’ )


{
(a) break case ‘d’ : pr int f (“%” ,
(b) cont inue ‘o’ ) ;
(c) exi t ( ) case ‘B’ : pr int f (“%s” ,
(d) goto “Bad”) ;
4. The keyword el se can be used with }
el se
(a) i f statement case ‘G’ :
(b) swi tch statement pr int f (“%s” , “Good”) ;
(c) do . . . whi le( ) statement defaul t : pr int f(“%s”,
(d) None of the above “Boy”) ;
}
5. What will be the output of the following }
program?
(a) Good Boy
void main( ) (b) bad boy
{ (c) boy
char x=‘H’ ;
(d) None of the above
cl rscr ( ) ;
swi tch(x) 7. What will be the output of the following program?
{
case ‘H’ : pr int f(“%c”, ‘H’) ; void main( )
case ‘E’ : pr int f(“%c”, ‘E’) ; {
case ‘L’ : pr int f(“%c”, ‘L’) ; char x=‘d’ ;
case ‘ l ’ : pr int f(“%c”, ‘L’) ; cl rscr ( ) ;
case ‘O’ : pr int f(“%c”, ‘O’) ; swi tch(x)
} {
} case ‘b’ :
put s( “0 1 001”) ;
(a) HELLO break;
(b) HELlo defaul t :
(c) H put s(“1 2 3”) ;
(d) None of the above break;
6. What will be the output of the following case ‘R’ :
program? put s(“I I I I I I”) ;
}
}
void main( )
{ (a) 123
char x=‘G’ ; (b) 0 1 001
swi tch(x) (c) I II III
{ (d) None of the above

IV What is/are the output/s of the following programs?


1. pr int f (“\n The Entered number
%d is odd” , number ) ;
void main( )
getche( ) ;
{
}
int number=7;
cl rscr ( ) ; 2.
i f (number %2==0)
pr int f (“\n The entered number void main( )
%d is even” , number ) ; {
else int b=4 , a=1 , c=2;

M05_KAMT3553_02_SE_C05.indd 149 5/17/2015 9:13:26 AM


150 Programming in C

float x1 , x2; pr int f (“%d\n” , z) ;


cl rscr ( ) ; }
i f (b*b>4*a*c) el se
{ {
x1=-b+sqr t (b*b-4*a*c) /2*a; i f (z > y)
x2=-b-sqr t (b*b-4*a*c) /2*a; pr int f (“%d\n” , z) ;
pr int f (“\n x1=% . 1f el se
x2=% . 1f” , x1 , x2) ; pr int f (“%d\n” , y) ;
} }
el se getche( ) ;
pr int f (“\n Root s are }
Imaginary”) ;
getch( ) ; 5.
} void main( )
3. {
int ini t ial=1000 , final=1300 ,
void main( ) consumed;
{ float total ;
float bs , hra , da , cv , incent ive , cl rscr ( ) ;
bonus , sale=110000 , t s ; consumed = final - ini t ial ;
cl rscr ( ) ; i f (consumed>=200)
i f (sale>=100000) total=consumed * 2 . 50;
{ el se
bs=3000; total=consumed * 1 . 50;
hra=20 * bs /100; pr int f (“Total bi l l
da=110 * bs /100; for %d uni t s i s Rs
cv=500; % . 2f” , consumed , total ) ;
incent ive=sale*10/100; getche( ) ;
bonus=500; }
}
el se 6.
{ void main( )
bs=3000;hra=20 * {
bs /100; int a=2 , b=4 , c=1 , temp;
da=110 * bs /100; cl rscr ( ) ;
cv=500; if
incent ive=sale*5/100; (a<b)
} {
t s=bs+hra+da+cv+incent ive+ i f (a<c)
bonus ; temp=a;
pr int f (“\n % . 2f” , t s) ; el se
getch( ) ; temp=c;
} }
4. el se
{
void main( ) i f (b<c)
{ temp=b;
int x=6 , y=5 , z=10; el se
cl rscr ( ) ; temp=c;
pr int f (“\nAnswer i s :”) ; }
i f (x > y) pr int f (“Answer out of three
{ numbers (%d %d %d) i s %d \n” ,
i f (x > z) a , b , c , temp) ;
pr int f (“%d\n” , x) ; getche( ) ;
el se }

M05_KAMT3553_02_SE_C05.indd 150 5/17/2015 9:13:26 AM


Decision Statements 151

V Find the bug/s in the following program/s?


1. 3.
void main( ) void main( )
{ {
int cet ; cl rscr ( ) ;
cl rscr ( ) ; i f (3>2)
pr int f(“\n Enter marks obtained pr int f(“2 is smal ler than 3”) ;
in CET examinat ion :”) ; pr int f (“and”) ;
scanf (“%d” , &cet ) ; el se
i f (ci t>120) pr int f (“3 is greater”) ;
pr int f (“\n El igible for }
admiss ion in autonomous
Ins t i tute . ”) ; 4.
getch( ) ; void main( )
} {
cl rscr ( ) ;
2. i f (3>2)
void main( ) pr int f(“2 is smal ler than 3”) ;
{ el se
cl rscr ( ) ; pr int f(“ Numbers are equal”) ;
i f (0) el se
pr int f (“Fal se”) ; pr int f (“3 is greater”) ;
else }
pr int f (“True”) ;
}

VI Attempt the following programs:


1. Write a program to check whether the blood donor (a) Scanning and hardcopy of a passport photo
is eligible or not for donating blood. The condi- Rs. 5.
tions laid down are given below. Use i f statement. (b) Scanning and hardcopies (more than 10) Rs. 3.
(a) Age should be greater than 18 years but not 5. Write a program to calculate bill of Internet brows-
more than 55 years. ing. The conditions are given below.
(b) Weight should be more than 45 kg.
(a) 1 Hour – 20 Rs.
2. Write a program to check whether the voter is eli- (b) ½ Hour – 10 Rs.
gible for voting or not. If his/her age is equal to or (c) Unlimited hours in a day – 90 Rs.
greater than 18, display message ‘Eligible’ other-
Owner should enter number of hours spent by cus-
wise ‘Non- Eligible’. Use the i f statement.
tomer.
3. Write a program to calculate bill of a job work
6. Write a program to enter a character through
done as follows. Use i f-else statement.
keyboard. Use sw i t ch case structure and print
(a) Rate of typing Rs. 3/page. appropriate message. Recognize the entered
(b) Printing of 1st copy Rs. 5/page and later character whether it is vowel, consonants or
every copy Rs. 3/page. symbol?
User should enter the number of pages and print
7. The table given below is a list of gases, liquids and
out copies he/she wants.
solids. By entering one by one substances through
4. Write a program to calculate the amount of the bill the keyboard, recognize their state (gas, liquid and
for the following jobs. solid).

M05_KAMT3553_02_SE_C05.indd 151 5/17/2015 9:13:26 AM


152 Programming in C

WATER OZONE 8. Write a program to calculate the sum of re-


mainders obtained by dividing with modular
OXYGEN PETROL division operations by 2 on 1 to 9 numbers.
IRON ICE
GOLD MERCURY

VII Answer the following questions:

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

M05_KAMT3553_02_SE_C05.indd 152 5/17/2015 9:13:26 AM


Decision Statements 153

IV What is/are the output/s of the following programs?


Q. Ans.
1. The Entered number 7 is odd
2. x1= 2.0 x2= 6.0
3. 18900.00
4. Answer is :10
5. Total bill for 300 units is Rs 750.00
6. Answer out of three numbers ( 2 4 1) is 1

V Find the bug/s in the following program/s?


Q. Ans.
1. Replace cet instead of cit in i f statement.
2. i f (0) is always false statement.
3. scope of i f block is not defined.
4. i f should not have multiple el se.

M05_KAMT3553_02_SE_C05.indd 153 5/17/2015 9:13:26 AM


CHAPTER

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

M14_KAMT3553_02_SE_C6.indd 154 5/17/2015 9:19:51 AM


Loop Control 155

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.

6.1.1 | What is a Loop?


A loop is defined as a block of statements, which are repeatedly executed for a certain number of times.
The loops are of two types.
(i) Counter-controlled repetition: This is also called the definite repetition action, because the
number of iterations to be performed is defined in advance in the program itself. The steps
for performing counter-controlled repetitions are as follows.

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).

Table 6.1 Loops in C


for wh i l e do - wh i l e
for (express ion -1; expression -1; Expression -1; do
express ion-2; whi le(expression -2) {
express ion-3) { statement ;
s tatement ; s tatement ; expression-3;
expression -3; }
} whi le(expression-2) ;

M14_KAMT3553_02_SE_C6.indd 155 5/17/2015 9:19:52 AM


156 Programming in C

Start

Start Body of
loop

Initialization True

True Test
condition?
Test Body Update the
condition? statement/s initialised value
False
False
Stop Stop

Figure 6.1 The wh i l e statement Figure 6.2 The do - wh i l e statement

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.

6.2 THE for LOOP


The for loop allows to execute a set of instructions until a certain condition is satisfied. Condition may
be predefined or open-ended. The general syntax of the for loop will be as given in Table 6.2 (see
also Figures 6.3 and 6.4).
Explanation:
The for statement contains three expressions which are separated by semi-colons. Following actions
are to be performed in the three expressions.

Table 6.2 Syntax of f o r loop


for ( ini t ial ize counter ; tes t condi t ion; re-evaluat ion
parameter )
{
s tatement1;
s tatement2;
}

M14_KAMT3553_02_SE_C6.indd 156 5/17/2015 9:19:52 AM


Loop Control 157

Increment the
Keyword
variable

for (counter=0;counter<=5;counter++)

Counter variable with Loop condition


initial value

Figure 6.3 The for loop

Expression 1

Test NO
condition? Out of the loop

YES

Statements

Expression 3

Figure 6.4 Execution of the f o r loop

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.

M14_KAMT3553_02_SE_C6.indd 157 5/17/2015 9:19:53 AM


158 Programming in C

Table 6.3 Various formats of ‘ f o r ’ Loop


Syntax Output Remarks
1 . for ( ; ; ) Infinite loop No arguments
2 . for (a=0; a<=20; ) Infinite loop ‘a’ is neither incremented nor
decremented.
3. for(a =0;a<=10; a++) Displays value from 0 to 10 ‘a’ is incremented from 0 to 10. Curly
pr int f(“%d”, a) ; braces are not necessary. Default scope of
the for loop is one statement after the
for loop.
4 . for (a =10;a>=0;a–- ) Displays value from 10 to 0 ‘a’ is decremented from 10 to 0.
pr int f (“%d” , a)

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.

M14_KAMT3553_02_SE_C6.indd 158 5/17/2015 9:19:53 AM


Loop Control 159

6.2 Display numbers from 1 to 15 using for loop. Use i ++.

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++;

M14_KAMT3553_02_SE_C6.indd 159 5/17/2015 9:19:53 AM


160 Programming in C

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 :”) ;

M14_KAMT3553_02_SE_C6.indd 160 5/17/2015 9:19:53 AM


Loop Control 161

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 ( ) ;

M14_KAMT3553_02_SE_C6.indd 161 5/17/2015 9:19:53 AM


162 Programming in C

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

M14_KAMT3553_02_SE_C6.indd 162 5/17/2015 9:19:53 AM


Loop Control 163

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.

M14_KAMT3553_02_SE_C6.indd 163 5/17/2015 9:19:53 AM


164 Programming in C

6.11 Write a program to display numbers from 1 to 9 and their square roots.

# include <math . h>


void main( )
{
int i ;
float a;
cl rscr ( ) ;
for ( i=1; i<=9; i++)
pr int f (“\n\ t %d % . 2f “ , i , a=sqr t ( i ) ) ;
getche( ) ;
}

OUTPUT:
1 1 . 00
2 1 . 41
3 1 . 73
4 2 . 00
5 2 . 24
6 2 . 45
7 2 . 65
8 2 . 83
9 3 . 00

Explanation:
In the above program, the for loop executes nine times from 1 to 9. The 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.

# include <process . h>


void main( )
{
int x;
cl rscr ( ) ;
for (x=7;x<100;x++)
{
i f (x%4==0 && x%5==4 && x%6==4)
{
pr int f (“\n Number : %d” , x) ;
}
}
getche( ) ;
}
OUTPUT:
Number : 64

M14_KAMT3553_02_SE_C6.indd 164 5/17/2015 9:19:53 AM


Loop Control 165

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 :”) ;

M14_KAMT3553_02_SE_C6.indd 165 5/17/2015 9:19:53 AM


166 Programming in C

scanf (“%d” , &n) ;


for ( j=1; j<=n;++j )
t r i_num=t r i_num+j ;
pr int f (“Tr iangular number of 5 is %d” , t r i_num) ;
}

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.

6.15 Write a program to find the sum of the following series.

/* 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

M14_KAMT3553_02_SE_C6.indd 166 5/17/2015 9:19:53 AM


Loop Control 167

Explanation:
In the above program, sum and square of sum are assumed to be zero. The first for loop
prints number from 1 to the entered number. The second for loop does sum and squares
of the numbers from 1 to the entered number. The variable ‘sum’ and ‘ssum’ are used for
displaying the final results.
6.16 Write a program to find the perfect squares from 1 to 500.

#include <math . h>


void main( )
{
int i , count , x;
float c;
cl rscr ( ) ;
pr int f (“\n\n”) ;
pr int f (“ Per fect squares f rom 1 to 500\n”) ;
count=0;
for ( i=1; i<=500; i++)
{
c=sqr t ( i ) ;
x=floor (c) ; /* For rounding up floor ( ) is used . */
i f (c==x)
{
pr int f (“\ t%5d” , i ) ;
count++;
}
}
pr int f (“\n\n Total Per fect Squares =%d\n” , count ) ;
getch( ) ;
}
OUTPUT:
Per fect squares f rom 1 to 500
1 4 9 16 25 36 49 64 81 121 144
169 196 225 256 289 324 361 400 441 484
Total Per fect Squares = 22

Explanation:
Numbers like 2, 4, 9, 25, . . . are perfect squares. In the above program a for loop is used from
1 to 500. We can use the 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) ;
{

M14_KAMT3553_02_SE_C6.indd 167 5/17/2015 9:19:53 AM


168 Programming in C

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

M14_KAMT3553_02_SE_C6.indd 168 5/17/2015 9:19:54 AM


Loop Control 169

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( ) ;
}

M14_KAMT3553_02_SE_C6.indd 169 5/17/2015 9:19:54 AM


170 Programming in C

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

M14_KAMT3553_02_SE_C6.indd 170 5/17/2015 9:19:54 AM


Loop Control 171

reports the error message ‘Type Mismatch’. The scanf() is compared with the number of
arguments entered correctly. If it is less than the given argument the program displays ‘Type
Mismatch’. The marks of the second student onwards can be entered and the results can be
observed.
6.22 Write a program to enter a character and display its position in alphabets.

# include <ctype . h>


void main( )
{
int c=1;
char i , ch;
cl rscr ( ) ;
pr int f (“Enter a character :”) ;
scanf (“%c” , &ch) ;
ch=toupper (ch) ;
for ( i=65; i<=90; i++ , c++)
i f (ch ==i )
pr int f (“\n’%c’ i s%d [s t /nd/ rd/ th] Character in Alphabet ic . ” , i , c) ;
}
OUTPUT:
Enter a character : U
‘U’ i s 21 [st / /nd/ rd/ th] Character in Alphabet ic .

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( ) ;
}

M14_KAMT3553_02_SE_C6.indd 171 5/17/2015 9:19:54 AM


172 Programming in C

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.3 NESTED for LOOPS


We can also use loop within loops. In nested for loops one or more for statements are included in
the body of the loop. In other words C allows multiple for loops in nested forms. The numbers of it-
erations in this type of structure will be equal to the number of iteration in the outer loop multiplied by
the number of iterations in the inner loop. Given below examples are based on the nested for loops.

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.

M14_KAMT3553_02_SE_C6.indd 172 5/17/2015 9:19:54 AM


Loop Control 173

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.

M14_KAMT3553_02_SE_C6.indd 173 5/17/2015 9:19:54 AM


174 Programming in C

Table 6.4 Output of program 6.27


Values of Loop Variables Output
Outer Middle Inner
1. a=1 b=1 c=1 a+b+c=3
2. a=1 b=1 c=2 a+b+c=4
Inner loop over
3. a=1 b=2 c=1 a+b+c=4
4. a=1 b=2 c=2 a+b+c=5
Inner loop over
Middle loop over
5. a=2 b=1 c=1 a+b+c=4
6. a=2 b=1 c=2 a+b+c=5
Inner loop over
7. a=2 b=2 c=1 a+b+c=5
8. a=2 b=2 c=2 a+b+c=6
Inner loop over
Middle loop over
Outer loop over

6.27 Write a program to find perfect cubes up to a given number.


/ 1, 8, 27, 64 are perfect cubes of 1, 2, 3 and 4 /.

# 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

M14_KAMT3553_02_SE_C6.indd 174 5/17/2015 9:19:54 AM


Loop Control 175

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

M14_KAMT3553_02_SE_C6.indd 175 5/17/2015 9:19:54 AM


176 Programming in C

‘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.

# include <ctype . h>


void main( )
{
int a=0 , b=0 , o=0 , i ;
char v;
cl rscr ( ) ;
pr int f (“\ tPress A or B\n”) ;
for ( i=1; i<=3; i++)
{
pr int f (“\n\nVoter no . %d” , i ) ;
pr int f (“Enter Vote :”) ;
v=getche( ) ;
v=toupper (v) ;
i f (v==‘A’ )
a++;
el se i f (v==‘B’ )
b++;
el se
o++;
}
pr int f (“\n\n Status of vote(s) \n”) ;
pr int f (“\nA secures %d vote(s) . ” , a) ;
pr int f (“\nB secures %d vote(s) . ” , b) ;
pr int f (“\nInval id votes %d . ” , o) ;
}
OUTPUT:
Press A or B
Voter no . 1 Enter Vote :A
Voter no . 2 Enter Vote :A
Voter no . 3 Enter Vote :A
Status of vote(s)
A secures 3 vote(s) .
B secures 0 vote(s) .
Inval id votes 0 .

Explanation:
In the above program, the for loop is used for the number of voters who will be voting to
either ‘A’ or ‘B’. The body of the loop is executed for three times. The voter can give his/her
choice by pressing either ‘A’ or ‘B’. Apart from these two characters, if the user enters any
other character, the vote will be invalid. The results are displayed at the output.
6.30 Write a program to simulate a digital clock.

# include <dos . h>


void main( )
{

M14_KAMT3553_02_SE_C6.indd 176 5/17/2015 9:19:54 AM


Loop Control 177

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]++;
}
}

M14_KAMT3553_02_SE_C6.indd 177 5/17/2015 9:19:54 AM


178 Programming in C

pr int f (“\occur rence of 0-9 digi ts between 1 to %d Numbers . ” , n) ;


pr int f (“\n======= = == === ====== ======= = ========\n”) ;
for ( i=0; i<10; i++)
i f (st [ i ]>0)
pr int f (“\n %d Occurs %8d Times . ” , i , s t [ i ] ) ;
getch( ) ;
}
OUTPUT:
Enter a Decimal Number : 15
Occur rence of 0-9 digi t s between 1 to 15 Numbers .
0 Occurs 1 Times .
1 Occurs 8 Times .
2 Occurs 2 Times .
3 Occurs 2 Times .
4 Occurs 2 Times .
5 Occurs 2 Times .
6 Occurs 1 Times .
7 Occurs 1 Times .
8 Occurs 1 Times .
9 Occurs 1 Times .

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)
{

M14_KAMT3553_02_SE_C6.indd 178 5/17/2015 9:19:54 AM


Loop Control 179

pr int f (“\n %2d” , s) ;


n=s;
s=0;
}
}
pr int f (“\n %2d” , s) ;
}

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)

M14_KAMT3553_02_SE_C6.indd 179 5/17/2015 9:19:54 AM


180 Programming in C

{
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! */

# include <math . h>


void main( )
{
int n , i , x , c=3 , f=1 , l ;
float sum;
cl rscr ( ) ;
pr int f (“Enter x & n :”) ;
scanf (“%d %d” , &x , &n) ;
sum=x;
for ( i=3; i<=n; i+=2)
{
f=1;
i f (c%2!=0)
{
for ( l=1; l<=i ; l++)
f=f*l ;
sum=sum-pow(x , i ) / f ;
}

M14_KAMT3553_02_SE_C6.indd 180 5/17/2015 9:19:54 AM


Loop Control 181

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! */

# include <math . h>


void main( )
{
int f=1 , l , i , x , y;
float sum;
cl rscr ( ) ;
pr int f (“Enter the value of x & y :”) ;
scanf (“%d %d” , &x , &y) ;
sum = x;
for ( i=2; i<=y; i+=2)
{
f=1;
for ( l=1; l<=i ; l++)
f=f*l ;
sum = sum + pow(x , i ) / f ;
}
pr int f (“\n Sum of Ser ies : %f” , sum) ;
getche( ) ;
}
OUTPUT:
Enter the value of x & y : 4 4
Sum of Ser ies :22 . 6666

M14_KAMT3553_02_SE_C6.indd 181 5/17/2015 9:19:54 AM


182 Programming in C

6.36 Write a program to evaluate the series given in comment.


/* 1-1/1!+2/2! -3/3! . . . n/n! */

# include <math . h>


void main( )
{
int n , i , c=3 , l ;
float sum=0 , f=1 , k;
cl rscr ( ) ;
pr int f (“Enter value of n :”) ;
scanf (“%d” , &n) ;
sum=1;
for ( i=1; i<=n; i++)
{
f=1;
i f (c%2!=0)
{
for ( l=1; l<=i ; l++)
f=f*l ;
k=i / f ;
sum=sum-k;
}
else
{
for ( l=1; l<=i ; l++)
f=f*l ;
sum=sum+( i / f ) ;
}
c++;
}
pr int f (“\nSum of ser ies Numbers :%f” , sum) ;
}
OUTPUT:
Enter value of n : 3
Sum of ser ies Numbers : 0 . 5000

6.37 Write a program to detect the Armstrong numbers in three digits from 100 to 999. If the sum
of cubes of each digits of the number is equal to the number itself, then the number is called
an Armstrong number (e.g. 153 = 13 53 33 = 153).

# include <math . h>


void main( )
{
int n , d , x;
int k , i , cube=0;
cl rscr ( ) ;
pr int f (“\n The fol lowing numbers are arms t rong numbers . ”) ;
for (k=100;k<=999;k++)
{

M14_KAMT3553_02_SE_C6.indd 182 5/17/2015 9:19:54 AM


Loop Control 183

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.

6.38 Write a program to display the stars as shown below.


*
* *
* * *
* * * *
* * * * *

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”) ;
}
}

M14_KAMT3553_02_SE_C6.indd 183 5/17/2015 9:19:54 AM


184 Programming in C

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

M14_KAMT3553_02_SE_C6.indd 184 5/17/2015 9:19:54 AM


Loop Control 185

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.

M14_KAMT3553_02_SE_C6.indd 185 5/17/2015 9:19:54 AM


186 Programming in C

6.41 Write a program to generate the pyramid structure using numerical.

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.

6.42 Write a program to convert a binary number to a decimal number.

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) ;

M14_KAMT3553_02_SE_C6.indd 186 5/17/2015 9:19:54 AM


Loop Control 187

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.

M14_KAMT3553_02_SE_C6.indd 187 5/17/2015 9:19:54 AM


188 Programming in C

6.44 Write a program to convert a binary to decimal number. Enter the binary bits by using the
for loop.

#include <process . h>


void main( )
{
int a , b , z[10] , i ;
cl rscr ( ) ;
pr int f (“\nEnter the number of bi ts : -”) ;
scanf (“%d” , &b) ;
pr int f (“\nEnter the binary bi t s: -”) ;
for ( i=0; i<b; i++)
scanf (“%d” , &z[ i ] ) ;
a=z[0] ;
for ( i=0; i<(b-1) ; i++)
{
a=a*2+z[ i+1] ;
pr int f (“\n%d” , a) ;
}
pr int f (“\nDecimal Number i s : %d” , a) ;
getche( ) ;
}
OUTPUT:
Enter the number of bi t s: - 5
Enter the binary bi t s : - 1 0 0 0 1
2
4
8
17
Decimal Number i s : 17

Explanation:
In the above program, the number of binary bits is entered. Using this number, individual bits
are entered through the keyboard. For this for loop is used. The first element of the array is
assigned to variable ‘a’. The logic used here is to multiply by 2 to the variable ‘a’ and add the
next successive bit. For this the equation a=a*2+z[ i+1] ; is used. The number of iterations
to be carried out is equal to the number of binary bits minus one. Here, five bits are initialized,
hence the number of iterations will be four.
Table 6.5 gives the truth table of logic gates AND, OR and EX-OR.
Table 6.5 Logic gates truth table of AND, OR and EX-OR
Outputs
Inputs
AND Gate OR Gate EX-OR Gate
A B C C C
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

M14_KAMT3553_02_SE_C6.indd 188 5/17/2015 9:19:54 AM


Loop Control 189

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.

M14_KAMT3553_02_SE_C6.indd 189 5/17/2015 9:19:54 AM


190 Programming in C

6.46 Write a program to verify the truth table of OR Gate.

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.

M14_KAMT3553_02_SE_C6.indd 190 5/17/2015 9:19:55 AM


Loop Control 191

6.47 Write a program to verify the truth table of EX-OR GATE.

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

M14_KAMT3553_02_SE_C6.indd 191 5/17/2015 9:19:55 AM


192 Programming in C

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.

M14_KAMT3553_02_SE_C6.indd 192 5/17/2015 9:19:55 AM


Loop Control 193

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

#define DISTINCTION 420


#define FIRST 360
#define SECOND 240
void main( )
{
int number , i , j , rol l_no , marks , total ;
cl rscr ( ) ;
pr int f (“\n Enter number of Student s :”) ;
scanf (“%d” , &number ) ;
pr int f (“\n”) ;
for ( i=1; i<=number ;++i )
{
pr int f (“Enter Rol l Number :”) ;
scanf (“%d” , &rol l_no) ;
total=0;
pr int f (“\n Enter Marks of 6 Subjects for Rol l no %d :
\n” , rol l_no) ;
for ( j=1; j<=6; j++)
{
scanf (“%d” , &marks) ;
total=total+marks;
}
pr int f (“TOTAL MARKS =%d” , total ) ;
i f ( total>= DISTINCTION)
pr int f (“\n(Di s t inct ion) \n\n”) ;
el se i f ( total>=FIRST)
pr int f (“\n(Fi rst Divi s ion) \n\n”) ;
el se i f ( total>=SECOND)
pr int f (“\n(Second Divi sion) \n\n”) ;
el se
pr int f (“\n(***Fai l****)”) ;
}
}
OUTPUT:
Enter number of Student s : 1
Enter Rol l Number : 1
Enter Marks of 6 Subject s for Rol l no 1 :
42 52 62 72 82 92
TOTAL MARKS = 402
(Fi rs t Divi sion)

M14_KAMT3553_02_SE_C6.indd 193 5/17/2015 9:19:55 AM


194 Programming in C

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.

6.4 THE whi le LOOP


Another kind of loop structure in C is the whi le loop. The whi le loop is frequently used in pro-
grams for the repeated execution of statement/s in a loop. Until a certain condition is satisfied the loop
statements are executed.
The syntax of whi le loop is

whi le( test condi t ion)


{
body of the loop
}

The test condition is indicated at the top and it tests the value of the expression before processing
the body of the loop. The test condition may be any expression. The loop statements will be executed
till the condition is true, i.e. the test condition is evaluated and if the condition is true, then the body
of the loop is executed. When the condition becomes false the execution will be out of the loop.
The execution of the loop can be followed by the following flow chart given in Figure 6.5.

Entry

Initialize

Steps of while loops areas follows.

(1) The test condition is evaluated and if it is


Test False true, the body of the loop is executed.
condition?
True (2) On execution of the body, test condition is
Stop repetitively checked and if it is true the body is
executed.
Body of
the loop (3) The process of execution of the body will be
continued till the test condition becomes true.

(4) The control is transferred out of the loop if


Update test condition fails.

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.

M14_KAMT3553_02_SE_C6.indd 194 5/17/2015 9:19:55 AM


Loop Control 195

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) ;
}

M14_KAMT3553_02_SE_C6.indd 195 5/17/2015 9:19:55 AM


196 Programming in C

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 :”) ;

M14_KAMT3553_02_SE_C6.indd 196 5/17/2015 9:19:55 AM


Loop Control 197

scanf (“%d” , &a) ;


whi le(b<=a)
{
pr int f (“ %d *” , b) ;
fact=fact*b;
b++;
}
pr int f (“ = %d” , fact ) ;
pr int f (“\n Factor ial of %d i s %d” , b-1 , fact ) ;
}
OUTPUT:
Enter the Number : 4
1 * 2 * 3 * 4 * = 24
Factor ial of 4 i s 24 .

Explanation:
The working of the above program is the same as the last one. Here, we declared and initial-
ized one more variable ‘b’ to 1. Here, we are keeping the variable ‘a’ unchanged. We
require an extra variable to count the number of loops completed by the 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––)

M14_KAMT3553_02_SE_C6.indd 197 5/17/2015 9:19:55 AM


198 Programming in C

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.

# include <math . h>


# include <process . h>
void main( )
{
long n;
int x , y=0 , p=0;
cl rscr ( ) ;
pr int f (“\n Enter a Binary Number :”) ;
scanf (“%ld” , &n) ;
whi le(n!=0)
{

M14_KAMT3553_02_SE_C6.indd 198 5/17/2015 9:19:55 AM


Loop Control 199

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.

# include <math . h>


void main( )
{
int n , i , k=0;
cl rscr ( ) ;
pr int f (“Enter a number :”) ;
scanf (“%d” , &n) ;
i=n+1;
k=k-n;
whi le( i !=k)
{
pr int f (“%3d” , abs(k) ) ;
k++;
}
}
OUTPUT:
Enter a number : 3
3 2 1 0 1 2 3

M14_KAMT3553_02_SE_C6.indd 199 5/17/2015 9:19:55 AM


200 Programming in C

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)
{

M14_KAMT3553_02_SE_C6.indd 200 5/17/2015 9:19:55 AM


Loop Control 201

scanf (“%d” , &j ) ;


i f ( j>0)
{
p++;
s=s+j ;
}
el se i f ( j<0)
{
n++;
ns=ns+j ;
}
}
pr int f (“\n Total Posi t ive Numbers : %d” , p) ;
pr int f (“\n Total Negat ive Numbers : %d” , n) ;
pr int f (“\n Sum of Pos i t ive Numbers : %d” , s) ;
pr int f (“\n Sum of Negat ive Numbers : %d” , ns) ;
}
OUTPUT:
Enter Numbers (0) Exi t :1 2 3 4 5 -5 -4 -8 0
Total Posi t ive Numbers : 5
Total Negat ive Numbers : 3
Sum of Pos i t ive Numbers : 15
Sum of Negat ive Numbers : -17

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;}

M14_KAMT3553_02_SE_C6.indd 201 5/17/2015 9:19:55 AM


202 Programming in C

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( ) ;
}

M14_KAMT3553_02_SE_C6.indd 202 5/17/2015 9:19:55 AM


Loop Control 203

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.

# include <ctype . h>


void main( )
{
s tat ic char scan[40] , cap[20] , smal l [20] , num[20] , oth[20] ;
int i=0 , c=0 , s=0 , h=0 , n=0;
cl rscr ( ) ;
put s(“Enter Text Here : \n”) ;
get s(scan) ;
whi le(scan[ i ] !=‘ \0’ )
{
i f (scan[ i ]>=48 && scan[ i ]<=57)
num[++n]=scan[ i ] ;
else
i f (scan[ i ]>=65 && scan[ i ]<=90)
cap[++c]=scan[ i ] ;
else
i f (scan[ i ]>=97 && (scan[ i ]<=122) )
smal l [++s]=scan[ i ] ;
else
oth[++h]=scan[ i ] ;
i++;
}
pr int f (“\nCapi tal Let ters : [”) ;
for ( i=0; i<20; i++)
pr int f (“%c” , cap[ i ] ) ;
pr int f (“] \nSmal l Let ters : [”) ;
for ( i=0; i<20; i++)
pr int f (“%c” , smal l [ i ] ) ;
pr int f (“] \nNumar ic Let ters : [”) ;
for ( i=0; i<20; i++)
pr int f (“%c” , num[ i ] ) ;
pr int f (“] \nOther Let ters : [”) ;
for ( i=0; i<20; i++)

M14_KAMT3553_02_SE_C6.indd 203 5/17/2015 9:19:55 AM


204 Programming in C

pr int f (“%c” , oth[ i ] ) ;


pr int f (“]”) ;
getche( ) ;
}
OUTPUT:
Enter Text Here: HAVE A NICE DAY , contact me on 51606 .
Capi tal Let ters: [HAVEANICEDAY]
Smal l Let ters : [contactmeon]
Numar ic Let ters : [28669]
Other Let ters : [ , ]

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)
{

M14_KAMT3553_02_SE_C6.indd 204 5/17/2015 9:19:55 AM


Loop Control 205

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

#include <process . h>


void main( )
{
int i=48;
cl rscr ( ) ;
pr int f (“Numbers :”) ;
whi le( i<124)
{
i f ( i<58)
pr int f (“%2c” , i ) ;
el se
{
i f ( i==58)
{
pr int f (“\nCapi tal Let ters :”) ;
i+=7;
}
i f ( i>64 && i<91)
pr int f (“%2c” , i ) ;
i f ( i==90)
{
pr int f (“\n Smal l Let ters :”) ;
i+=7;
}
i f ( i>96 && i<123)

M14_KAMT3553_02_SE_C6.indd 205 5/17/2015 9:19:55 AM


206 Programming in C

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

M14_KAMT3553_02_SE_C6.indd 206 5/17/2015 9:19:55 AM


Loop Control 207

Inner Loop (k) Completed .


Middle Loop ( j ) Completed .
Outer Loop ( i ) Completed .

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.

6.5 THE do-whi le LOOP


The syntax of do-whi le loop in C is as follows.

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.

Table 6.6 Comparison of the wh i l e and do - wh i l e loop


Sr. No. wh i l e Loop do - wh i l e Loop
1 Condition is specified at the top. Condition is mentioned at the bottom.
2 Body statement/s is/are executed Body statement/s executes even when
when condition is satisfied. the condition is false.
3 No brackets for a single statement. Brackets are essential even when a
single statement exits.
4 It is an entry-controlled loop. It is an exit-controlled 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
{

M14_KAMT3553_02_SE_C6.indd 207 5/17/2015 9:19:56 AM


208 Programming in C

pr int f (“\n This i s a program of do whi le loop . ”) ;


i++;
}
whi le( i<=5) ;
}
OUTPUT:
Thi s is a program of do whi le loop .
Thi s is a program of do whi le loop .
Thi s is a program of do whi le loop .
Thi s is a program of do whi le loop .
Thi s is a program of do whi le loop .

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

M14_KAMT3553_02_SE_C6.indd 208 5/17/2015 9:19:56 AM


Loop Control 209

Reversed Number : - 1234


Addi t ion of digi t s : - 10
Mul t ipl icat ion of digi t s : - 24

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.

/* Thi s is a program of cube of a given number */


#include “math . h”
void main( )
{
int y , x=1;
cl rscr ( ) ;
pr int f (“\n Pr int the numbers and thei r cubes”) ;
pr int f (“\n”) ;
do
{
y=pow(x , 3) ;
pr int f (“%4d %27d\n” , x , y) ;
x++;
}
whi le(x<=10) ;
}
OUTPUT:
Pr int the numbers and thei r cubes
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000

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.

M14_KAMT3553_02_SE_C6.indd 209 5/17/2015 9:19:56 AM


210 Programming in C

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)
{

M14_KAMT3553_02_SE_C6.indd 210 5/17/2015 9:19:56 AM


Loop Control 211

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.

M14_KAMT3553_02_SE_C6.indd 211 5/17/2015 9:19:56 AM


212 Programming in C

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.

6.6 THE whi le LOOP WITHIN THE do-whi le LOOP


The syntax of do-whi le with multiple whi le statement loop is as follows:
do-whi le(condi t ion)

{
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)
{

M14_KAMT3553_02_SE_C6.indd 212 5/17/2015 9:19:56 AM


Loop Control 213

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.

6.7 BOHM AND JACOPINI’S THEORY


The structured programming provides simplicity. Bohm and Jacopini showed the following three
forms of controls:
(i) sequence
(ii) selection
(iii) repetition
Sequence means statements appearing one after another. Recall that in the last chapter, we learned
that selection can be implemented using i f–else and swi tch statements. Now in this chapter, we
learned that repetition can be implemented using for , whi le and do-whi le statements. goto
instructions can be used by using if and while, for and do–whi le, i.e., C language includes i f and
other loop control structures which are equivalent to the same with goto.
All the above controls can be combined by two ways: (i) stacking and (ii) nesting. Thus, the struc-
tured programming supports simplicity.

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.

M14_KAMT3553_02_SE_C6.indd 213 5/17/2015 9:19:56 AM


214 Programming in C

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

II Match the following correct pairs given in Group A with Group B:


1 2
Group A Group B Group A Group B
Sr. No. Loop Sr. No. No. of Execution Sr. No. Loop Sr. No. No. of Execution
1 for ( ; ; ) A Loop executes 1 whi le(0) A Wrong syntax of
5 times whi le
2 for ( j=1; B Non-working lop 2 whi le(1) B Non-working
j<=5; loop
j++) 3 whi le C Infinite loop
3 for ( ; ; ); C Infinite loop (a>10);
(where a=15)

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) ;
}

M14_KAMT3553_02_SE_C6.indd 214 5/17/2015 9:19:56 AM


Loop Control 215

4. What would be the final value of ‘x’ after the (c) 3


execution of the following program? (d) None of the above
void main( )
6. What will be the final values of x and y?
{
int x=1; void main( )
cl rscr ( ) ; {
do whi le(x<=10) int x=1 , y=1;
{ cl rscr ( ) ;
x++; do whi le(x<=8)
} {
whi le(x<=5) ; x++ , y++;
pr int f (“\n x=%d” , x) ; }
} whi le(y<=5) ;
(a) x=11 pr int f (“\n x=%d y=%d” , x , y) ;
(b) x=6 }
(c) x=2 (a) x=9 y=9
(d) None of the above
(b) x=9 y=6
5. How many whi le statements are possible in the (c) x=6 y= 6
do–whi le loop? (d) None of the above
(a) 2
(b) 1

IV Attempt the following programs:

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.

M14_KAMT3553_02_SE_C6.indd 215 5/17/2015 9:19:56 AM


216 Programming in C

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.

M14_KAMT3553_02_SE_C6.indd 216 5/17/2015 9:19:56 AM


Loop Control 217

34. What would be the output of the given below (d)


programs? void main( )
{
(a) whi le( ! NULL)
void main( ) {
{ pr int f(“\n %s”,“Hel lo”) ;
whi le(0) }
{ }
pr int f (“\n Hel lo”) ; (e)
} void main( )
} {
(b) whi le(“ ”)
void main( ) {
{ pr int f(“\n %s”,“Hel lo”) ;
whi le( !0) }
{ }
pr int f (“\n Hel lo”) ;
35. What will be the output of the below given
}
program? Attempt this program with other
}
keywords and functions. List the names of
(c)
keywords and functions, which can be used as
void main( )
{ arguments in the whi le loop.
whi le( !1)
void main( )
{
{
pr int f (“\n Hel lo”) ;
whi le(main)
}
{
}
pr int f (“\n %d” , main) ;
}

V Find the bug/s in the following program/s:


1. pr int f (“%d” , ) ;
void main( ) n=n+1;
{ }
int n=1; getche( ) ;
cl rscr ( ) ; }
whi le(n<10) ;
{ 3.
pr int f (“%d” , n) ; void main( )
n=n+3; {
} int k=1;
getche( ) ; cl rscr ( ) ;
} do;
{
2. pr int f (“\n %d” , k) ;
void main( ) k=k+1;
{ }
int n; whi le(k<=5) ;
cl rscr ( ) ; getche( ) ;
pr int f (“Enter the number up }
to 8: -”) ;
scanf (“%d” , n) ; 4.
whi le(n<9) void main( )
{ {

M14_KAMT3553_02_SE_C6.indd 217 5/17/2015 9:19:56 AM


218 Programming in C

chr i=65; for ( i=1; i<=n; i++)


cl rscr ( ) ; {
do j=j*i ;
{ sum=sum+i / j ;
pr int f (“ %c” , i ) }
i=i+1; pr int f (“\n % . 2f” , sum) ;
} getche( ) ;
whi le( i<=90) ; }
getche( ) ;
} 7.
void main( )
5. {
void main( ) int i=10;
{ cl rscr ( ) ;
int num=678, sum=0, rev=0,digi t ; do
cl rscr ( ) ; {
do pr int f (“%d” , i ) ;
{ i=i -1;
digi t=num-num\10*10; }
num=num/10; whi le( i>0 | | i=5) ;
rev=rev*10+digi t ; getche( ) ;
sum=sum+digi t ; }
}
8.
whi le(num>0) ;
void main( )
pr int f (“\n %d” , rev) ;
{
pr int f (“\n”) ;
int x=7 , y=0 , z=7 , i ;
pr int f (“\n %d” , sum) ;
cl rscr ( ) ;
getche( ) ;
for ( i=0; i<=x; i++) ;
}
{
6. y=x+i*z;
pr int f (“%d” , y) ;
void main( ) }
{ getche( ) ;
int i , j=1 , n=4; }
float sum=1 . 0;
cl rscr ( ) ;

VI Answer the following questions:


1. What happens if you create a loop that never 6. What is the difference between (!0) and (!1).
ends? How whi le loop works with these values?
2. Is it possible to create a for loop that is never 7. What is the difference between (1= =! 1) and
executed? (1! =1)?
3. What is a loop? Why it is necessary in a 8. What is the difference between (! 0) and (! 0)?
program?
9. What are the values of NULL and ! NULL?
4. Is it possible to nest whi le loop within for
loops? 10. Is it possible to use multiple whi le statements
with Do statement?
5. How do you choose between whi le and for
loops? 11. Explain Bohm and Jacopini’s theory.

M14_KAMT3553_02_SE_C6.indd 218 5/17/2015 9:19:56 AM


Loop Control 219

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

II Match the following correct pairs given in Group A with Group B:

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:

Q. Ans. Q. Ans. Q. Ans. Q. Ans. Q. Ans.


1. a 2. a 3. a 4. a 5. a
6. a

V Find the bug/s in the following program/s:


Q. Ans.
1. Semi-colon at the end of whi le loop is not expected program runs with this
semi-colon, but nothing appears on screen on execution.
2. & is missing in scanf and n variable in pr int f statements.
3. Semi-colon is not expected in do.
4. chr should replace with char & semi-colon is missing in pr int f.
5. Instead of “\” division “/” is expected in digit statement.
6. (float)i/j is expected in sum statement, if correct result is required otherwise the
program gives runs but result given will be wrong.
7. i= =5 is expected.
8. Omit semi-colon from for statement if correct result is required.

M14_KAMT3553_02_SE_C6.indd 219 5/17/2015 9:19:56 AM


CHAPTER

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

M07_KAMT3553_02_SE_C07.indd 220 5/17/2015 9:26:50 AM


Data Structure: Array 221

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.

7.2 ARRAY DECLARATION


Declaration of a one-dimensional array can be done with data type first, followed by the variable name
and lastly the array size is enclosed in square brackets. Array size should be integer constant and it
must be greater than zero and data type should be valid C data type.
For example, declaration of one-dimensional array is as follows:
int a[5] ; It tells the compiler that ‘a’ is an integer type of an array and its size is five integers. The
compiler reserves 2 bytes of memory for each integer array element, i.e. 10 bytes are reserved for storing
five integers in the memory. In the same way, an array of differrant data types is declared as follows:
char ch[10] ;
float real [10] ;
long num[5] ;
When we declare a variable, for example:
int x;
the variable x is declared and the memory location of two bytes is allocated to it and later a single
value can be stored in it as shown in Figure 7.1
x=4;

M07_KAMT3553_02_SE_C07.indd 221 5/17/2015 9:26:50 AM


222 Programming in C

Every variable has a name, a value assigned to it and it


x 4 6048
is to be stored in memory location. Hence, from the above,
we can say that only one value is assigned to a variable or
stored.
The way, we declare one-dimensional array in the same
Variable Memory
way and can also declare two-dimensional array. Two- Value
name Location
dimensional array is a table that contains rows and
columns. For Example, int a[3][3]; It informs the compiler
Figure 7.1 Variable mechanisms
that ‘a’ is an integer type of an array and its size is 9 integers.
This array is a three-by-three matrix. Its details are given in
the two-dimensional array and operations.
Similarly, one can declare the multi-dimensional array as follows:
datatype arrayname[size1][size2][size3]--------[sizeN];
For example, the following array declares three-dimensional array:
int a[3][3][3];
Its details are given in this chapter under three- or multi-dimensional array title.

7.3 ARRAY INITIALIZATION


The array initialization can be done as under:
int a[5]={1 , 2 , 3 , 4 , 5};

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;

M07_KAMT3553_02_SE_C07.indd 222 5/17/2015 9:26:50 AM


Data Structure: Array 223

num[3]=2;
num[4]=5;
The initialization can be done at the compile time or dynamically at the run time. The above is an example
of compile time initialization. In the statement (2), declaration and
initialization are done at once; in such type of declaration the number
1 num[0]
of elements (five) is not necessary to mention in the square bracket [].
The compiler automatically counts the value initialized and as-
2
sumes the number of elements initialized as the array size.
In the above array, the element num[0] i.e. 1 is the lowest
4
bound and num[4] i.e. 5 is the last element. In C and C++, there
is no bound checking. Hence, the programmer has to check it
2
while accessing or storing elements. Once the array is declared,
its lowest bound cannot be changed but the upper bound can be
expanded. The array name itself is a constant pointer, and there- 5 num[4]
fore we cannot modify it. Storing elements in contiguous memory
locations can expand the upper bound. Figure 7.2 Array of integers
The array name itself is a pointer. The array num is pointer to
the first element i.e. num contains address of memory location where element 1 is stored. The address
stored in the array name is called the base address. Figure 7.2 shows the pictorial representation. To
access individual elements, the following syntax is used.
num[0] refers to the 1
num[1] refers to the 2
num[2] refers to the 4
num[3] refers to the 2
num[4] refers to the 5
Thus, an array is a collection of elements of the same data type, stored in unique and successive
memory locations.

7.4 ARRAY TERMINOLOGY


Size: Number of elements or capacity to store elements in an array is called its size. It is always
mentioned in brackets ([]).
Type: Types refer to data type. It decides which type of element is stored in the array. It also instructs
the compiler to reserve memory according to data type.
Base: The address of the first element (0th) is a base address. The array name itself stores address of
the first element.
Index: The array name is used to refer to the array element. For example, num[x], num is array
name and x is index. The value of x begins from 0 to onwards depending on the size of the array. The
index value is always an integer value.
Range: Index of an array i.e. value of x varies from lower bound to upper bound while writing or
reading elements from an array. For example, in num[100], the range of index is 0 to 99.
Word: It indicates the space required for an element. In each memory location, computer can store a
data piece. The space occupation varies from machine to machine. If the size of element is more than
word (one byte) then it occupies two successive memory locations. The variables of data type int ,
float , long need more than one byte in memory.

M07_KAMT3553_02_SE_C07.indd 223 5/17/2015 9:26:51 AM


224 Programming in C

7.5 CHARACTERISTICS OF AN ARRAY


1. The Declaration int a[5] is nothing but creation of five variables of integer types in memory.
Instead of declaring five variables for five values, the programmer can define them in an array.
2. All the elements of an array share the same name, and they are distinguished from one an-
other with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other
elements.
int a[5]={1 , 2 , 3 , 4 , 8};
If a programmer needs to replace 8 with 10, then it need not require changing all other numbers except 8.
To carry out this task, the statement a[4]=10 can be used. Here, other four elements are not disturbed.
5. Any element of an array a[ ] can be assigned/equated to another ordinary variable or array
variable of its type.
Example:
b= a[2] ;
a[2]=a[3] ;
(a) In the statement b=a [ 2 ] or vice versa, the value of a[2] is assigned to ‘b’, where ‘b’
is an integer.
(b) In the statement a[2]=a[3] or vice versa, the value of a[2] is assigned to a[3],
where both the elements are of the same array.
(c) The array elements are stored in continuous memory locations.
6. Array elements are stored in contiguous memory locations.
A program on array initialization and determination of their memory locations is given below:
7.1 Write a program to display array elements with their addresses.

int main( )
{
int num[5]={1 , 2 , 3 , 2 , 5};
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

M07_KAMT3553_02_SE_C07.indd 224 5/17/2015 9:26:51 AM


Data Structure: Array 225

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.

Num[0] Num[1] Num[2] Num[3] Num[4]

1 2 3 2 5

65516 65518 65520 65522 65524

Figure 7.3 Storage of one-dimensional array

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.

M07_KAMT3553_02_SE_C07.indd 225 5/17/2015 9:26:51 AM


226 Programming in C

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.

7.6 ONE-DIMENSIONAL ARRAY


Array elements are stored contiguously in sequence one after the other. The elements of an array are
just arranged in one-dimension. They can be shown in a row or column. Single subscript will be used
in one-dimensional array to represent its elements.
An example of initialization of an array: - int a[5] ; in this initialization of an array is done.
The type of variable is integer; its variable name is a and 5 is the size of the array.
The elements of the integer array a[5] are stored in contiguous memory locations. It is as-
sumed that the starting memory location is 2000. Each integer element requires 2 bytes. Hence, sub-
sequent element appears after the gap of two locations. Table 7.2 shows the locations of elements of
integer array.

M07_KAMT3553_02_SE_C07.indd 226 5/17/2015 9:26:51 AM


Data Structure: Array 227

Table 7.2 Integer data type and their memory locations


Element A[0] A[1] A[2] A[3] A[4]
Address 2000 2002 2004 2006 2008

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.

M07_KAMT3553_02_SE_C07.indd 227 5/17/2015 9:26:51 AM


228 Programming in C

Table 7.3 Data type and their required bytes


Data Type Memory Requirement
char 1 bytes
int 2 bytes
float 4 bytes
long 4 bytes
double 8 bytes

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

M07_KAMT3553_02_SE_C07.indd 228 5/17/2015 9:26:51 AM


Data Structure: Array 229

Table 7.4 Character array elements and their locations


Array Element No 0 1 2 3 4
Elements A R R A Y
Memory Addresses 4054 4055 4056 4057 4058

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[ ]

M07_KAMT3553_02_SE_C07.indd 229 5/17/2015 9:26:51 AM


230 Programming in C

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
=================================

M07_KAMT3553_02_SE_C07.indd 230 5/17/2015 9:26:51 AM


Data Structure: Array 231

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”) ;

M07_KAMT3553_02_SE_C07.indd 231 5/17/2015 9:26:51 AM


232 Programming in C

for ( i=0; i<=5; i++)


{
pr int f (“\n\ t \ t %d + %d = \ t%d” , num[ i ] , num1[ i ] , num[ i ]+num1[ i ] ) ;
}
}

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

M07_KAMT3553_02_SE_C07.indd 232 5/17/2015 9:26:51 AM


Data Structure: Array 233

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

M07_KAMT3553_02_SE_C07.indd 233 5/17/2015 9:26:51 AM


234 Programming in C

1st day of week i s Sunday


3rd day of week i s Tuesday
2nd day of week i s Monday
4th day of week i s Wednesday
5th day of week i s Thursday
7th day of week i s Saturday
8th i s inval id day

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.

# include <process . h>


void main( )
{
int month[12]={31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31};
int i ;
cl rscr ( ) ;

M07_KAMT3553_02_SE_C07.indd 234 5/17/2015 9:26:51 AM


Data Structure: Array 235

for ( i=0; i<=11; i++)


{
pr int f (“\n Month [%d] of a year contains %d days . ” , i+1 , month[ i ] ) ;
pr int f (“\n”) ;
}
getche( ) ;
}
OUTPUT:
Month [1] of a year contains 31 days .
Month [2] of a year contains 28 days .
Month [3] of a year contains 31 days .
Month [4] of a year contains 30 days .
Month [5] of a year contains 31 days .
Month [6] of a year contains 30 days .
Month [7] of a year contains 31 days .
Month [8] of a year contains 31 days .
Month [9] of a year contains 30 days .
Month [10] of a year contains 31 days .
Month [11] of a year contains 30 days .
Month [12] of a year contains 31 days .

Explanation:
In the above example, one-dimensional array month[12] is initialized with the number
of days of different months of a year from 1 to 12 as per their order. In 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.

# include <process . h>


void main( )
{
int month[12]={1 , 3 , 5 , 7 , 8 , 10 , 12 , 4 , 6 , 9 , 11 , 2};
int i , mn;
cl rscr ( ) ;
pr int f (“Enter Number of Month :”) ;
scanf (“%d” , &mn) ;
for ( i=0; i<=11; i++)
{
i f (mn==month[ i ] )
goto compare;
}
pr int f (“\n Inval id Month”) ;
exi t (1) ;
compare: ;

M07_KAMT3553_02_SE_C07.indd 235 5/17/2015 9:26:51 AM


236 Programming in C

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

M07_KAMT3553_02_SE_C07.indd 236 5/17/2015 9:26:51 AM


Data Structure: Array 237

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
======================================

M07_KAMT3553_02_SE_C07.indd 237 5/17/2015 9:26:51 AM


238 Programming in C

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’.

7.7 ONE-DIMENSIONAL ARRAY AND OPERATIONS


We learned how to declare, initialize and access the array elements. One-dimensional array elements
may be shown in one row. So far, the examples, we discussed is of one-dimensional array.
Example:
int num[5]; / / one dimensional array
One can perform numerous operations on elements of an array and the same are explained together
with the following programs. We will learn how to traverse, insert, delete and display elements in the