272 57 22MB
English Pages 672 Year 2012
COMPUTER PROGRAMMING
This page is intentionally left blank.
COMPUTER PROGRAMMING Second Edition
ITL Education Solutions Limited Research and Development Wing New Delhi Ashok N. Kamthane Assistant Professor Department of Electronics and Telecommunication SGGS Institute of Engineering and Technology Nanded, Maharashtra
Copyright © 2012 Dorling Kindersley (India) Pvt. Ltd Licensees of Pearson Education in South Asia No part of this eBook may be used or reproduced in any manner whatsoever without the publisher’s prior written consent. This eBook may or may not include all assets that were part of the print version. The publisher reserves the right to remove any material present in this eBook at any time. ISBN 9788131764947 eISBN 9788131776124 Head Office: A-8(A), Sector 62, Knowledge Boulevard, 7th Floor, NOIDA 201 309, India Registered Office: 11 Local Shopping Centre, Panchsheel Park, New Delhi 110 017, India
Contents Preface
ix
Acknowledgements
xii
About the Authors
xiii
PART I
FUNDAMENTALS OF COMPUTERS 1
Chapter 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8
Introduction to Computers 3 Introduction 3 Characteristics of Computers 4 Evolution of Computers 5 Computer Generations 7 Classification of Computers 10 Application of Computers 13 Basic Computer Organization 15 Number System 18 Summary 26 Exercises 27
Chapter 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8
Computer Software 29 Introduction 29 Software 30 Types of Software 30 Software Terminologies 37 Installing and Uninstalling Software 39 Software Piracy 41 Starting a Computer (Booting) 43 Software Development Steps 43 Summary 45 Exercises 45
Chapter 3 Information Technology and Internet 47 3.1 Introduction 47 3.2 Information Technology (IT) 3.3 Internet 56 Summary 73 Exercises 75
48
Chapter 4 Computer Programming and Languages 77 4.1 Introduction 77 4.2 Problem-solving Techniques 78 4.3 Program Control Structures 85 4.4 Programming Paradigms 87 4.5 Programming Languages 92 4.6 Generations of Programming Languages 92 4.7 Language Translators 99 4.8 Features of a Good Programming Language 101 Summary 103 Exercises 104 Chapter 5 Microsoft Word 107 5.1 Introduction 107 5.2 Working with Word 2000 Documents 112 5.3 Working with Text 114 5.4 Working with Tables 125 5.5 Checking Spelling and Grammar 134 5.6 Adding Graphics to Document 138 5.7 Mail Merge 146 5.8 Printing a Document 154 5.9 Advanced Features of Microsoft Word 157 Important Keyboard Shortcuts 162 Summary 164 Exercises 165 Chapter 6 Microsoft Excel 169 6.1 Introduction 169 6.2 Working with Excel 2000 Workbook 172 6.3 Working with Worksheet 174 6.4 Formulas and Functions 187 6.5 Inserting Charts 194 6.6 Sorting 200
vi
Contents 6.7
Object Linking and Embedding 202 6.8 Importing and Exporting Data 206 6.9 Inserting PivotTable 208 6.10 Printing in Excel 212 6.11 Advanced Features of Microsoft Excel 216 Important Keyboard Shortcuts 221 Summary 223 Exercises 223 Chapter 7 7.1 7.2 7.3 7.4 7.5
PART II
Microsoft PowerPoint 225 Introduction 225 Working with PowerPoint 2000 228 Working with Different Views 233 Designing Presentation 235 Printing in PowerPoint 252 Summary 254 Exercises 255 PROGRAMMING WITH C
The C Declarations 269 Introduction 269 C Character Set 270 Delimiters 271 C Keywords 271 Identifiers 272 Constants 273 Variables 275 Rules for Defining Variables Data Types 276 Declaring Variables 278
Initializing Variables 278 Dynamic Initialization 281 Type Conversion 281 Constant and Volatile Variables Summary 284 Exercises 284
282
Chapter 10 Operators and Expressions 291 10.1 Introduction 291 10.2 Properties of Operators 292 10.3 Priority of Operators and their Clubbing 293 10.4 Comma and Conditional Operator 296 10.5 Arithmetic Operators 297 10.6 Relational Operators 300 10.7 Logical Operators 303 10.8 Bitwise Operators 304 Summary 310 Exercises 310
257
Chapter 8 Introduction to C 259 8.1 Introduction 259 8.2 Overview of Compilers and Interpreters 260 8.3 Structure of a C Program 260 8.4 Programming Rules 261 8.5 Executing the Program 262 8.6 Flow Chart for the Execution of a C Program 262 Summary 265 Exercises 266 Chapter 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10
9.11 9.12 9.13 9.14
275
Chapter 11 Input and Output in C 317 11.1 Introduction 317 11.2 Input and Output Functions 318 11.3 Formatted Functions 319 11.4 Flags, Width, and Precision with the Format String 324 11.5 Unformatted Functions 328 11.6 Commonly used Library Functions 334 Summary 335 Exercises 335 Chapter 12 Decision Statements 341 12.1 Introduction 341 12.2 The if Statement 342 12.3 The if-else Statement 345 12.4 Nested if-else Statement 348 12.5 The goto Statement 353 12.6 The switch() Statement 355 12.7 Nested switch() case 362 12.8 The switch() case and Nested if 364 Summary 365 Exercises 365
vii
Contents Chapter 13 Loop Control Statements 373 13.1 Introduction 373 13.2 The for Loop 374 13.3 Nested for Loops 383 13.4 The while Loop 390 13.5 The do-while Loop 397 13.6 The do-while Statement with while Loop 401 13.7 The break Statement 402 13.8 The continue Statement 403 Summary 404 Exercises 405 PART III
FUNCTIONS, ARRAYS, AND STRINGS 413
Chapter 14 Functions 415 14.1 Introduction 415 14.2 Definition of Function 416 14.3 Definition Syntax Function and Function Protoypes 417 14.4 The return Statement 421 14.5 Types of Functions 422 14.6 Call by Value and Reference 428 14.7 Function Returning More Values 430 14.8 Function as an Argument 431 14.9 Function with Operators 433 14.10 Function and Decision Statements 438 14.11 Function and Loop Statements 440 14.12 Functions with Arrays and Pointers 443 14.13 Recursion 450 14.14 Pointer to Function 451 Summary 453 Exercises 454 Chapter 15 Storage Class 467 15.1 Introduction 467 15.2 Automatic Variables 468 15.3 External Variables 469 15.4 Static Variables 471 15.5 Register Variables 472 Summary 473 Exercises 474
Chapter 16 Arrays 481 16.1 Introduction 481 16.2 Array Initialization 482 16.3 Definition of Array 483 16.4 Characteristics of Array 483 16.5 One-dimensional Array 483 16.6 Predefined Streams 489 16.7 Two-dimensional Array 491 16.8 Three or Multi-dimensional Arrays 495 16.9 The sscanf() and sprintf() Functions 497 16.10 Operation with Arrays 500 Summary 508 Exercises 508 Chapter 17 17.1 17.2 17.3 17.4
Working with Strings and Standard Functions 519 Introduction 519 Declaration and Initialization of String 520 Display of Strings with Different Formats 522 String Standard Functions 524 Summary 541 Exercises 541
Chapter 18 Preprocessor Directives 551 18.1 Introduction 551 18.2 The #define Directive 552 18.3 Undefining a Macro 553 18.4 Token Pasting and Stringising Operators 554 18.5 The #include Directive 555 18.6 Conditional Compilation 556 18.7 The #ifndef Directive 557 18.8 The #error Directive 558 18.9 The #line Directive 559 18.10 The inline Directive 559 18.11 The #pragma Saveregs 559 18.12 The #pragma Directive 559 18.13 The Predefined Macros in ANSI and Turbo-C 561 18.14 Standard I/O Predefined Streams in stdio.h 564 18.15 The Predefined Marcos in ctype.h 565
viii
Contents
18.16 Assertions 567 Summary 567 Exercises 568 PART IV
POINTERS AND STRUCTURES UNIONS 579
Chapter 19 Pointers 581 19.1 Introduction 581 19.2 Features of Pointers 582 19.3 Pointer Declaration 582 19.4 Arithmetic Operations with Pointers 586 19.5 Pointers and Arrays 588 19.6 Pointers and Two-dimensional Arrays 590 19.7 Array of Pointers 591 19.8 Functions and Pointers 592 19.9 Pointer to Pointer 594 19.10 Pointers and Strings 595 19.11 Void Pointers 597 Summary 598 Exercises 599 Chapter 20 Dynamic Memory Allocation 609 20.1 Dynamic Memory Allocation 609 20.2 Memory Models 610
20.3
Memory Allocation Functions Summary 614 Exercises 615
610
Chapter 21 Structure and union 617 21.1 Introduction 617 21.2 Features of Structures 618 21.3 Definition, Declaration, and Initialization of Structure 618 21.4 Structure within Structure 620 21.5 Array of Structures 622 21.6 Pointer to Structure 624 21.7 Structure and Functions 625 21.8 typedef 626 21.9 Bit Fields 627 21.10 Enumerated Data Type 629 21.11 union 631 21.12 Calling BIOS and DOS Services 632 21.13 union of Structures 636 Summary 637 Exercises 637 Appendix A: American Standard Code for Information Interchange 649 Index
653
Preface The world today is witnessing a new kind of revolution—the Information Revolution—ushered in by technology. This revolution is in fact far more sweeping than any other revolution in history in its reach and influence, bringing fundamental changes in all aspects of our life. Information technology (IT) is the engine used to drive useful information systems. This includes computers, software, the Internet/Intranet, and telecommunication systems. IT provides the means for collecting, storing, encoding, processing, analyzing, transmitting, receiving, and printing information. An indispensable text for teaching and learning C, Computer Programming is a rich collection of the basics of computer and C programs. Theoretical concepts are supplemented by numerous numbers of programs that lead trainers/students to understand the concepts better. This is a second edition book wherein a reader finds many more additional chapters/points/programs than the previous edition. The revised book certainly helps the programmer to become an expert in C Language provided they write and execute a few programs every day for one or other applications. After all there is tremendous demand for software professionals who write C programs neatly and efficiently in this competitive world. Programs presented in this revised book are designed for use by students in their first course on computer programming at the undergraduate and postgraduate levels. Beginners who wish to learn the basics of computer science programming in C would find it most useful. This book would be helpful to all the students enrolled in various courses, for example, BE, BCS, BCA, MCA, MCS, B.Sc., M.Sc., MSCIT, DOEACC, and private institutes, which have C programming language as a part of the course. Chapter 1 provides an overview of the history of computers and basic digital computer concepts. It also explores the classification of computers and their features. The chapter concludes with an overview on basic computer units, computer applications, and the number system. The essentials of computer software are introduced in Chapter 2. It continues with the type of software, namely system software and application software, their roles along with the hardware in building up a fully functional computer system. In the latter part of the chapter, piracy and techniques of its prevention are explained. Chapter 3 introduces the reader to IT and its impact on various areas such as business, education, defence, etc. It also discusses the evolution of the Internet and terms associated with it. This chapter also highlights various Internet applications and its languages. Chapter 4 essentially deals with programming and various programming tools such as algorithms, flow charts, and pseudocodes. The chapter explains the evolution of various programming languages and generations of programming languages. It also presents the working of language translators, namely assemblers, compilers, and interpreters. Chapter 5 provides a foundation to harness the power of word processing using Microsoft Word 2000. The chapter covers various tools and features such as bullets and numbering, headers and footers, spelling and grammar checking, tables, and many more through which text document can be enhanced. Chapter 6 provides a base for the reader to harness the power of a spreadsheet program using Microsoft Excel 2000. The chapter covers various tools and features such as formulas and functions, inserting charts, formatting cells, etc., which help in creating worksheets quickly and efficiently. Chapter 7 provides a foundation for the reader to harness the power of creating presentations using Microsoft PowerPoint 2000. The chapter covers various tools and features such as animation effects, transition effects, etc. through which a presentation can be greatly enhanced.
x
Preface
Chapter 8 gives an overview of the C language after providing the reader with its brief history. The role of the interpreter and compiler is narrated in this chapter. The structure of a C program and programming rules of C are presented and various sections of the C program and their meanings are explained. A flow chart that is needed to execute the program is also discussed in this chapter. The fundamentals of C are explained in Chapter 9. The reader is introduced to alphanumerical codes supported by C. Different data types like digits, characters, floating point numbers besides white space, and special characters supported by C are discussed in this chapter Valid and invalid constants of C are also discussed. Rules for defining the variables and initialization of a variable are described. Dynamic initializations, constant and volatile variables, type conversion, etc. are discussed in this chapter. Chapter 10 covers arithmetic, logical, and relational operators, which are essential for the writing and execution of C programs. The properties and precedence of the operators in arithmetic operations are explained. The conditional and comma operators and programs based on them are described in this chapter. The use of OR, AND, XOR, and NOT operators are explained. Using bitwise operators, programs are developed. Chapter 11 deals with input and output statements of C. This chapter explains formatted functions such as printf() and scanf() together with flags, width, and precision. The unformatted functions such as putchar(), getche(), gets(), and cgets() are described together with programming examples. Special symbols such as escape sequences, and their applications, are also discussed. A few library functions such as clrscr() and exit() that are commonly used in programs are described in this chapter. Decision-making statements are dealt with in Chapter 12. The if, if-else statements with flow charts and programs that use them are explained in this chapter. Also, the multi-way decision-making statement switch() case is discussed. How nested if-else and switch() case statements are to be used in programs are also illustrated in a simple and easy way. The keywords break, continue, and goto are exposed to the reader in this chapter. Chapter 13 deals with the control loop statements that are used in C programs. The scope of loops such as for, while, and do-while is discussed. The technique of breaking the loop and continuing the loop using keywords break and continue, respectively, is also elaborated. Chapter 14 introduces functions. Function definition, passing actual arguments, formal arguments, and return statements are described. Function as an argument, function with operators, function and loop statements, etc. are explained with programs. Recursive functions are explained with numerous examples. Chapter 15 deals with storage class and covers auto, static, register, and extern classes along with relevant programs. Chapter 16 deals with characteristics of an array. How one-, two-, and multi-dimensional arrays work using C with numerous programming examples are presented in this chapter. Various operations with arrays such as insertion, deletion of an element, and searching for an element in an array are discussed. Pointers and arrays are also presented in this chapter. The predefined stream concept is explained at the end of the one-dimensional array in this chapter. Chapter 17 focuses on strings and standard functions supported by the C library. String-handling problems such as the conversion of string from lower to upper case, concatenation of strings, searching for a character, comparing two strings, and reversing string elements are discussed in length with programs. Chapter 18 explains preprocessor directives used in C. This chapter covers directives such as #define, #undef, #include, etc. The Stringising operation, the manner of how a macro argument is converted to a string, is described. Conditional compilation directives such as #ifdef, #else, #endif, etc. are also explained with programs. The other directives covered in this chapter are #error and #pragma. The reader is further exposed to predefined macors in ctype.h. Chapter 19 covers pointers, its features, and uses in programs. The topics cover declaration of pointers, how to access variables with pointers, operations with pointers, arithmetic operations on pointers, pointers
Preface
xi
to pointers, pointers and arrays, pointers and functions, chain of pointers, void pointers, and association of pointers with strings. How to use memory for the storage of data is discussed in Chapter 20. Various memory models are discussed in this chapter. Dynamic memory allocation and release of memory functions have been elucidated here. Various functions such as malloc(), calloc(), realloc(), free(), and coreleft() are covered in this chapter. Chapter 21 deals with the concept of structure and union. Various topics under structure such as declaration and initialization of structures, structure within the structure, array of structures, and pointer to structure are elaborated. The typedef facility can be used for creating user-defined data types and is illustrated with many programming examples. The DOS and ROM-BIOS functions and their applications are explained. Hope you enjoy reading this book as much as we have enjoyed writing it.
Feedback For any suggestions and comments about this book, please send your feedback to [email protected] and [email protected]. Rohit Khurana Ashok N. Kamthane
Acknowledgements I wish to thank the entire research and development team who have put in their earnest efforts and relentless perseverance to bring out a high-quality book. I also thank our technical and editorial consultants for devoting their precious time to improve the quality of the book. I thank the editorial team at Pearson Education and the panel reviewers for their valuable contribution towards the enrichment of content. Rohit Khurana I express my sincere gratitude towards my beloved father, Late Sri. Namdev Kamthane; my grandfather, Late Sri. Jagganath Kamthane; and my mother, Late Smt. Sumanbai Namdev Kamthane. It is because of their blessings that I could write this book in addition to several other technical books. I am indebted to Mr S. Ramamurthi, president of Subhram Trust, Bangalore, for presenting me with the Samaj Seva Bhushan Award 2004 for technical book writing, and I take pride in the felicitation and honor bestowed on me. I am grateful for the encouragement and support extended by the members of the trust on the occasion of their silver jubilee celebrations. I am grateful to the members of the Board of Governors of our institute for encouraging and inspiring me to write this book, and I thank the chairman, Mr Baba N. Kalyani, and the director, Dr S. R. Kajale. Other board members, Dr S. K. Mahajan, Director of Technical Education, Maharashtra State, Dr K. G. Narayankhedkar, Director, VJTI Mumbai, Vijay Ghate, Kamlesh Pande, J. S. Sahariya Principal Secretary Higher Education, Government of Maharashtra, Kantilal Umap Deputy secretary, Higher education, Sardar Inpinder Singh, and Dr V. P. Dimri, extended their good wishes. I am obliged to all my colleagues, friends, and students who extended moral support. Among them are Dr S. V. Bonde, Dr D. D. Doye, Dr S. N. Talbar, Dr S. G. Kahalekar, Dr P. D. Jadhav, Dr P. Pramanik, Dr M. L. Waikar, Dr B. M. Dabde, Dr U. V. Kulkarni, Dr V. M. Nandedkar, Dr R. S. Holambe, Dr B. M. Patre, Prof. R. K. Chavan, Dr J. V. L. Venkatesh, Ms S. S. Kandhare, Prof. P. S. Nalawade, Prof. S. S. Hatkar, Dr R. C. Thool, Prof. A. V. Nandedkar, Dr P. B. Londhe, Dr R. R. Manthalkar, Prof. N. G. Megde, Dr A. S. Sontakke, Prof. Deepak Bacchewar, Dr L. M. Waghmare, Dr R. H. Chille, Prof. Asutkar, and Prof. A. I. Tamboli. All of them were a great source of help and encouragement while writing this book. I also thank my friends Prof. S. L. Kotgire and Prof. Balaji Bacchewar for their help. M. M. Jahagirdar, R. M. Medabalmewar, Bhatambre, Kishan Buddhewar, L. M. Buddhewar, D. V. Deshpande, S. R. Kokne, M. G. Damkondawar, R. D. Yeramwar, S. R. Tumma, S. R. Mana, G. M. Kamthekar, and Halle were helpful during the writing of this book. I am also thankful to Mr Deepesh Raghuwanshi and Mr Prashant Mahajan for proofreading the text of this book. I thank all the students, faculty, and non-teaching staff of this college who either directly or indirectly helped me to complete this book. I take this opportunity to thank the editorial and the production editorial teams at Pearson Education, especially Thomas Mathew Rajesh, Sojan Jose, S. Shankari, M. E. Sethurajan, and Jennifer Sargunar for their painstaking work in bringing out this book in record time. Thanks are also due to my wife Surekha who supported me patiently during the preparation of this book. Last, but not the least, my sons, Amol and Amit; daughter, Sangita; and daughter-in-law, Swaroopa, were also of great help and supported me at all times. I thank them all. Ashok N. Kamthane
About the Authors Rohit Khurana is the founder and CEO of ITL Education Solutions Limited (ITL ESL). He has over 15 years of experience in training, research, content development, consultancy and management. ITL ESL is a part of the ITL group, which has operations all over the world with a significant presence in the field of computer education and IT-enabled services. It specializes in handling implementation projects in various IT domains with a dedicated R&D wing of industry experts, who help in designing and developing content.
Ashok Namdev Kamthane is a postgraduate in electronics from Shri Guru Gobind Singhiji college of Engineering and Technology, Nanded. An eminent academician, he has won a number of prizes for his contribution to Information Technology including the Samaja Seva Bhushan Award from Ramamurthy Subhram Trust, Bangalore. The author has been associated with the development of hardware and software using 8051 (8-bit microcontroller) on Acoustic Transceiver System required in submarines. He has also worked at Merton as an executive. He is a faculty at the Electronics and Telecommunication Engineering department at SGGS Engineering and Technology, Nanded, and his teaching career has spanned 27 years. Currently, he is an assistant professor, where he teaches computer language subjects such as C, C++, Data Structures, Wireless Communication, and Microprocessors and their applications. He has guided a number of undergraduate and postgraduate students and has published several technical papers of national and international repute.
Part I Fundamentals of Computers
01-Computer_Program-01.indd 1
5/28/2010 5:19:44 AM
This page is intentionally left blank.
01-Computer_Program-01.indd 2
5/28/2010 5:19:45 AM
Chapter
1
Introduction to Computers CHA PT E R O U T LIN E 1.1
Introduction
1.5
Classification of Computers
1.2
Characteristics of Computers
1.6
Application of Computers
1.3
Evolution of Computers
1.7
Basic Computer Organization
1.4
Computer Generations
1.8
Number System
1.1 INTRODUCTION At the beginning of civilization, people used fingers and pebbles for computing purposes. In fact, the word digitus in Latin actually means finger and calculus means pebble. This gives us a clue to the origin of early computing concepts. With the development of civilization, computing needs also grew. The need for a mechanism to perform lengthy calculations led to the invention of the calculator first and then computers. The term computer is derived from the word compute, which means to calculate. A computer is an electronic machine used for performing calculations and controlling operations that can be expressed either in logical or numerical terms. In simple words, a computer is an electronic device that performs diverse operations using instructions to process the information in order to achieve the desired results. Although the application domain of a computer depends totally on human creativity and imagination, it covers a huge area of applications including education, industries, government, medicine, scientific research, law, and even music and arts.
01-Computer_Program-01.indd 3
5/28/2010 5:19:45 AM
4
Computer Programming
Computers are one of the most influential computing devices available in modern times. Harnessing the power of computers compensates for relatively limited and fallible human capacities with regard to memory, logical decision-making, reaction, and perfection to be extended to almost infinite levels. Millions of complex calculations can be done in a fraction of time and difficult decisions can be made with unerring accuracy at comparatively little cost. Computers are widely seen as a device for future progress and as a tool to achieve sustainability by way of improved access to information, for example, through video conferencing and e-mail. Indeed, computers have left an indelible mark on modern civilization that we call this era as the “information age.”
1.2
CHARACTERISTICS OF COMPUTERS
The human race developed computers so that they could perform intricate operations, such as calculation and data processing, or simply for entertainment. Today, much of the world’s infrastructure depends on computers and it has profoundly changed our lives, mostly for the better. Let us discuss some of the characteristics of computers, which make them an essential part of every emerging technology and a desirable tool in human development. • Speed: Computers process data at an extremely fast rate—millions of instructions per second. In a few seconds, a computer can perform a complex task that a normal human being may take days or even years to complete. The speed of a computer is calculated in megahertz (MHz), that is, 1 million instructions per second. At present, a powerful computer can perform billions of operations in just 1 second. • Accuracy: Besides efficiency, computers are accurate as well. The level of accuracy depends on the instructions and the type of machine being used. Since a computer is capable of doing only what it is instructed to do, faulty instructions for data processing may lead to faulty results. This is known as Garbage In Garbage Out (GIGO). • Diligence: A computer, being a machine, does not suffer from the human traits of tiredness and lack of concentration. If 4 million calculations have to be performed, then the computer will perform the last fourmillionth calculation with the same accuracy and speed as the first calculation. • Reliability: Generally, reliability is the measurement of performance of a computer, which is measured against some predetermined standard for operation without any failure. The major reason for reliability of the computers is that, at the hardware level, it does not require any human intervention between its processing operations. Moreover, computers have built-in diagnostic capabilities, which help in continuous monitoring of the system. • Storage Capability: Computers can store large amounts of data and can recall the required information almost instantaneously. The main memory of the computer is relatively small and it can hold only a certain amount of information; therefore, the data are stored on secondary storage devices, such as magnetic tapes or disks. Small sections of the data can be accessed very quickly and brought into the storage devices as and when required for processing. • Versatility: Computers are quite versatile in nature. They can perform multiple tasks simultaneously with great ease. For example, at one moment, they can be used to draft a letter, another moment they can be used to play music and in between, they can be used to print a document as well. All this work is possible by changing the program (computer instructions). • Resource Sharing: In the initial stages of development, computers used to be isolated machines. With the tremendous growth in computer technologies, computers today have the capability to connect with each other. This has made the sharing of costly resources like printers possible. Apart from device sharing, data and information can also be shared among groups of computers, thus creating a large information and knowledge base.
01-Computer_Program-01.indd 4
5/28/2010 5:19:45 AM
Introduction to Computers
5
Although processing has become less tedious with the development of computers, it is still a timeconsuming and expensive job. Also, computer parts require regular check-ups and maintenance to give correct results. Furthermore, computers need to be installed in a dust-free place. Generally, some parts of computers get heated up due to heavy processing. Therefore, the ambient temperature of the computer system should be maintained.
1.3
EVOLUTION OF COMPUTERS
The need for a device to perform calculations along with growth in commerce and other human activities explain the evolution of computers. Having the right tool to perform these tasks has always been important for human beings. In their quest to develop efficient computing devices, many apparatuses were developed. However, many centuries elapsed before technology was adequately advanced to develop computers. In the beginning, when the task was simply counting or adding, people used either their fingers or pebbles along lines in the sand. In order to simplify the process of counting, people in Asia Minor built a counting device called the abacus. This device allowed users to perform calculations using a system of sliding beads arranged on a rack. The abacus (Fig. 1.1) was simple to operate and was used worldwide for centuries. In fact, it is still used in many countries even today. With the passage of time, many computing devices, such as Napier’s bones and the slide rule were invented. It took many Figure 1.1 Abacus centuries, however, for the next significant advancement in computing devices. In 1642, a French mathematician, Blaise Pascal, invented the first functional automatic calculator. This brass rectangular box, also called a pascaline (Fig. 1.2), used eight movable dials to add sums up to a length of eight figures. In 1694, German mathematician Gottfried Wilhem von Leibniz extended the Pascal’s design to perform multiplication, division, and to find the square root. This Figure 1.2 Pascaline machine is known as the stepped reckoner. It was the first mass-produced calculating device, which was designed to perform multiplication by repeated addition. Like its predecessor, FACT FILE Leibniz’s mechanical multiplier worked through a system of gears What’s in the Name? and dials. The only problem with this device was that it lacked mechanical precision in its construction and was not reliable. In 1896, Hollerith founded the TabulatThe real beginnings of computers as we know them today, ing Machine Company, which was later however, lay with an English mathematics professor, Charles named International Business Machines Babbage. In 1822, he proposed a machine to perform differen(IBM). IBM developed numerous tial equations, called a difference engine. Powered by steam and mainframes and operating systems, as large as a locomotive, the machine had a stored program and many of which are still in use today. For could perform calculations and print the results automatically. example, IBM co-developed OS/2 with However, Babbage never quite made a fully functional difference Microsoft, which laid the foundation engine, and in 1833, he quit working on this machine to confor Windows operating systems. centrate on the analytical engine. The basic design of this engine
01-Computer_Program-01.indd 5
5/28/2010 5:19:45 AM
6
Computer Programming
included input devices in the form of perforated cards containing operating instructions and a “store” for a memory of 1,000 numbers of up to 50 decimal digits long. It also contained a control unit (CU) that allowed processing instructions in any sequence and output devices to produce printed results. Babbage borrowed the idea of punch cards to encode the instructions in the machine from the Joseph-Marie Jacquard’s loom. Although the analytical engine was never constructed, it outlined the basic elements of a modern computer. In 1889, Herman Hollerith, who worked for the U.S. Census Bureau, also applied the Jacquard loom concept to computing. Unlike Babbage’s idea of using perforated cards to instruct the machine, Hollerith’s method used cards to store data, which he fed into a machine that compiled the results mechanically (Fig. 1.3). The start of World War II produced a substantial need for computer capacity, especially for the military purposes. One early success was the Mark I, which was built as a partnership between Harvard Aiken and IBM in 1944. This electronic calculating machine used relays and electromagnetic components to replace mechanical components. In 1946, John Eckert and John Mauchly of the Moore School of Engineering at the University of Pennsylvania developed the Electronic Numerical Integrator and Calculator (ENIAC). This computer used electronic vacuum tubes to make the internal parts of the computer. Figure 1.3 Hollerith It embodied almost all the components and concepts of today’s high-speed, Tabulator electronic digital computers. Later on, Eckert and Mauchly also proposed the development of the Electronic Discrete Variable Automatic Computer (EDVAC). It was the first electronic computer to use the concept of a stored program introduced by John von Neumann. It also had the capability of conditional transfer of control, that is, the computer could stop any time and then resume operations. In 1949, at the Cambridge University, a team headed by Maurice Wilkes developed the Electronic Delay Storage Automatic Calculator (EDSAC), which was also based on John von Neumann’s stored program concept. This machine used mercury delay lines for memory and vacuum tubes for logic. The Eckert–Mauchly Corporation manufactured the Universal Automatic Computer (UNIVAC) in 1951, and its implementation marked the real beginning of the computer era. In the 1960s, efforts to design and develop the fastest possible computer with the greatest capacity reached a turning point with the LARC machine, which had an access time of less then 1 microsecond and a total capacity of 100,000,000 words. During this period, the major computer manufacturers began to offer a range of capabilities and prices, as well as accessories, such as card feeders, page printers, and cathode ray tube displays. During the 1970s, the trend shifted towards a larger range of applications for cheaper computer systems. During this period, many business organizations adopted computers for their offices. The vacuum deposition of transistors became the norm, and entire computer assemblies became available on tiny “chips” known as Integrated Circuits (IC). This led to the development of microprocessors, processors on a single IC chip. In the 1980s, Very Large-Scale Integration (VLSI) designs, in which hundreds of thousands of transistors were placed on a single chip, became increasingly common. The “shrinking” trend continued with the introduction of personal computers (PCs), which are programmable machines small enough and inexpensive enough to be purchased and used by individuals. Microprocessors equipped with read-only memory (ROM), which stores constantly used, unchanging programs, performed an increased number of functions. By the late 1980s, some PCs were run by microprocessors, handling 32 bits of data at a time, and could process about 4,000,000 instructions per second. By the 1990s, PCs have become part of everyday life. The trend continued leading to the development of smaller and smaller microprocessors with a proportionate increase in processing powers. The computer technology continues to experience huge growth. Computer networking, e-mail, and e-publishing are just a few of the applications that have grown in recent years. Advances in technologies
01-Computer_Program-01.indd 6
5/28/2010 5:19:46 AM
7
Introduction to Computers
continue to produce cheaper and more powerful computers, offering the promise that in the near future, computers or terminals will reside in most, if not all, homes, offices, and schools.
1.4
COMPUTER GENERATIONS
The history of computer development is often discussed with reference to the different generations of computing devices. In computer terminology, the word generation is described as a stage of technological development or innovation. A major technological development that fundamentally changed the way computers operate, resulting in increasingly smaller, cheaper, more powerful, and more efficient and reliable devices, characterizes each generation of computer. According to the technology used, there are five generations of computers that are discussed in the following sections.
1.4.1 First Generation (1940–1956): Vacuum Tubes First generation computers were vacuum tubes/thermionic valve-based machines (Fig. 1.4). These computers used vacuum tubes for circuitry and magnetic drums for memory. A magnetic drum is a metal cylinder coated with magnetic iron-oxide material on which data and programs can be stored. Input was based on punched cards and paper tape, and output was displayed in the form of printouts. First generation computers relied on binary-coded language (language of ‘0’s and ‘1’s) to perform operations and were able to solve only one problem at a time. Each machine was fed with different binary codes and hence were difficult to program. This resulted in lack of versatility and speed. In addition, to run on different types of computers, instructions must be rewritten or recompiled. For example: ENIAC, EDVAC, and UNIVAC.
Figure 1.4 Vacuum Tube
Characteristics of First Generation Computers • These computers were based on vacuum tube technology. • These were the fastest computing devices of their times (computation time was in milliseconds). • These computers were very large and required a lot of space for installation. • Since thousands of vacuum tubes were used, they generated a large amount of heat. Therefore, air conditioning was essential. • These were non-portable and very slow equipments. • They lacked in versatility and speed. • They were very expensive to operate and used a large amount of electricity. • These machines were unreliable and prone to frequent hardware failures. Hence, constant maintenance was required. • Since machine language was used, these computers were difficult to program and use. • Each individual component had to be assembled manually. Hence, commercial appeal of these computers was poor.
1.4.2 Second Generation (1956–1963): Transistors Second generation computers used transistors, which were superior to vacuum tubes. A transistor is made up of semiconductor material like germanium and silicon. It usually had three leads (Fig. 1.5) and
01-Computer_Program-01.indd 7
5/28/2010 5:19:46 AM
8
Computer Programming
performed electrical functions, such as voltage, current, or power amplification with low power requirements. Since the transistor is a small device, the physical size of computers was greatly reduced. Computers became smaller, faster, cheaper, energy-efficient, and more reliable than their predecessors. In second generation computers, magnetic cores were used as primary memory and magnetic disks as secondary storage devices. However, they still relied on punched cards for input and printouts for output. One of the major developments of this generation includes the progress from machine language to assembly language. Assembly language used mnemonics (abbreviations) for instructions rather than numbers, for example, ADD for addition and MULT for multiplication. As a result, programming became less cumbersome. Early high-level programming languages, such as COBOL and FORTRAN also came into existence in this period. For example: PDP-8, IBM 1401, and IBM 7090. Figure 1.5
Characteristics of Second Generation Computers Transistor • These machines were based on the transistor technology. • These were smaller when compared to the first generation computers. • The computational time of these computers was reduced to microseconds from milliseconds. • These were more reliable and less prone to hardware failure. Hence, such computers required less frequent maintenance. • These were more portable and generated less amount of heat. • Assembly language was used to program computers. Hence, programming became more time-efficient and less cumbersome. • Second generation computers still required air conditioning. • Manual assembly of individual components into a functioning unit was still required.
1.4.3 Third Generation (1964 to Early 1970s): Integrated Circuits The development of the IC was the trait of the third generation computers. An IC consists of a single chip (usually silicon) with many components, such as transistors and resistors fabricated on it (Fig. 1.6). ICs replaced several individually wired transistors. This development made computers smaller in size, reliable, and efficient. Instead of punched cards and printouts, users interacted with third generation computers through keyboards and monitors and interfaced with the operating system. This allowed the device to run many different applications at a time with a central program that monitored the memory. For the first time, computers became accessible to mass audience because they were smaller and cheaper than their predecessors.
Figure 1.6 Integrated Circuit
For example: NCR 395 and B6500. Characteristics of Third Generation Computers • These computers were based on IC technology. • They were able to reduce computational time from microseconds to nanoseconds. • They were easily portable and more reliable than the second generation computers. • These devices consumed less power and generated less heat. In some cases, air conditioning was still required.
01-Computer_Program-01.indd 8
5/28/2010 5:19:47 AM
Introduction to Computers
9
• • • •
The size of these computers was smaller compared with the previous generation computers. Since hardware rarely failed, the maintenance cost was quite low. Extensive use of high-level languages became possible. Manual assembling of individual components was not required, so it reduced the large requirement of labour and cost. However, highly sophisticated technologies were required for the manufacture of IC chips. • Commercial production became easier and cheaper.
1.4.4 Fourth Generation (Early 1970s Till Date): Microprocessors The fourth generation computers use an extension of the third generation technology. Although the technology of this generation was still based on the IC, these have been made readily available to us because of the development of the microprocessor (circuits containing millions of transistors). The Intel 4004 chip, which was developed in 1971, took the IC one step further by locating all the components of a computer (central processing unit, CPU; memory; and input and output controls) on a miniscule chip. A microprocessor is built onto a single piece of silicon, known as the chip. It is about 0.5 cm along one side and no more than 0.05 cm thick (Fig. 1.7). The fourth generation computers led to an era of Large-Scale Integration (LSI) and VLSI technology. LSI technology allowed thousands of transistors to be constructed on one small slice of silicon material, whereas VLSI squeezed hundreds of thousands of components onto a single chip. Ultra large-scale integration (ULSI) increased that number into millions. This way, computers became smaller and cheaper than ever before. The fourth generation computers became more powerful, compact, reliable, and affordable. As a result, it gave rise to the PC revolution. Figure 1.7 Microprocessor During this period, magnetic core memories were substituted by semiconductor memories, which resulted in faster random access main memories. Moreover, secondary memories, such as hard disks became economical, smaller, and bigger in capacity. The other significant development of this era was that these computers could be linked together to form networks, which eventually led to the development of the Internet. This generation also saw the development of the Graphical User Interfaces (GUIs), mouse, and handheld devices. Despite many advantages, this generation required complex and sophisticated technology for the manufacturing of the CPU and other components. For example: Apple II, Altair 8800, and CRAY-1. Characteristics of Fourth Generation Computers • Fourth generation computers are microprocessor-based systems. • These computers are very small. • Fourth generation computers are the cheapest among all the other generations. • They are portable and quite reliable. • These machines generate negligible amount of heat, hence they do not require air conditioning. • Hardware failure is negligible, so minimum maintenance is required. • The production cost is very low. • GUI and pointing devices enable users to learn to use the computer quickly. • Interconnection of computers leads to better communication and resource sharing.
01-Computer_Program-01.indd 9
5/28/2010 5:19:47 AM
10
Computer Programming
1.4.5 Fifth Generation (Present and Beyond): Artificial Intelligence The dream of creating a human-like computer that would be capable of reasoning and reaching a decision through a series of “what-if-then” analyses has existed since the beginning of computer technology. Such a computer would learn from its mistakes and possess the skill of experts. These are the objectives for creating fifth generation computers. The starting point for the fifth generation computers has been set in the early 1990s. The process of developing fifth generation computers is still in the development stage. However, the expert system concept is already in use. The expert system is defined as a computer information system that attempts to mimic the thought process and reasoning of experts in specific areas. Three characteristics can be identified with fifth generation computers. These are: Mega Chips Fifth generation computers will use Super Large-Scale Integrated (SLSI) chips, which will result
in the production of a microprocessor having millions of electronic components on a single chip. In order to store instructions and information, fifth generation computers require a great amount of storage capacity. Mega chips may enable the computer to approximate the memory capacity of the human mind. Parallel Processing Most computers today access and execute only one instruction at a time. This is called
serial processing. However, a computer using parallel processing accesses several instructions at once and works on them at the same time using of multiple CPUs. Artificial Intelligence (AI) It refers to a series of related technologies that tries to simulate and reproduce human behaviour, including thinking, speaking, and reasoning. AI comprises a group of related technologies: expert systems (ES), natural language processing (NLP), speech recognition, vision recognition, and robotics.
1.5
CLASSIFICATION OF COMPUTERS
At present, computers are available in many sizes and types. Some fit in the palm, while others occupy an entire room. Computers also differ based on their data-processing abilities. Based on physical size, performance, and application areas, we can generally divide computers into four major categories: micro computers, mini computers, mainframe computers, and super computers (Fig. 1.8).
Figure 1.8 Classification of Computers
1.5.1
Micro Computers
A micro computer is a small, low-cost digital computer, which usually consists of a microprocessor, a storage unit, an input channel, and an output channel, all of which may be on one chip inserted into one or several PC boards. The addition of a power supply and connecting cables, appropriate peripherals (keyboard, monitor,
01-Computer_Program-01.indd 10
5/28/2010 5:19:48 AM
11
Introduction to Computers
printer, disk drives, and others), an operating system, and other software programs can provide a complete micro computer system. The micro computer is generally the smallest of the computer family. Originally, these were designed for individual users only, but nowadays they have become powerful tools for many businesses that, when networked together, can serve more than one user. IBM-PC Pentium 100, IBM-PC Pentium 200, and Apple Macintosh are some examples of micro computers. Micro computers include desktop, laptop, and hand-held models, such as personal digital assistants (PDAs). Desktop Computer Desktop computer, also known as Personal Computer
(PC), is principally intended for stand-alone use by an individual (Fig. 1.9). These are the most common types of micro computers. These micro computers typically consist of a system unit, a display monitor, a keyboard, internal hard disk storage, and other peripheral devices. The main reason behind the importance of the PCs is that they are not very expensive for the individuals or the small businesses. Some of the major PC manufacturers are Apple, IBM, Dell, and Hewlett-Packard. Laptop A laptop is a portable computer, that is, a user can carry it around. Since the laptop computer resembles a notebook, it is also known as a “notebook.” Laptops are small computers enclosing all the basic features of a normal desktop computer. The biggest advantage of this computer is that one can use this computer anywhere and at anytime, especially when one is travelling. Moreover, these computers do not need any external power supply, as a rechargeable battery is completely self-contained in them. These computers are expensive as compared to desktop computers (Fig. 1.10). Hand-held Computers A hand-held computer, also called a Personal Digital Assistant (PDA), is one that can conveniently be stored in a pocket (of sufficient size) and used while the user is holding it. PDAs are essentially small portable computers and are slightly bigger than the common calculators. A PDA user generally uses a pen or an electronic stylus, instead of a keyboard for input. As shown in Figure 1.11, the monitor is very small and is the only apparent form of output. Since these computers can be easily fitted on the palm, they are also known as palmtop computers. Hand-held computers usually have no disk drive; instead they use small cards to store programs and data. However, they can be connected to a printer or a disk drive to generate output or store data. They have limited memory and are less powerful as compared to desktop computers. Some examples of PDAs are Apple Newton, Casio Cassiopeia, and Franklin eBookMan.
1.5.2
Figure 1.9 Desktop Computer
Figure 1.10 Laptop Computer
Mini Computers
In the early 1960s, Digital Equipment Corporation (DEC) started shipping its PDP series computer, which the press described as mini computers. The mini computer is a small digital computer, whose process and storage Figure 1.11 Personal Digital capacity is lesser than that of a mainframe, but more than that of a micro Assistant computer (Fig. 1.12). It is about the size of a two-drawer filing cabinet. Generally, it is used as a desktop device that is often connected to a mainframe to perform auxiliary operations.
01-Computer_Program-01.indd 11
5/28/2010 5:19:48 AM
12
Computer Programming
The mini computer (sometimes called a mid-range computer) is designed to meet the computing needs for several people simultaneously in a small to mediumsized business environment. It is capable of supporting from 4 to about 200 simultaneous users. It serves as a centralized storehouse for a cluster of workstations or as a network server. Mini computers are usually multi-user systems, so these are used in interactive applications in industries, research organizations, colleges, and universities. These are also used for real-time controls and engineering design work. High-performance workstations with graphics I/O capability use mini computers. Some of the widely used mini computers are PDP 11, IBM (8000 series), and VAX 7500.
1.5.3 Mainframe Computer A mainframe computer is an ultra high-performance computer made for highvolume, processor-intensive computing. It consists of a high-end computer processor, with related peripheral devices, capable of supporting large volumes of data processing, high-performance online transaction processing systems, and extensive data storage and retrieval. Normally, it is able to process and store more data than a mini computer and far more than a micro computer. Moreover, it is designed to perform at a faster rate than a mini computer and at an even faster rate than a micro computer. Mainframes are the second largest (in capability and size) of the computer family, the largest being super computers. However, mainframes can usually execute many programs simultaneously at a high speed, whereas super computers are designed for single processes (Fig. 1.13). A mainframe allows its user to maintain large information storage at a centralized location, and access and process these data from different computers located at different locations. It is typically used by large businesses and for scientific purposes. Examples of mainframe computers are IBM’s ES000, VAX 8000, and CDC 6600.
1.5.4
Super Computers
Super computers are special-purpose machines, which are specially designed to maximize the numbers of Floating Point Operations Per Second (FLOPS). Any computer below 1 gigaflop/sec is not considered a super computer. A super computer has the highest processing speed at a given time for solving scientific and engineering problems. Essentially, it contains a number of CPUs that operate in parallel to make it faster. Its processing speed lies in the range of 400–10,000 Millions of Floating Point Operations Per Second (MFLOPS). Due to this feature, super computers are used in many applications (Fig. 1.14).
01-Computer_Program-01.indd 12
Figure 1.13
Figure 1.12 Mini Computer
Mainframe Computer
FACT FILE India’s Super Achievement Recently, India developed the PARAM Padma super computer, which marks an important step towards high-performance computing. The PARAM Padma computer was developed by India’s Center for Development of Advanced Computer (C-DAC) and promised processing speeds of up to one teraflop per second (1 trillion processes per second).
5/28/2010 5:19:49 AM
Introduction to Computers
13
Figure 1.14 Super Computer
A super computer can process a great deal of information and make extensive calculations very quickly. It can resolve complex mathematical equations in a few hours, which would have taken a scientist with paper and pencil a lifetime, or years, using a hand calculator. It is the fastest, costliest, and most powerful computer available today. Typically, super computers are used to solve multi-variant mathematical problems of existent physical processes, such as aerodynamics, metrology, and plasma physics. These are also required by the military strategists to simulate defence scenarios. Cinema technicians use them to produce sophisticated movie animations. Scientists build complex models and simulate them in a super computer. However, a super computer has limited broad-spectrum use because of its price tag and limited market. The largest commercial use of super computers is in the entertainment/advertising industry. CRAY–3, Cyber 205, and PARAM are some well-known super computers.
1.6
APPLICATION OF COMPUTERS
In the last few decades, computer technology has revolutionized businesses and other aspects of human life all over the world. Practically, every company, large or small, is now directly or indirectly dependent on computers for information processing. Computer systems also help in the efficient operations of railway and airway reservation, hospital records, accounts, electronic banking, and so on. Computers not only save time but also paperwork. Some of the areas where computers are being used are listed below (Fig. 1.15). • Science: Scientists have been using computers to develop theories, to analyze, and test data. The fast speed and accuracy of the computer allow for different scientific analyses to be carried out. They can be used to generate detailed studies of how earthquakes affect buildings or pollution affects weather patterns. Satellitebased applications could not have been possible without the use of computers. It would also not be possible to obtain the information of our solar system and the cosmos without computers. • Education: Computers have also revolutionized the whole process of education. Currently, classrooms, libraries, and museums are utilizing computers to make education much more interesting. Unlike recorded television shows, computer aided education (CAE) and computer based training (CBT) packages are making learning much more interactive.
01-Computer_Program-01.indd 13
5/28/2010 5:19:50 AM
14
Computer Programming
Figure 1.15 Application Areas of Computer
• Medicine and Health Care: There has been an increasing use of computers in the field of medicine. Now doctors are using computers right from diagnosing illness to monitoring a patient’s status during complex surgery. By using automated imaging techniques, doctors are able to look inside a person’s body and study each organ in detail (such as CAT scans or MRI scans), which was not possible few years ago. There are several examples of special-purpose computers that can operate within the human body, such as a cochlear implant, a special kind of hearing aid that makes it possible for deaf people to hear. • Engineering/Architecture/Manufacturing: Architects and engineers extensively use computers in creating designs and drawings. Using computers, a three-dimensional view of the objects can be simulated. By using techniques like virtual reality, architects can explore houses that have been designed, but not built. The manufacturing factories use computerized robotic arms to perform hazardous jobs. Besides, computer aided manufacturing (CAM) can be used in designing products, ordering parts, and planning production. • Entertainment: Computers are finding greater use in the entertainment industry. They are used to control the images and sounds. Special effects, which mesmerize the audience, would not have been possible without the use of computers. In addition, computerized animation and colourful graphics have modernized the film industry. • Communication: E-mail is one of the communication media that makes use of computers. Through e-mail, messages and reports are passed from one person to one or more persons. The benefit of the e-mail service is that while transferring messages, it saves time, paper, and is instantly delivered to the recipient. Moreover, the person who is receiving the messages can read the messages whenever he or she is free and can save it, reply it, forward it, or delete it from the computer. • Business Application: Initially, computers were used for batch processing jobs, where one does not require an immediate response from the computer. Currently, computers are mainly used for real-time applications that require an immediate response from the computer. There are various concerns for which computers are used, such as in business forecasting, to prepare pay bills and personal records, in banking operations and data storage, in the various types of life insurance business, and as an aid to management. Businesses are also using the networking of computers, where a number of computers are connected together to share data and information. The use of e-mail and Internet has changed the ways in which a business operates. • Publishing: Computers have created a field known as Desktop Publishing (DTP). In DTP, with the help of a computer and a laser printer, one can perform the publishing job all by oneself. Many of the tasks requiring
01-Computer_Program-01.indd 14
5/28/2010 5:19:50 AM
Introduction to Computers
15
long manual hours, such as generating table of contents and index, can be automatically done by the application of computers and DTP software. • Banking: In the field of banking and finance, computers are extensively used. People can use the Automated Teller Machine (ATM) services 24 hours of the day to deposit and withdraw cash. When different branches of a bank are connected through computer networks, inter-branch transactions can be performed by the computers without any delay.
1.7 BASIC COMPUTER ORGANIZATION A computer is an information-processing machine. It can be viewed as a system, which consists of a number of inter-related components that work together with the aim of converting data into information. This processing is carried out electronically, usually with little or no intervention from a human user. To obtain the required information, data are entered through input devices. These data are processed using the CPU, and then the processed data (known as information) are displayed to the users using various output devices. All these parts (input devices, CPU, and output devices) are referred to as the hardware of the computer. The general perception of people regarding the computer is that it is an “intelligent thinking machine.” However, this is not true. Every computer needs to be told exactly what to do and how to do. This is done by giving instructions to the computer. These instructions are given in the form of computer programs, which constitute the software. In Section 1.7.1, we discuss the computer hardware in detail. Computer software is discussed in the next chapter.
1.7.1
Hardware
Hardware refers to all visible devices that are assembled together to build a computer system. These include various input devices, CPU, output devices, and memory (Fig. 1.16).
Figure 1.16
Various Hardware Devices
Input Devices Input devices are electromechanical devices that allow the user to feed information into the computer for analysis, storage, and to give commands to the CPU. Data and instructions are entered into the memory of a computer through input devices. It captures information and translates it into a form that can be processed by the CPU. The computer accepts input in two ways, either manually or directly. In case of manual data entry, the user enters data into the computer by hand, for example, by using a keyboard and a mouse. In case of direct entry, information is fed into the computer automatically from a source document (like barcode). Some of the commonly used input devices are keyboard, pointing devices like mouse and joystick, and scanners.
01-Computer_Program-01.indd 15
5/28/2010 5:19:50 AM
16
Computer Programming
Central Processing Unit The central processing unit (CPU) referred to as the “brain” of a computer system converts data (input) into meaningful information (output). It is a highly complex, extensive set of electronic circuitry, which executes stored program instructions. A CPU (Fig. 1.17) controls all internal and external devices, performs arithmetic and logic operations, and operates only on binary data, that is, data composed of ‘1’s and ‘0’s. In addition, it also controls the usage of main memory to store data and instructions, and controls the sequence of operations. The CPU consists of three main subsystems: the Arithmetic/Logic Unit (ALU), the Control Unit (CU), and the Registers. The three subsystems work together to provide operational capabilities to the computer.
Memory
Figure 1.17
CPU
The arithmetic/logic unit (ALU) contains electronic circuitry that executes all arithmetic and logical operations on the data made available to it. The data required to perform the arithmetic and logical functions are inputs from the designated registers. The ALU comprises two units: arithmetic unit and logic unit.
Arithmetic/Logic Unit (ALU)
• Arithmetic unit: The arithmetic unit contains the circuitry that is responsible for performing the actual computing and carrying out the arithmetic calculations, such as addition, subtraction, multiplication, and division. It can perform these operations at a very high speed. • Logic unit: The logic unit enables the CPU to perform logical operations based on the instructions provided to it. These operations are a logical comparison between data items. The unit can compare numbers, letters, or special characters and can then take action based on the result of the comparison. Logical operations of a logic unit can test for three conditions: equal-to condition, less-than condition, and greater-than condition. This unit checks the correctness of sequence of operations. It fetches program instruction from the primary storage unit, interprets them, and ensures correct execution of the program. It also controls the input/output devices and directs the overall functioning of the other units of the computer (Fig. 1.18).
Control Unit (CU)
01-Computer_Program-01.indd 16
5/28/2010 5:19:51 AM
Introduction to Computers
17
Figure 1.18 Control Unit Registers Registers are special-purpose, high-speed temporary memory units that hold various types of information, such as data, instructions, addresses, and the intermediate results of calculations. Essentially, they hold the information that the CPU is currently working on. Registers can be thought of as CPU’s working memory, a special additional storage location that offers the advantage of speed (Fig. 1.19).
Figure 1.19 Registers in CPU
01-Computer_Program-01.indd 17
5/28/2010 5:19:51 AM
18
Computer Programming
Output Devices Just as humans communicate with computers through input devices, the computer can communicate with human beings using output devices. Output devices take the machine-coded output results from the CPU and convert them into a form that is easily readable (such as characters, graphical, or audio visual) by human beings. The output unit processes data into useful information. The outputs, which can be easily understood and used by human beings, are in the form of hard copy and soft copy. The physical form of output is known as hard copy. The electronic version of an output, which usually resides in computer memory and/or on disk, is known as soft copy. Some of the commonly used output devices are monitors, printers, plotters, and audio response. Memory The CPU handles the processing of data and after processing presents the results with the help of output devices. However, computers require memory to process data and store output. Memory refers to the electronic storing place for instructions and data. Some data will be required instantaneously, while others may not be needed for extended periods. Likewise, the CPU requires memory to handle the intermediate results and to store the final output. Hence, we can classify memory into two broad categories: primary memory (to handle the data) and secondary memory (to store the output). Primary Memory Primary memory, also known as main memory, stores data and instructions for processing.
Logically, it is an integral component of the CPU but physically, it is a separate part placed on the computer’s motherboard (also known as the main board). Primary memory can be further classified into random access memory (RAM) and read-only memory (ROM). Secondary Memory Secondary memory, also known as auxiliary memory or external memory, is used for stor-
ing instructions (software programs) and data, since the main memory is temporary and limited in size. This memory is least expensive and has much larger storage capacity than the primary memory. Instructions and data stored on such storage devices are permanent in nature. It can be removed only if the user wants to or if the device is destroyed.
1.8
NUMBER SYSTEM
Since the early days of human civilization, people have been using their fingers, sticks, etc. for counting things. The need for counting probably originated when humans started to use animals for domestic purposes and to practice animal breeding for fulfilling his needs and requirements. As daily activities became more complex, numbers became more important in trade, time, distance, and in all other spheres of human life. Ever since people discovered that it was necessary to count objects, they have been looking for easier ways of counting. To count large numbers, humans soon started to count in groups, and various number systems were formed. As manual counting had a limited role for carrying simple computing tasks, computation that was more complex made humans depend on machines to perform the computing task efficiently and accurately. With the advancement of machines, different number systems were formed to make the task simple, accurate, and fast. These number systems worked on the principle of digital logic design present in the modern day computer system and opened a gateway to overcome complex computation barriers. In a precise manner, a number system defines a set of values used to represent “quantity.” Generally, one talks about a number of people attending class, or a number of modules taken by each student, and use numbers to represent grades achieved by students in tests. Quantifying values and items in relation to each other is helpful for us to make sense of our environment. The number system can be categorized into two broad categories:
01-Computer_Program-01.indd 18
5/28/2010 5:19:52 AM
19
Introduction to Computers
• Non-Positional Number Systems: In ancient times, people used to count with their fingers. When fingers became insufficient for counting, stones and pebbles were used to indicate values. This method of counting is called the non-positional number system. It was very difficult to perform arithmetic operations with such a number system, as it had no symbol for zero. The most common non-positional number system is the Roman number system. These systems are often clumsy and it is very difficult to perform calculations for large numbers. • Positional Number Systems: A positional number system is any system that requires a finite number of symbols/digits of the system to represent arbitrarily large numbers. When using these systems the execution of numerical calculations becomes simplified, because a finite set of digits is used. The value of each digit in a number is defined not only by the symbol, but also by the symbol’s position. The most popular positional number system being used today is the decimal number system. Base (or Radix) of System The word base (or radix) means the quality of admissible marks used in a given number system. The admissible marks are the characters, such as Arabic numerals, Latin letters, or other recognizable marks, which are used to present the numerical magnitude of a “quantity.” The decimal number system originated in India. This system has 10 as the base of a number system and is indicated by a subscript (decimal number) and this is followed by the value of the number. For example, (7592)10 represents base 10 number system and (214)8 represents base 8 number system. For a computer, everything is in the digital form (binary form) whether it is number, alphabet, punctuation mark, instruction, etc. Let us illustrate this with the help of an example. Consider the word “INDIA” that appears on the computer screen as a series of alphabetic characters. However, for the computer, it is a combination of numbers. To the computer it appears as: 01001001 I Table 1.1
01001110 N
01000100 D
01001001 I
01000001 A
Types of Number System
Number System
Radix Value
Set of Digits
Example
Decimal
R = 10
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(25)
Binary
R=2
(0, 1)
(11001)
Octal
R=8
(0, 1, 2, 3, 4, 5, 6, 7)
(31)
Hexadecimal
R = 16
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)
(19)
10 2
8 16
1.8.1 Types of Number System Generally, a user is least aware of the fact that actual operations in a computer are performed with a binary number system. Traditionally, the two possible states for a binary system are represented by the digits ‘0’s and ‘1’s. Long before the introduction of octal and hexadecimal numbers, programmers used a convenient method of handling large binary numbers in either 3-bit or 4-bit groupings. Later, the actual machine code for the computer instructions was replaced by mnemonics, which comprised three or four letters of the assembly language for a particular CPU. It was also possible to use more than one base numeration for writing data in these assembly languages, so programmers made sure their assemblers could understand octal, hexadecimal, and binary numbers. Octal and hexadecimal numbers being convenient to humans are used in computational
01-Computer_Program-01.indd 19
5/28/2010 5:19:52 AM
20
Computer Programming
tasks, since the computer only understands binary and as octal and hexadecimal are much more compact than binary. In addition, octal and hexadecimal numbers prevent unwieldy strings that were written in binary. For example, the three-digit decimal number 513 requires 10 digits in pure binary (1000000001) but only three (201) in hexadecimal (Table 1.1). Binary Number System The digital computer provides accurate solutions to the problems by performing arithmetic computations. These numbers are not expressed as decimal numbers within the computer because it is not suitable for machine processes. Computers are not only powered by electricity but they compute with electricity. They shift voltage pulses around internally. When numbers are represented in a computer’s memory by means of small electrical circuits, a number system with only two symbols is used. These symbols are ON or OFF states of the circuit. This system of representing numbers is known as the binary number system. Circuits allow electricity to flow or to be blocked depending on the type of circuit. A computer circuit is made of transistors, which have only two states, ON and OFF. ON is interpreted as 1, while OFF as 0. Similar to the decimal system, the position of a digit in a number indicates its value. Instead of ones, tens, hundreds, thousands, etc., as in the decimal system, the columns in the binary system contain ones, twos, fours, eights, etc. Each additional column to the left has powers of 2, specifically, each place in the number represents two times (2×’s) the place to its right. Table 1.2 represents the first 10 binary numbers. Table 1.2 Representing Decimal Numbers in Binary Decimal Numbers
Binary Numbers 24
23
22
21
20
16
8
4
2
1
0
0
1
1
2
1
0
3
1
1
4
1
0
0
5
1
0
1
6
1
1
0
7
1
1
1
8
1
0
0
0
9
1
0
0
1
Octal Number System The octal number system is a base 8 system, having eight admissible marks: 0, 1, 2, 3, 4, 5, 6, and 7 with no 8’s or 9’s in the system. This system is a positional notation number system. The octal system uses powers of 8 to determine the digit of a number’s position (Table 1.3).
01-Computer_Program-01.indd 20
5/28/2010 5:19:52 AM
21
Introduction to Computers Table 1.3 Representing Binary and Decimal in Octal Decimal Number
Binary Number
Octal Number
0
0000
000 (0 × 8 )
1
0001
001 (1 × 8 )
2
0010
002 (2 × 8 )
3
0011
003 (3 × 8 )
4
0100
004 (4 × 8 )
5
0101
005 (5 × 8 )
6
0110
006 (6 × 8 )
7
0111
007 (7 × 8 )
8
1000
010 (1 × 81 + 0 × 8 )
9
1001
011 (1 × 81 + 1 × 8 )
0 0 0 0 0 0 0 0
0 0
Hexadecimal Number System The hexadecimal system is similar to the decimal, binary, and octal number systems, except that the base is 16. Each hexadecimal number represents a power of 16. To represent the decimal numbers, this system uses 0–9 numbers and A–F characters to represent 10–15, respectively. The largest hexadecimal digit F is equivalent to binary 1111. Table 1.4
Comparing Decimal, Binary, Octal, and Hexadecimal
Decimal
Binary
Octal
Hexadecimal
0
0000
000
0
1
0001
001
1
2
0010
002
2
3
0011
003
3
4
0100
004
4
5
0101
005
5
6
0110
006
6
7
0111
007
7
8
1000
010
8
9
1001
011
9
10
1010
012
A
11
1011
013
B
12
1100
014
C
13
1101
015
D
14
1110
016
E
15
1111
017
F
01-Computer_Program-01.indd 21
5/28/2010 5:19:52 AM
22
Computer Programming
1.8.2 Conversion between Number Bases Computers and other digital systems process information as their primary function. Therefore, it is necessary to have methods and systems for representing information in forms, which can be manipulated and stored using electronic or other types of software. As discussed earlier, a computer uses binary numbers for data representation internally, whereas it uses decimal numbers externally. However, any number in one number system can be represented in another number system. Various techniques, which can be used to convert numbers from one base to another, are as follows: Converting Decimal to Binary, Octal, and Hexadecimal The method used for the conversion of a decimal number into other number systems is often done using the “remainder” method. This method involves the following steps: 1. Divide the decimal number by the base of the target number system. That is, to convert decimal to binary, divide the decimal number with 2 (the base of the binary number system), 8 for octal, and 16 for hexadecimal. 2. Note the remainder separately as the first digit from the right. In case of hexadecimal, if the remainder exceeds 9, convert the remainder into an equivalent hexadecimal form. For example, if the remainder is 10 then note the remainder as A. 3. Continually repeat the process of dividing until the quotient is zero and keep writing the remainders after each step of division. 4. Finally, when no more division can occur, write down the remainders in reverse order. Example 1: Determine the binary equivalent of (36)10.
2
36
Remainder
2
18
0
2
9
0
2
4
1
2
2
0
2
1
0
0
1
Least Significant Bit
Most Significant Bit
Taking remainders in reverse order, we have 100100. Thus, the binary equivalent of (36)10 is (100100)2. Example 2: Determine the octal equivalent of (359)10.
8
359
Remainder
8
44
7
8
5
4
8
0
5
Least Significant Bit
Most Significant Bit
Thus, the octal equivalent of (359)10 is (547)8.
01-Computer_Program-01.indd 22
5/28/2010 5:19:52 AM
23
Introduction to Computers
Example 3: Determine the hexadecimal equivalent of (5112)10.
16
5112
Remainder
16
319
8=8
16
19
15 = F
16
1
3=3
16
0
1=1
Least Significant Bit
Most Significant Bit
Thus, the hexadecimal equivalent of (5112)10 is (13F8)16.
Converting Binary, Octal, and Hexadecimal to Decimal The method used for the conversion of a binary, octal, or hexadecimal number to a decimal number involves each digit of the binary, octal, or hexadecimal number to be multiplied by its weighted position, and then each of the weighted values is added together to obtain the decimal number.
Example 1: Determine the decimal equivalent of (11010)2. Binary Number
1
1
0
1
Weight of Each Bit
24
23
22
21
4
3
2
1
0 20
Weighted Value
2 ×1
2 ×1
2 ×0
2 ×1
20 × 0
Solved Multiplication
16
8
0
2
0
Sum of weight of all bits = 16 + 8 + 0 + 2 + 0 = 26 Thus, the decimal equivalent of (11010)2 is (26)10.
Example 2: Determine the decimal equivalent of (456)8. Octal Number
4
5
Weight of Each Bit
82
81
2
1
6 80
Weighted Value
8 ×4
8 ×5
80 × 6
Solved Multiplication
256
40
0
Sum of weight of all bits = 256 + 40 + 6 = 302 Thus, the decimal equivalent of (456)8 is (302)10.
01-Computer_Program-01.indd 23
5/28/2010 5:19:52 AM
24
Computer Programming
Example 3: Determine the decimal equivalent of (B14)16. Hexadecimal Number
B = 11
1
Weight of Each Bit
162
161
2
1
4 160
Weighted Value
16 × 11
16 × 1
160 × 4
Solved Multiplication
2816
16
4
Sum of weight of all bits = 2816 + 16 + 4 = 2836 Thus, the decimal equivalent of (B14)16 is (2836)10. Converting among Binary, Octal, and Hexadecimal Converting among binary, octal, and hexadecimal can be accomplished easily without converting to decimal first, as the base numbers of all the three systems (2, 8, and 16) are powers of 2. Any octal digit can be written as a group of three binary digits, while a hexadecimal number will comprise four binary digits. Example 1: Determine the octal equivalent of (010111)2. Binary Number
010
111
Octal Number
2
7
The octal equivalent of (010111)2 is (27)8.
Example 2: Determine the hexadecimal equivalent of (11001011)2. Binary Number
1100
Decimal Number
12
11
Hexadecimal Number
C
B
1011
The hexadecimal equivalent of (11001011)2 is (CB)16.
Example 3: Determine the binary equivalent of (231)8. Octal Number
2
3
1
Binary Value
010
011
001
Thus, the binary equivalent of (231)8 is (010011001)2.
Example 4: Determine the binary equivalent of (5AF)16. Hexadecimal Number
5
A
F
Binary Value
0101
1010
1111
Thus, the binary equivalent of (5AF)16 is (010110101111)2.
01-Computer_Program-01.indd 24
5/28/2010 5:19:52 AM
25
Introduction to Computers
Converting between Octal and Hexadecimal The method used for the conversion of an octal number to a hexadecimal number is accomplished by the following steps: 1. Convert each octal digit to the 3-bit binary form. 2. Combine all the 3-bit binary numbers. 3. Segregate the binary numbers into the 4-bit binary form by starting the first number from the right bit (LSB) towards the number on the left bit (MSB). 4. Finally, convert these 4-bit blocks into their respective hexadecimal symbols. Example 1: Determine the hexadecimal equivalent of (2327)8. Octal Number
2
3
2
7
Binary Value
010
011
010
111
Combining the 3-bit binary blocks, we have 010011010111. Separating the group of binary numbers (from the left side) into the 4-bit binary number and by converting these blocks into their respective hexadecimal symbols, we have: 0100 4
1101 D
0111 7
Thus, the hexadecimal equivalent of (2327)8 is (4D7)16. The method used for the conversion of a hexadecimal number to an octal number is the same as the octal to hexadecimal conversion except that each hexadecimal digit is converted into the 4-bit binary form and then after grouping of all the 4-bit binary blocks, it is converted into the 3-bit binary form. Finally, these 3-bit binary forms are converted into octal symbols. Example 2: Determine the octal equivalent of (2B6)16. Hexadecimal Number
2
B
6
Binary Value
0010
1011
0110
Combining all the 4-bit binary blocks, we have 001010110110. Separating the group of binary numbers into the 3-bit binary blocks and by converting these blocks into octal symbols, we have: 001 1
010 2
110 6
110 6
Thus, the octal equivalent of (2B6)16 is (1266)8.
01-Computer_Program-01.indd 25
5/28/2010 5:19:53 AM
26
Computer Programming
SUMMARY 1. A computer is an electronic device that performs diverse operations using instructions to process the information in order to achieve desired results. Speed, accuracy, reliability, versatility, diligence, storage capabilities, and source sharing are the characteristics of the computers. 2. Computer development is divided into five main generations. With every generation, computer technology has fundamentally changed, resulting in increasingly smaller, cheaper, more powerful, more efficient, and reliable devices. First generation computers were vacuum tubebased machines. These computers were very large, and required a lot of space for installation, generated a large amount of heat, and were non-portable and very slow equipments. Second generation computers used transistors in place of vacuum tubes. Since the transistor was a small device, the physical size of computers was greatly reduced. Computers became smaller, faster, cheaper, energy-efficient, and more reliable than their predecessors. Third generation computers were integrated circuit (IC)-based machines. IC replaced several individually wired transistors making computers smaller in size, reliable, and efficient. Fourth generation computers use a microprocessor (circuits containing millions of transistors) as their basic processing device. These computers are most powerful, compact, reliable, and affordable as compared to their predecessors. Fifth generation computers that are still in the development stage will use mega chips, which will result in the production of microprocessors having millions of electronic components in a single chip. They will use intelligent programming (AI) and knowledge-based problem-solving techniques. 3. A micro computer is a small, low-cost digital computer, which usually consists of a microprocessor, a storage unit, an input channel, and an output channel.A mini computer is a small digital computer, whose process and storage capacity is lesser than that of a mainframe, but more than that of a micro computer. A mainframe is an ultra high-performance computer made for high-volume, processor-intensive computing. It is mainly used for large volumes of data processing, high-performance online transaction processing systems, and extensive data storage and retrieval. 4. Super computers are special-purpose machines. These are unique and parallel architectures in order to achieve high speeds and being effective on a small range of problems. 5. Computers have entered every sphere of human life and have found applications in various fields, such as medicine and health care, business, education, science, banking, publishing, entertainment, engineering, architecture, and so on. 6. A computer can be viewed as a system that comprises input devices, central processing unit, output devices, and memory. Input devices, central processing, and output devices are referred to as hardware of the computer. Hardware refers to all visible devices that are assembled together to build a computer system. 7. Input devices are electromechanical devices that allow the user to feed information into the computer for analysis, storage, and to give commands to the central processing unit. Output devices take the machine-coded output results from the CPU and convert them into a form that is easily readable (such as characters, graphical, or audio visual) by human beings. 8. CPU handles the processing of data and after processing presents the results with the help of output devices. However, computers require memory to process data and store output. Memory refers to the electronic holding place for instructions and data.
01-Computer_Program-01.indd 26
5/28/2010 5:19:53 AM
Introduction to Computers
27
9. With the advancement of machines, different number systems were formed to make the task simple, accurate, and fast.These number systems worked on the principle of digital logic design present in the modern-day computer system and opened a gateway to overcome complex computation barriers. In a precise manner, a number system defines a set of values used to represent “quantity.” 10. The number system can be categorized into two broad categories: non-positional number systems and positional number systems. 11. In a non-positional number system, special symbols or characters are used to indicate values. It is very difficult to perform arithmetic with such a number system, as it has no symbol for zero. 12. In a positional number system, the value of each digit in a number is defined by the symbols but also by the symbol’s position. These symbols are called digits. 13. The positional number system, which is being used nowadays, is called the decimal number system. Apart from this number system, there are some other positional number systems, such as binary number system, octal number system, and hexadecimal number system. 14. The base or radix of the number system tells the number of symbols or digits used in the system. The base of the decimal number system is 10, of binary number system is 2, of octal number system is 8, and of hexadecimal number system is 16.
EXERCISES A. Answer the following questions. 1. 2. 3. 4. 5. 6. 7. 8. 9.
10.
11.
Discuss the characteristics of computers. What are the advantages of transistors over vacuum tubes? Discuss the various types of computers in detail. List the various applications of computers. Discuss the various computer generations along with the key characteristics of the computers of each generation. Discuss the basic organization of a computer system, and explain the functions of various units of a computer system. What do you understand by central processing unit? Describe in detail the various units of a CPU. What are registers in a CPU? With an appropriate example, explain the conversion of: (a) Binary to octal and vice versa (b) Binary to hexadecimal and vice versa (c) Octal to hexadecimal and vice versa Perform the following conversions: (a) Convert binary 00011011 to decimal (b) Convert decimal 278 to binary (c) Convert decimal 0.625 to binary What is a radix or base of the system? With the help of this system, brief the various types of number systems.
01-Computer_Program-01.indd 27
5/28/2010 5:19:53 AM
28
Computer Programming
B. Select the appropriate option for each of the following questions: 1. The development of computers can be divided into ......................... generations. (a) 3 (b) 4 (c) 5 (d) 6 2. Analytical engine was developed by: (a) Gottfried Wilhem Von Leibniz (b) Charles Babbage (c) Herman Hollerith (d) Joseph-Marie Jacquard 3. The computer that is not considered as a portable computer is: (a) Laptop computer (b) Notebook computer (c) Mini computer (d) None of these 4. UNIVAC is an example of: (a) First generation computer (b) Second generation computer (c) Third generation computer (d) Fourth generation computer 5. The unit that performs the arithmetical and logical operations on the stored numbers is known as ......................... (a) Arithmetic Logic Unit (b) Control Unit (c) Memory Unit (d) Both (a) and (b) 6. Choose the odd one out. (a) Micro computer (b) Mini computer (c) Super computer (d) Digital computer 7. ......................... is a very small computer that can be held in the palm of the hand. (a) PDA (b) PC (c) Laptop (d) Mini computer 8. The main distinguishing feature of fifth generation computers will be: (a) Liberal use of microprocessors (b) Artificial intelligence (c) Extremely low cost (d) Versatility 9. CPU stands for: (a) Central protection unit (b) Central processing unit (c) Central power unit (d) Central prerogative unit 10. The physical form of output is known as ....................... . (a) Printout (b) Hard copy (c) Soft copy (d) Printed copy
01-Computer_Program-01.indd 28
5/28/2010 5:19:53 AM
Chapter
2
Computer Software CH A PT E R O U T LIN E
2.1
2.1
Introduction
2.5
Installing and Uninstalling Software
2.2
Software
2.6
Software Piracy
2.3
Types of Software
2.7
Starting a Computer (Booting)
2.4
Software Terminologies
2.8
Software Development Steps
INTRODUCTION
A computer system consists of hardware, the electronic devices that are capable of computing and manipulating information, and software (set of instructions) that carries out predefined tasks to complete a given job. As we know, a computer cannot think or perform on its own. It performs operations like addition, subtraction, multiplication, and division only when the user instructs it to do so. The user gives logical instructions and the central processing unit (CPU) acts in accordance with the instructions. The sets of instructions that control the sequence of operations are known as programs, and collectively, the programs are called software. It is an intangible commodity, that is, the part of a computer system that users cannot touch. We can compare hardware and software with human body and human intelligence, respectively. All human physical actions, such as walking and eating are movements initiated and controlled by the brain. If the brain does not initiate an action, we do not perform any physical activity. Similarly, the functioning of every hardware component is driven by software. The combination of physical components (hardware) and logical instructions (software) gives modern computing systems their power and versatility.
02-Computer_Program-02.indd 29
5/28/2010 4:34:07 AM
30
2.2
Computer Programming
SOFTWARE
Software is a generic term for an organized collection of computer data and instructions. It is responsible for controlling, integrating, and managing the hardware components of a computer and for accomplishing specific tasks. In other words, software tells the computer what to do and how to do it. For example, the software instructs the hardware what to display on the user’s screen, what kinds of input to take from the user, and what kinds of output to generate. Thus, software communicates with the hardware by organizing the control sequences and the hardware carries out the instructions defined by the software. As discussed earlier, a computer needs to be instructed to perform any task. These instructions are given in the form of computer programs, which are written in computer programming languages. A program controls the activity of the processor. When the hardware (processor, memory, etc.) acts as per the instructions of a program, the program is said to be in running or executing state. A set of programs that are specifically written to provide the user a precise functionality like solving a specific problem is termed as a software package. For example, word processing software package provides functionality to the computer so that it can be used to create text documents like letters and mailing lists. Similarly, an image processing software package assists a user in drawing and manipulating graphics.
2.2.1
Relationship between Software and Hardware
Software refers to the computer programs that are loaded into a computer system, and hardware refers to all the visible devices that are assembled together to build a computer system. Both software and hardware go hand in hand; you cannot have one without the other. Even though hardware is the physical part of a computer, it is of no use unless it has software to control it. In a way, hardware is like a car without a driver; one needs both to make something happen. Software is a set of instructions that tells the hardware what to do and how to perform the requested actions. Thus, hardware and software share a special relationship. If hardware is the ‘heart’ of a computer system, software is its ‘soul’. Both are complimentary to each other. An analogy can be taken of a video game system that comprises a console, games cassettes, joystick, and display screen as the hardware. The games in the cassettes can be considered as the software. To play a particular game, the cassette of that game has to be loaded on the console. Similarly, to get a particular job done by a computer, the relevant software is loaded in the storage device, which makes a computer perform the desired functions. Therefore, it is evident that software is vital. Another inference from this analogy is that different software can be used on the same hardware to perform different jobs, just as different games can be played on the same console by using different cassettes.
2.3
TYPES OF SOFTWARE
Software can be categorized as system software and application software. System software is a generic term for referring to any computer program whose purpose is to help the user to run the computer system, whereas application software employs the capabilities of a computer directly to a task that the user wishes to perform. As an analogy, we can compare an electric bulb with an application and the electric power generation plant with the system. The power plant merely generates electricity. It is not really of any use until harnessed to an application like the electric bulb, which performs a service that the user desires.
2.3.1
System Software
System software consists of several programs that are directly responsible for controlling, integrating, and managing the individual hardware components of a computer system. You must have noticed that a new
02-Computer_Program-02.indd 30
5/28/2010 4:34:07 AM
31
Computer Software
computer system is always accompanied by some software, either stored in a floppy or CD, which is supplied by the manufacturer. This software manages and supports the computer system and its information-processing activities. System software is more transparent and less noticed by users; it usually interacts with the hardware or the applications. It provides a programming environment in which programmers can create applications to accommodate their needs. This environment provides functions that are not available at the hardware level and performs the tasks related to the execution of an application program. Hence, system software acts as an interface between the hardware of the computer and the software applications (Fig. 2.1).
Computer User
System Software
Application Software
Computer User
Figure 2.1 System Software as an Interface
In simple terms, system software makes the computer functional. It provides basic functionality like file management, visual display, and keyboard input, and is used by the application software to accomplish these functions. Some examples of system software are operating systems, device drivers, language translators, and system utilities. • Operating System: Operating system is the first layer of software loaded into computer memory when it starts up (Fig. 2.2). As the first software layer, all other software that gets loaded after it depends on it for various common core services. These common core services include disk access, memory management, task scheduling, and user interfacing. In addition, the operating system ensures that different programs executing at the same time do not interfere with each other. It provides a software platform on top of which other programs can run. In simple words, the operating system organizes and controls the hardware. Examples of operating systems are Windows XP, UNIX, and Linux. • Device Drivers: Device drivers are system programs that are responsible for proper functioning of devices (Fig. 2.3). Every device, whether it is a printer, monitor, mouse, or keyboard, has a driver program associated with it for its proper functioning. Whenever a new device is added to the computer system, a new device driver must be installed before the device is used. In modern operating systems, most hardware drivers, such as the keyboard driver, come with the operating system. A driver acts like a translator between the device and the program (typically, an operating system) that uses the device. For example, when a user prints a document, the processor issues a set of generic commands to the printer driver, and the driver translates those commands into specialized instructions that the printer understands. Note that each device has its own set of specialized commands that only its driver understands. A device driver is not an independent program; it assists and is assisted by the operating system for the proper functioning of the device. • Language Translators: Computers only understand a language consisting of ‘0’s and ‘1’s called machine language. To ease the burden of programming entirely in ‘0’s and ‘1’s, special programming languages called
02-Computer_Program-02.indd 31
5/28/2010 4:34:07 AM
32
Computer Programming
Monitor Mouse
user Interface Security Management Device Management File Management Memory Management Process Management Hardware
Printer
Hard Disk Operating System
Application
Keyboard
Figure 2.2 Operating System
stem
Operating Sy
UX
LIN
D R I V E R S
Printer
Monitor
LAN Card
Figure 2.3 Device Drivers
high-level programming languages were developed that resemble natural languages like English. Therefore, a tool was required that could translate a program written in a programming language to machine language. With every programming language, a language translator was also developed, which accepts the programs written in a programming language and executes them by transforming them into a form suitable for
02-Computer_Program-02.indd 32
5/28/2010 4:34:08 AM
33
Computer Software execution. To be precise, they convert programming statements into ‘0’s and ‘1’s that the computer is able to process (Fig. 2.4). Depending on the programming language used, language translators are divided into three major categories: compiler, interpreter, and assembler. All these are listed in Table 2.1
Source program cin >> x; a=x+y-z if (a != B cout B
Yes
Output A
Output B
Check whether the value of A is greater than the value of B If A is greater than B then display A, otherwise display B Connector symbols are used to join the flow lines
Stop
04-Computer_Program-04.indd 86
End the flowchart
5/28/2010 4:32:35 AM
87
Computer Programming and Languages
4.3.3 Repetition Control Structure
Flowchart
Pseudocode
Repetition or loop pattern causes an interruption REPEAT in the normal sequence of processing (Fig. 4.4). It Repeated Task Sequence 1 directs the system to loop back to a previous statement Sequence 2 in the program, repeating the same sequence over and False again, usually with new data. When a sequence of Condition statements is repeated against a condition, it is said Sequence N to be in a loop. Using looping, the programmer avoids True UNTIL Condition is False writing the same set of instructions again. The looping process can either be one time or multiple times until the desired output is obtained within a single Figure 4.4 Flowchart and Pseudocode for Repetition program. Construct The following example, shown in Table 4.4, prints the first 10 natural numbers. Notice that at the beginning, the value of COUNT variable is initialized to zero. After that, COUNT is increased by one and the value is printed. If the value of COUNT is less than 10 (which represents the count of numbers to be displayed) then the same process is repeated. At the conclusion of each iteration, the condition is evaluated, and the loop repeats until the condition becomes true. The loop terminates when the condition becomes false. Table 4.4
Repetition Control Structure
Example Flowchart Start
Count=0
Count=Count+1
Step-by-Step Instructions Begin the flowchart Initialize the memory variable COUNT to zero Increment the value of COUNT by 1
Print Count
Print the value of COUNT
If Count
Greater than
=
Greater than or equal to
Greater than
|
Vertical bar
()
Parenthesis left /right
/
Slash
[]
Bracket left/right
\
Back slash
{}
Curly Braces left/right
~
Tilde
%
Percent Number sign or Hash
_
Underscore
#
$
Dollar
=
Equal to
?
Question Mark
@
At the rate
9.3 DELIMITERS The language pattern of C uses special kinds of symbols called delimiters. They are given in Table 9.3. Table 9.3 Delimiters Symbol
Delimiters
Use
:
Colon
Useful for label
;
Semicolon
Terminates statement
()
Parenthesis
Used in expression and function
[]
Square bracket
Used for array declaration
{}
Curly brace
Scope of statement
#
Hash
Preprocessor directive
,
Comma
Variable separator
9.4 C KEYWORDS The C keywords are reserved words by the compiler. All C keywords have been assigned a fixed meaning. They cannot be used as variable names because they have been assigned fixed jobs. However, few C compilers allow the
09-Computer_Program-09.indd 271
3/11/2011 11:57:20 AM
Computer Programming
272
construction of variable names, which exactly coincide with the keywords. It is suggested not to mix up keywords with variable names. For utilizing the keywords in a program, no header file is to be included. The descriptions of the keywords are explained in different programs/chapters. The C keywords are listed in Table 9.4. Table 9.4 The 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 are as follows:
asm
cdecl
far
huge
interrupt
near
pascal
9.5 IDENTIFIERS A symbolic name is used to refer to a variable. This is done using identifiers. In other words, identifiers refer to variety of entities, such as structures, unions, enumeration, constants, typedef names, functions, and objects. The C identifier does not allow blank spaces, punctuation, signs, etc. Identifiers are user-defined names, consisting of sequence of letters and digits, with the letter as the first character. They are used to name variables, functions, and arrays. They are generally defined in lower case letters. However, upper case letters are also permitted. The (_) underscore symbol can also be used as and in an identifier. In general, underscore is used as a link between two words in long identifiers. Examples of valid identifiers are length, area, volume, sUM, Average, etc. Examples of Invalid identifiers are length of line, S+um, year’s, etc. Figure 9.2 shows the various identifiers.
Variable Pointer Structure
Identifiers
Union Array Function
Figure 9.2 Identifiers
09-Computer_Program-09.indd 272
3/11/2011 11:57:21 AM
The C Declarations
273
Some identifiers in C can be as follows: (a) #define N 10 (b) #define a 15 Here, ‘N’ and ‘a’ are user-defined identifiers.
9.6 CONSTANTS The constants in C are applicable to the values that do not change during the execution of a program. There are several types of constants in C. They are classified into the following groups as given in Figure 9.3. C Constants
Numeric Constants
Character Constants
Integer Constants
Single Character Constants
Real Constants
String Constants
Figure 9.3 C constants
9.6.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 hexadecimal 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 representation, with leading OX or OX.
09-Computer_Program-09.indd 273
3/11/2011 11:57:22 AM
Computer Programming
274
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) (b) (c) (d)
The decimal point is permitted. Neither blank spaces nor commas are permitted. Real numbers could be either positive or negative. 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 exponential 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. 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.
9.6.2 Character Constants (a) Single character constants A character constant is a single character. Characters are also represented by a single digit, single special symbol, or white space enclosed within a pair of single quote marks. Example: ‘a’, ‘8’, ‘”’, etc. Character constants have integer values known as ASCII values. For example, the statement printf (“%c %d”,65,‘B’); will display the characters, ‘A’ and 66. (b) String constants String constants are sequence of characters enclosed within double quote marks. The string may be a combination of all kinds of symbols. Example: “Hello”, “India”, “444”, “a”.
09-Computer_Program-09.indd 274
3/11/2011 11:57:22 AM
The C Declarations
275
A programming example is illustrated below on various constants. 9.1 Write a program to demonstrate various constants. void main() { int x; float y; char z; double p; long int q; clrscr(); x=40; y=2e2; z=‘a’; p=3.1e10; q=123456; printf(“\n%d %10.2f %c getche(); }
%.2lf %ld”,x,y,z,p,q);
OUTPUT: 40 200.00 a 31000000000.00 123456
Explanation: In this programming example, various constants are assigned to the variables and they are displayed.
9.7 VARIABLES During program execution, the value of variables can be changed. Variables can be of different data types. They can be integer, real, or character data types. These data are stored in the memory and at the time of execution different operations are performed on them. In C, a variable is a data name used for storing a data value. Its value may be changed during program execution. The value of variables keeps on changing during the execution of a program. In other words, a variable can be assigned different values at different times during the execution of a program. A variable name may be declared based on the meaning of the operation. Some meaningful variable names are height, average, sum, etc.
9.8 RULES FOR DEFINING VARIABLES 1. They must begin with a character without spaces but underscore is permitted. 2. The length of the variable varies from one compiler to another. Generally, most of the compilers support eight characters excluding extension. However, the ANSI standard recognizes the maximum length of a variable up to 31 characters. 3. The variable should not be a C keyword. 4. The variable names may be a combination of upper and lower characters. For example, suM and sum are not the same variables. 5. The variable name should not start with a digit.
09-Computer_Program-09.indd 275
3/11/2011 11:57:22 AM
276
Computer Programming
9.9 DATA TYPES All C compilers support a variety of data types. This enables the programmer to select the appropriate data type according to the need of the application. Generally, data is represented using numbers or characters. The numbers may be integers or real. The C compiler supports different data types, which are explained here under.
9.9.1 Integer Data Types (a) Integer – short and long All C compilers offer either short or long integer data types. Short integers require half the space of the memory than the long ones. A brief description of them is given in Table 9.5. Table 9.5 Difference Between Short and Long Integers Short Integer
Long Integer
Occupies 2 bytes of memory
Occupies 4 bytes of memory
Range: –32,768 to 32,767
Range: –2147483648 to 2147483647
Program runs faster.
Program runs slower.
Format specifier is %d or %i.
Format specifier is %ld.
Example: int a=2; short int b=2; When a variable is declared without a short or long keyword, the default is short-signed int.
Example: long b; long int c;
(b) Integers – signed and unsigned The difference between signed and unsigned integers is given in Table 9.6. Table 9.6 Difference Between Signed and Unsigned Integers Signed Integer
Unsigned Integer
Occupies 2 bytes of memory
Occupies 2 bytes of 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 short-signed int.
By default, unsigned int is short-unsigned int.
There are also long-signed integers ranging from –2147483648 to 2147483647.
There are also long-unsigned integers with range 0 to 4294967295.
Example: int a=2; long int b=2;
Example: unsigned long b; unsigned short int c; When a variable is declared as unsigned the negative range of the data type is transferred to positive, i.e., double the largest size of the possible value. This is because on declaring unsigned int; the 16th bit is free and not used to store the sign of the number.
09-Computer_Program-09.indd 276
3/11/2011 11:57:22 AM
The C Declarations
277
9.9.2 Characters – signed and unsigned A brief description on these data types are illustrated in Table 9.7. Table 9.7 Difference Between Signed and Unsigned Characters Signed Character
Unsigned Character
Occupies 1 byte of memory
Occupies 1 byte of memory
Range: –128 to 127
Range: 0 to 255
Format specifier: %c
Format specifier: %c
When printed using %d control string, corresponding ASCII number is printed.
When printed using %d control string, corresponding ASCII number is printed.
Example: char ch=‘b’;
Example: unsigned char=‘b’;
9.9.3 Floats and Doubles Table 9.8 shows the description of floats and double floats. Table 9.8 Difference Between Float and Double Float Float
Double Float
Occupies 4 bytes of memory
Occupies 8 bytes of memory
Range: 3.4e–38 to 3.4e+38
Range: 1.7e–308 to 1.7e+308
Format specifier: %f
Format specifier: %lf
Example: float a;
Example: double y; There also exist long double having a range of 3.4e–4932 to 3.4e+4932 and occupies 10 bytes of memory. Example: long double k;
9.9.4 Entire Data Types in C The entire data types supported by the 16-bit machine are given in Table 9.9 for the convenience of the reader. Table 9.9 Data Types and their format specifiers Data Type
Size (bytes)
Range
Format Specifiers
char
1
–128 to 127
%c
unsigned char
1
0 to 255
%c
short or int
2
–32,768 to 32,767
%i or %d
unsigned int
2
0 to 65535
%u
long
4
–2147483648 to 2147483647
%ld
unsigned long
4
0 to 4294967295
%lu
float
4
3.4e–38 to +3.4e+38
%f or %g
double
8
1.7e–308 to 1.7e+308
%lf
long double
10
3.4e–4932 to 1.1e+4932
%lf
09-Computer_Program-09.indd 277
3/11/2011 11:57:22 AM
Computer Programming
278
9.10 DECLARING VARIABLES The declaration of variables should be done in the declaration part of the program. The variables must be declared before they are used in the program. Declaration provides two things: (1) Compiler obtains the variable name and (2) It tells the compiler about the data type of the variable being declared and helps in allocating the memory. The syntax of declaring a variable is as follows: Syntax Data_type variable_name Example: int age; char m; float s; double k; int a,b,c;
The int, char, float, and double are keywords to represent data types. Commas separate the variables, if variables are more than one. Table 9.10 shows various data types and their keywords used in C. Table 9.10 Data Types and Their Keywords Data Types
Keyword
Character
char
Signed character
signed char
Unsigned character
unsigned char
Integer
int
Signed integer
signed int
Unsigned integer
unsigned int
Unsigned short integer
unsigned short int
Signed long integer
signed long int
Unsigned long integer
unsigned long int
Floating point
float
Double floating point
double
Extended double floating point
long double
9.11 INITIALIZING VARIABLES Variables declared can be assigned or initialized using an assignment operator ‘=’. The declaration and initialization can also be done in the same line. Syntax variable_name = constant or data_type variable_name= constant
09-Computer_Program-09.indd 278
3/11/2011 11:57:22 AM
The C Declarations
279
Example: x=2; where x is an integer variable. int y=2; int x,y,z;x=y=z=5;
The third example of initialization is also a valid statement. One or more variables can be initialized. A programming example on initialization of a variable is given below 9.2 Write a program to declare, initialize variable and display. void main() { int age=20; float height=5.4; char sex=‘M’; clrscr(); printf(“Age :%d \nFloat : %g \nSex : %c”,age,height,sex); } OUTPUT Age :20 Float : 5.4 Sex : M
Explanation In the above program, int, float, and char variables are declared and values are assigned. Using printf() statement, values are displayed. 9.3 Write a program to swap two numbers using a third variable.
Algorithm for swapping two numbers: STEP 1: Start. STEP 2: Declare variables a, b, & c. STEP 3: Read values of a & b. STEP 4: Copy value of a to c; b to a; & c to b. STEP 5: Print swapped values of a & b. STEP 6: Exit. Program: void main() { int a,b,c; clrscr(); printf(“\nEnter two numbers for A & B:”); scanf(“%d %d”,&a,&b); c=a; a=b; b=c; printf(“\nAfter swaping the values are:A=%d & B=%d.”,a,b); getch(); }
09-Computer_Program-09.indd 279
Flowchart for swapping two numbers: START
Declare variables a, b, c.
Enter the values of a&b
c = a; a = b; b = c;
Print a, b
END
3/11/2011 11:57:23 AM
Computer Programming
280
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 printf( ) statement prints the values of a & b.
9.4 Write a program to swap two numbers without using a third variable.
Algorithm: STEP 1: Start. STEP 2: Declare two variables a & b. 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. STEP 6: Print values of a & b. STEP 7: End. Program:
Flowchart: START
Declare variables & assign values to a & b.
void main() { int a=4,b=6; clrscr(); a=a+b; b=a-b; a=a-b; printf(“\nthe value of a=%d & b=%d”,a,b); getch(); }
a = a + b; b = a b; a = a b;
Print values of a & b
OUTPUT: The value of a=6 & b=4 END
Explanation: In the above cited program, first two variables a & b are declared and initialized. Values of a & b are added in the statement a = a + b. In the next statement, b is subtracted from a and result is stored in b. Finally, the value of a is obtained by subtracting b from a. The printf( ) statement prints the values of a & b.
09-Computer_Program-09.indd 280
3/11/2011 11:57:25 AM
The C Declarations
281
9.12 DYNAMIC INITIALIZATION The initialization of variable at run time is called dynamic initialization. Dynamic refers to 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. 9.5 Write a program to demonstrate dynamic initialization. void main() { int r=2; float area=3.14*r*r; clrscr(); printf(” Area=%g “,area); } OUTPUT Area=12.56
Explanation In the above program, area is calculated and assigned to variable area.The expression is solved at run time and assigned to area at run time. Hence, it is called dynamic initialization.
9.13 TYPE CONVERSION Sometimes, the 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 execution of the following program. 9.6 Write a program to change data type of results obtained by division operations. void main() { clrscr(); printf(“\n printf(“\n printf(“\n printf(“\n }
Division operation\t\tResult”); Two Integers (5 & 2) \t\t: %d”,5/2); One int & one float (5.5 & 2)\t: %g”,5.5/2); Two Integers (5 & 2)\t\t: %g”,(float)5/2);
OUTPUT: Division operation Two Integers (5 & 2) One int & one float (5.5 & 2) Two Integers (5 & 2)
09-Computer_Program-09.indd 281
Result : 2 : 2.75 : 2.5
3/11/2011 11:57:25 AM
282
Computer Programming
Explanation In the first division operation, data types are chosen as integers. 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 division 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. A programmer can specify any data type.
9.14 CONSTANT AND VOLATILE VARIABLES (a) Constant variable If we want the value of a certain variable to remain the same or remain unchanged during the execution of a program, it can be done only by declaring the variable as a constant. The keyword const is added before the declaration. It tells the compiler that the variable is a constant. Thus, variables that are declared as constant are protected from modification. Example: const int m=10; Where, const is a keyword, m is a variable name, and 10 is a constant value. The compiler protects the value of ‘m’ from modification. The user cannot assign any value to m, but using scanf() statement the value can be replaced. 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 the user attempts to modify the value of constant variable, the message ‘cannot modify the constant object in function main’ will be displayed.
9.7 Write a program to assign a constant value to const and make an attempt to change its value. void main() { const int m=12; ++m; printf(“%d”,m); getche(); }
The above program code will not be executed and end with error message. Here, an attempt is made to modify a constant’s value. (b) Volatile variable The volatile variables are those variables that are changed at any time by other external program or the same program. The syntax is as follows: volatile int d;
09-Computer_Program-09.indd 282
3/11/2011 11:57:25 AM
The C Declarations
283
If the value of a variable in the current program is to be maintained constant and desired not to be changed by any other external operation, then the declaration of variable will be as follows: volatile const d=10; 9.8 Write a program to use volatile variable and make an attempt to change its value void main() { volatile num=10; num=num–1; printf(“%d”,num); getche(); } OUTPUT: 9
Explanation: In this program, num is a volatile variable. Its value is initially declared as 10.The value can be changed and the changed value is 9 and is displayed in the output.
9.9 Write a program to use const with volatile variable and make an attempt to change its value and see the response of the compiler. void main() { volatile const num=12; num=num–1; printf(“%d”,num); getche(); } OUTPUT: The message ‘cannot modify the constant object in displayed due to use of const.
function main’ will be
Explanation: In this program, with volatile and const keywords num is initialized with 12. The value cannot be changed later as constant value is assigned to the num. If any attempt is made to change a constant value, the compiler shows the error.
09-Computer_Program-09.indd 283
3/11/2011 11:57:25 AM
Computer Programming
284
summary Having studied the basics in the previous chapter, the reader is now exposed to the additional fundamentals of C. These things are absolutely essential for writing programs. The reader is made aware of the following points: • • • • • •
Different types of characters like letters, digits, white space, and special characters Various delimiters used with C statements, keywords, and identifiers Different constants, variables, and data types Rules for defining variables and initializing them Type conversion of variables Constant and volatile variables
EXERCISES A. Answer the following questions. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.
What are the different data types? What are the differences between signed and unsigned data types? What is meant by a variable and a constant? Explain different types of constants in C. What are C keywords? Elaborate them. List the rules for declaring a variable. What are identifiers? Explain the methods for initialization of variables. Explain constants and volatile variables. Write about space requirement for variables of different data types. What are delimiters? Explain their uses. Is main a keyword? Explain. List any three keywords with their use. What is the difference between %f and %g format specifiers? Can both be used for representing float numbers? 15. What do you mean by type conversion? Why is it necessary? 16. What is dynamic initialization? B. Select the appropriate option for each of the following questions. 1. A character variable can store only (a) 1 character (c) 254 characters
09-Computer_Program-09.indd 284
(b) 20 characters (d) none of the above
3/11/2011 11:57:25 AM
The C Declarations
2. C variable cannot start with (a) a number (b) (c) a character (d) 3. A short integer variable occupies memory (a) 2 byes (b) (c) 1 byte (d) 4. C keywords are reserved words by (a) a compiler (b) (c) header file (d) 5. The declaration of C variable can be done (a) anywhere in the program (b) (c) in executable part (d) 6. In C, one statement can declare (a) only one variable (b) (c) ten variables (d) 7. The word ‘int’ is a (a) keyword (b) (c) header file (d) 8. The variables are initialized using (a) greater than (>) (b) (c) twice equal to (==) (d) 9. An unsigned integer variable contains values (a) greater or equal to zero (b) (c) only zeros (d) 10. The keyword ‘const’ keeps the value of a variable (a) constant (b) (c) variant (d) 11. Identifiers are (a) user-defined names (b) (c) C statements (d) 12. In C, every variable has (a) a type (b) (c) a value (d) 13. The range of character data type is (a) –128 to 127 (b) (c) 0 to 32767 (d) 14. The keyword ‘volatile’ keeps the value of variable (a) constant (b) (c) variant (d) 15. Which is an incorrect variable name? (a) else (b) (c) age (d)
09-Computer_Program-09.indd 285
285
an alphabet none of the above 4 bytes 8 bytes an interpreter (b) & (c) in declaration part at the end of the program two variables any number of variables password none of the above equal to (=) an increment operator (++) less than zero (a) & (b) both mutable none of the above reserved keywords none of the above a name a size
(e) all of the above
0 to 255 none of the above mutable none of the above name cha_r
3/11/2011 11:57:25 AM
Computer Programming
286
16. How many keywords are there in ANSI C? (a) 32 (b) 33 (c) 42 (d) 15 17. How many variables can be initialized at a time? (a) one (b) two (c) five (d) any number of variables. 18. Which of the following statements is wrong? (a) 5+5=a; (b) ss=12.25; (c) st=‘m’ * ‘b’; (d) is =‘A’+10; 19. The ANSI standard recognizes the maximum length of a variable up to (a) 31 characters (b) 8 characters (c) 25 characters (d) unlimited characters 20. The variable name can be started with (a) underscore symbol (_) (b) asterisk symbol (*) (c) ampersand symbol (&) (d) none of the above 21. What is the output of the following program? void main() { unsigned long v=–l; clrscr(); printf(“\n %lu”,v); }
(a) 4294967295 (c) –1 22. What would be the values of variable c and u?
(b) 0 (d) None of the above
void main() { char c=–127; unsigned char u=–127; clrscr (); printf(“\n c=%d u= %d”,c,u); }
(a) c=127 u=127 (b) c= –1.27 u=127 (c) c=127 u=128 (d) None of the above 23. An unsigned integer variable in C occupies a memory size of (a) 2 bytes (b) 4 bytes (c) 1 byte (d) 8 bytes 24. In C, double variable needs a memory of size (a) 4 bytes (b) 2 bytes (c) 10 bytes (d) All of the above
09-Computer_Program-09.indd 286
3/11/2011 11:57:25 AM
The C Declarations
25. In C, main () is a (a) function (c) string function 26. The word ‘continue’ in C is a (a) keyword (c) header file
287
(b) user-created function (d) any number of variables (b) password (d) none of the above
C. What will be the output of the following programs? 1 void main() { char c=65; clrscr(); printf(“%c %d”,c,c); } OUTPUT A 65
2 void main() { unsigned char c=122; clrscr(); printf(“%d %c %x %o ”,c,c,c,c); getche(); } OUTPUT 122 z 7a 172
3 void main() { unsigned u=2147483647; long l=2147483647; clrscr(); printf(“\n u=%u l=%ld”,u,l); } OUTPUT u=65535 l=2147483647
09-Computer_Program-09.indd 287
3/11/2011 11:57:25 AM
Computer Programming
288
4 void main() { float a=30e–1,b=25e–2; clrscr(); printf(“a=%g b=%g”,a,b); getche(); } OUTPUT a=3 b=0.25
5 void main() { int x,a=1e1, b=0; clrscr(); b+=1e1; printf(“a= %d b=%d”,a,b); } OUTPUT a=10
b=10
E. Find the bug(s) in the following programs. 1 void main() { clrscr(); printf(“\n %d”, 7/2); printf(“\n%g”,7.0/2); printf(“\n%g”, float7/2); getche(); } ANSWER float must be enclosed within brackets then the answer will be 3 3.5 3.5
09-Computer_Program-09.indd 288
3/11/2011 11:57:25 AM
The C Declarations
289
2 void main() { volatile d=15; const p=25; clrscr(); printf(“%d %d”d+10,p+1); getche(); } Answer Missing, (comma) in the printf(). Answer after correction 25 26
3 void main() { unsigned int d=65535; unsigned char p=65; clrscr(); printf(“%c %c”,d,p); getche(); } Answer First %c is to be replaced by %u Then the answer will be 65535 A
4 void main() { float d=65535.43; double p=65789.987654; clrscr(); printf(“%d %d”,d,p); getche(); } OUTPUT Control string provided is wrong. %f and %lf are needed. Answer on correction will be 65535.429688 65789.987654
09-Computer_Program-09.indd 289
3/11/2011 11:57:26 AM
290
Computer Programming
5 void main() { float d=1234567.43; double p=987654321.1234567; clrscr(); printf(“\n%f %lf”,d,p); printf(“\n%d %d”,size of(d),size of(p)); getche(); } Answer Space between size and of should be removed. The answer will be 1234567.375000 987654321.123457 4 8
6 # define N= 90 void main() { int x=10,p; clrscr(); p=x*N; printf(“\n%d ”, p); getche(); } Syntax error in the first line # define. Remove =. Answer will be 900
09-Computer_Program-09.indd 290
3/11/2011 11:57:26 AM
Chapter
10
Operators and Expressions Chapt e r O u t lin e 10.1 Introduction
10.5 Arithmetic Operators
10.2 Properties of Operators
10.6 Relational Operators
10.3 Priority of Operators and their Clubbing
10.7 Logical Operators
10.4 Comma and Conditional Operator
10.8 Bitwise Operators
10.1 INTRODUCTION In order to perform different kinds of operations, C uses different kinds of operators. An operator indicates an operation to be performed on data that may yield a new value. An operator can operate on character, integer, floating point numbers, or others. Using various operators in C, one can link the variables and constants. In other words, operators perform operations on operand/s, whereas operand is a data item on which the operation is performed depending upon the operator. C is rich in use of different operators. C provides four classes of operators. These are (1) arithmetic, (2) relational, (3) logical, and (4) bitwise. Apart from these basic operators, C also supports additional operators such as increment, decrement, conditional, assignment, among others. The basic operators and others along with their symbolic representation are shown in Table 10.1.
10-Computer_Program-10.indd 291
3/11/2011 5:46:37 PM
Computer Programming
292
Table 10.1 Types of Operators Type of Operator
Symbolic Representation
Arithmetic operators
+, -, ∗, / and %
Relational operators
>, =, ,
Right shift
=
Greater than or equal to
==
Equality
Left to right
7th
!=
Inequality
&
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
ˆ=, !=, = etc
Assignment Operators
Right to left
14th
,
Comma operator
Right to left
15th
(1) When two operators of the same priority are found in the expression, precedence is given to the extreme left operator. For example x=
5
*
4
+
8
/
2; 2
1
3
Here, 5∗4 is solved first. Though ∗ and / have the same priorities. The operator ∗ occurs before /.
(2) If there are more sets of parenthesis in the expression, the innermost parenthesis will be solved first, followed by the second and so on.
10-Computer_Program-10.indd 294
3/11/2011 5:46:38 PM
Operators and Expressions
295
For example
Here, (a) Innermost bracket is evaluated first, i.e. 2∗2=4. (b) Second innermost bracket is then evaluated. 2 is multiplied with result of innermost bracket. The answer of 2∗4=8. (c) Then the outer most is evaluated. 8 is divided by 8 and gives result 1. For example
Here, in this assumed example, priorities of operations are shown. Following program 10.1 is provided for understanding the concepts of precedence of operators.
10.1 Write a program to demonstrate the precedence of operator. void main() { int a=1,b=2,c=6,j; clrscr(); j=a∗b+c/b; printf(“\n j=%d”,j); j=(a+(b∗c)); printf(“\n j=%d”,j); getche(); } OUTPUT j=5 j=13
10-Computer_Program-10.indd 295
3/11/2011 5:46:39 PM
296
Computer Programming
Explanation: In this program, in the statement j=a*b+c/b, Multiplication is performed first, then division and at last addition. j=(a+(b*c));in this statement the priority is assigned firstly to the parenthesis. First multiplication operation is performed followed by it addition operation, hence value of j is13.
10.4 COMMA AND CONDITIONAL OPERATOR (a) 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 parenthesis. For example the statements given below are valid. For example a=2,b=4,c=a+b; (a=2,b=3,c=a+b;) The program given below illustrates the use of a comma operator.
Example 10.1
Write a program to illustrate the use of comma (,) operator. void main() { clrscr(); printf(“Addition = %d\nSubtraction = %d”,2+3,5-4); } OUTPUT: Addition = 5 Subtraction = 1
Explanation In the above program the two equations are separated by a comma. The results are obtained by solving the equations separated by a comma. The result is printed through printf() statement.
(b) Conditional operator (?) The conditional operator contains a condition followed by two statements or values. If the condition is true the first statement is executed, otherwise the second statement. The conditional operator (?) and (:) are sometimes called ternary operators because they take three arguments. The syntax of conditional operator is as given below.
10-Computer_Program-10.indd 296
3/11/2011 5:46:39 PM
Operators and Expressions
297
Syntax Condition ? (expression1): (expression2); Two expressions are separated by a colon. If the condition is true expression 1 gets evaluated, otherwise expression 2. The condition is always written before? mark. The program given below illustrates the use of a conditional operator.
Example 10.2
Write a program to use the conditional operator with two values. void main() { clrscr(); printf(“Result = %d”, 2= =3? 4:5); } OUTPUT: Result=5
Explanation In the above program the condition 2= =3 is false. Hence, 5 is printed.
10.5 ARITHMETIC OPERATORS There are two types of arithmetic operators: (a) binary operator and (b) unary operator. (a) Binary operator Table 10.3 shows different arithmetic operators that are used in C. These operators are commonly used in most of the computer languages. These arithmetic operators are used for numerical calculations between two constant values. They are also called as binary arithmetic operators. The examples are also shown in the Table 10.3. In the program, variables are declared instead of constants. Table 10.3 Binary Arithmetic Operators
10-Computer_Program-10.indd 297
Binary Arithmetic Operators
Operator Explanation
Examples
+
Addition
2+2=4
-
Subtraction
5-3=2
/
Division
10/2=5
%
Modular Division
11%3=2 (Remainder 2)
3/11/2011 5:46:39 PM
Computer Programming
298
(b) Unary operators Unary operators are increment operator (++), decrement operator (--), and minus (-). These operators and their descriptions are given in Table 10.4. Table 10.4 Unary Arithmetic Operators Operator
Description or Action
-
Minus
++
Increment
--
Decrement
&
Address Operator
sizeof
Gives the size of operator
Minus (-) Unary minus is used to indicate or change the algebraic sign of a value. For example int x= -50; int y= -x;
assigns the value of -50 to x and the value of –50 to y through x. The – 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. Increment(++) & Decrement(––) Operators The C compilers produce very fast, efficient object codes for increment and decrement operations. This code is better than that generated by using the equivalent assignment statement. So, increment and decrement operators should be used whenever possible. The operator ++ adds one to its operand. Whereas the operator –– subtracts one from its operand. For justification in C the statement 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+l; can be represented as x++; or ++x; If ++ or –– are used as a suffix to the variable names then the post increment/decrement operations take place. Consider an example for understanding ++ 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 increased 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 increased and then used for multiplication. The result is 220, which is assigned to ‘z’. The following programs can be executed for verification of increment and decrement operations.
10-Computer_Program-10.indd 298
3/11/2011 5:46:39 PM
Operators and Expressions
299
Example 10.3
Write a program to show the effect of increment operator as a suffix. void main() { int a,z,x=10,y=20; clrscr(); z=x∗y++; a=x∗y; printf(“\n%d %d”,z,a); } OUTPUT: 200 210
Explanation In the above program the equation z=x*y++ gives the result 200, because ‘y’ does not get increased. After multiplication ‘y’ increases to 11.The second equation gives result 210.This can be verified by executing the above program.
Example 10.4
Write a program to show the effect of increment operator as a prefix. void main() { int a,z,x=10,y=20; clrscr(); z=x∗++y; a=x∗y; printf(“\n%d %d”,z,a); } OUTPUT: 210 210
Explanation In the above program ‘y’ gets increased first and the equations are solved. Here both the equations give the same result, i.e. 210. sizeof() and ‘&’ Operator The sizeof() operator gives the bytes occupied by a variable. 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 example given below illustrates the use of both the operators.
10-Computer_Program-10.indd 299
3/11/2011 5:46:40 PM
Computer Programming
300
Example 10.5
Write a program to use ‘&’ and sizeof() operator and determine the size of integer and float variables. void main() { int x=2; float y=2; clrscr(); printf(“\n sizeof(x)=%d bytes”,sizeof(x)); printf(“\n sizeof(y)=%d bytes”,sizeof(y)); printf(“\n Address of x=%u and y=%u”,&x,&.y); } OUTPUT: sizeof(x)=2 sizeof(y)=4 Address of x=4066 and y=25096
Explanation In the above example variables x and y are declared and initialized.The variable x is an integer and y is a float data type. Using sizeof() and ‘&’ operator, their sizes and addresses can be displayed.
10.6 RELATIONAL OPERATORS These operators are used to distinguish between two values depending on their relations. These operators provide the relationship between the two expressions. If the relation is true then it returns a value 1, otherwise 0 for false relation. The relational operators together with their descriptions, example and return value are described in Table 10.5. Table 10.5 Relational Operators Operator
Description or Action
Example
Return Value
>
Greater than
5>4
1
=10); printf(“\n103 && 55 ¦¦ 83 && 53 && 55 | | 85||83 && 55 | | 8>
Right shift
>=2; y=x; printf(“The Right shifted data is = %d”,y); } OUTPUT: Read The Integer from keyboard (x):-8 The Right shifted data is = 2
Before the execution of the program: - The number entered through the keyboard is 8 and its corresponding binary number is 1 0 0 0.
0 15
0 14
0 13
0 12
0 11
0 10
0 09
0 08
0 07
0 06
0 05
0 04
1 03
0 02
0 01
0 0
After execution of the program: - as per the above program the input data x is to be shifted by 2 bits right side. The answer in binary bits would be as follows.
0 15
0 14
10-Computer_Program-10.indd 304
0 13
0 12
0 11
0 10
0 09
0 08
0 07
0 06
0 05
0 04
0 03
0 02
1 01
0 0
3/11/2011 5:46:40 PM
Operators and Expressions
305
Shifting two bits right means the input number is to be divided by 2s where s is number of shifts, that is, in short y=n/2s, where, n = Number s = Number of position to be shifted. As per the program cited above, Y = 8/22 = 2. Similarly, a program for shifting to the left can be written as follows.
Example 10.10
Write a program to shift inputed data by three bits left. void main() { int x,y; clrscr(); printf(“Read The Integer from keyboard (x):-”); scanf(“%d”, &x); x 2? (a) 4 (b) 8 (c) 2 (d) 5 What is the result of 5&&2? (a) 0 (b) 1 (c) 2 (d) 5 What will be the value of c after execution of the program? void main() { int a,b,c; a=9; b=10 ; c=(b> is the relational operator >= is the binary operator != is the relational operator The logical AND (&&) operator provides true result when both expressions are true The logical NOT operator (!) provides 0 if the condition is true otherwise 1 The logical OR (¦¦) operator provides false result when one of the expressions is true Bitwise EX-OR operation is performed by operator &. One’s complement is performed by operator ~. Bitwise OR is performed by operator ¦
1. F 2. T 3. T 4. T 5. F 6. F 7.T 8. T 9. F 10. F 11. F 12. T 13. T
10-Computer_Program-10.indd 316
3/11/2011 5:46:41 PM
Chapter
11
Input and Output in C Chapt e r O u t lin e 11.1 Introduction
11.5 Unformatted Functions
11.2 Input and Output Functions
11.6 Commonly used Library Functions
11.3 Formatted Functions 11.4 Flags, Width, and Precision with the Format String
11.1 INTRODUCTION Reading data from input devices, processing it, and displaying the results on the screen are the three tasks of any program. The data are read from the input device such as keyboard, operations on the data are performed based on the operators, and the results are displayed on the screen. All the three tasks cited above are important and none of them should 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. An example of an assignment statement is given in Chapter 10 and can be found in the ensuing chapters too. Assignment to the variables can be as follows: (1) int year=2005; (2) char letter=‘a’; (3) long int x=123456; etc.
11-Computer_Program-11.indd 317
3/9/2011 2:47:06 PM
Computer Programming
318
Another way to accept the data is with C, functions. In C, the input and output functions can be used for inputting the data and displaying the results respectively. In order to carry out these tasks, user-friendly C, has a number of input and output functions. When a program needs data, it takes the data through the input functions and sends the results after computation through the output functions. Thus, the input/output (I/O) functions are the link between the user and the terminal. Streams perform all input and output operations. They are nothing but sequence of bytes. When a program performs input and output operations, the streams are connected to the program 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.
11.2 INPUT AND OUTPUT FUNCTIONS There are a number of I/O standard functions in C, based on the data types. The I/O functions are classified into two types: a) formatted functions and b) unformatted functions. Various functions of these categories are listed in Figure 11.1.
Input and Output Functions
Formatted Functions
printf( ) scanf( )
Unformatted Functions
getch( ) getche( ) getchar( ) gets( ) putch( ) putchar( ) puts( )
Figure 11.1 Formatted and Unformatted Functions
(a) Formatted functions With formatted functions, the input data or output results are formatted as per requirement. They improve the readability of the I/O. For example, with formatted functions one can decide how the result should be displayed on the screen. Formatted functions take care of the appearance of the results. For example, the result can either be displayed in the second line or after leaving some space; if the result is a real number then a decision can be made even on number of digits before and after the decimal point. All I/O functions are defined in stdio.h header file, which can be initialized at the start of a program. The formatted I/O functions can be used to read and write all types of data values. They require a format specifier to identify the data type. The formatted functions return the 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 errors occurring during reading or writing the data.
11-Computer_Program-11.indd 318
3/9/2011 2:47:06 PM
Input and Output in C
319
Using this function, the given numeric data can be represented in floating point, integer, and double integer to the available limits of the language. The syntax of the input function for inputting the data is scanf(). Example: scanf(“control string”, address of variable 1,address of variable 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); 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 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. For displaying the result, prinf() formatted function is used. In Section 11.3, prinf() and scanf() are discussed in depth. Table 11.1 provides formatted and unformatted I/O functions. (b) Unformatted functions Formatting is not possible with unformatted functions. The unformatted I/O functions only work with character data types. They do not require format specifiers for identification of data types because they work only with character data types. There is no need to convert the data. In case values of other data types are passed to these functions, they are treated as character data. The unformatted functions also return values, but the returned value of unformatted functions is always the same. Table 11.1 Formatted and unformatted I/O functions. Formatted Functions
Unformatted Functions
Input
Output
Input
Output
scanf()
printf()
getch()
putch()
getche()
putchar()
getchar()
put()
gets()
11.3 FORMATTED FUNCTIONS (a) The printf() statement The printf() function prints all types of data values to the console. It requires format specifiers and variable names to print the data. The format specifiers and variable names should be same in number. An example of a printf() statement is given below.
11-Computer_Program-11.indd 319
3/9/2011 2:47:06 PM
320
Computer Programming
Example void main() { int x=2; float y=2.2; char z=’C’; printf(“%d %f %c”,x,y,z); } OUTPUT: 2 2.2000 C
In the above program, %d format specifier corresponds to ‘x’ variable, %f to ‘y’, and %c to ‘z’. The conversion symbol given by the user helps printf() to identify the data type of the given variable. If mismatch occurs, the value of the variable is converted according to the conversion symbol given.. Example int main() { int y=65; clrscr(); printf(“%c %d”,y,y ); return 0; } OUTPUT: A 65
In the above example, the integer variable ‘y’ contains value 65. The variable ‘y’ is printed using two format specifier symbols, integer and character. As shown in the output, the %c converts numeric value 65 to its corresponding character A. The %d prints the value 65 as it is, because the variable is of integer type. Sometimes if no conversion is possible between two data types, some garbage value is printed.
Example int main() { int y=7; clrscr(); printf(“%f”,y ); return 0; }
In the above example, we forced the printf statement to print the integer value as float value providing %f as a conversion symbol or format specifier. This is not the proper way. While compiling no error occurs, but after execution the printf() function will produce an error message “floating points formats not linked”.
11-Computer_Program-11.indd 320
3/9/2011 2:47:06 PM
Input and Output in C
321
(b) 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 a program. The syntax of the scanf() statement is same as printf() except that they work exactly opposite.
Syntax 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 shown. Otherwise, if the read value is converted to the given format, conversion is made. The following program is an example of such a mismatch case.
Example 11.1
Write a program to show the effect of mismatch of data types. void main() { int a ; clrscr(); printf(“Enter value of ‘A’:”); scanf(“%c”,&a); printf(“A=%c”,a); } OUTPUT: Enter value of ‘A’: 8 A=8
Explanation In the above program, though the type of variable a is int, it perfectly works with the conversion symbol of the character, i.e., character and integer data types are compatible to each other. When two data types are compatible to each other, then the compatible range is equal to the lowest range from the two data types. The above example illustrates this point.
Example 11.2
Write a program to read and print the integer value using character variable. void main() { char a; clrscr();
11-Computer_Program-11.indd 321
3/9/2011 2:47:06 PM
Computer Programming
322
printf(“Enter value of ‘A’:”); scanf(“%d”,&a); printf(“A=%d”,a); } OUTPUT: Enter value of ‘A’: 255 A=255 Enter value of ‘A’: 256 A=0
Explanation In the above program, variable a is of character type, i.e., its valid range is 0 to 255. The variable a is used with conversion symbol of integer data type, i.e., in the printf() and scanf() statement the variable a is supposed to be integer type. The value read in 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 character type. In such case, the excess range is again considered as a beginning or a starting point. Here, the 256 is excess by 1. That is why 0 is printed.
The printf() and scanf() statements follow different data types listed in Tables 11.2 and 11.3. Conversion symbols for each data type are also shown in the same tables. Table 11.2 Fundamental Data types with Conversion Symbols/format specifiers Fundamental Data Types
Data Type
Conversion Symbol
Integer
short integer
%d or %i.
short unsigned
%u
long signed
%ld
long unsigned
%lu
unsigned hexadecimal
%X or %x
unsigned octal
%o
float
%f or %g
double
%lf
signed character
%c
unsigned character
%c
string
%s
Real Character
Table 11.3 Data types with Conversion Symbols/format specifiers
11-Computer_Program-11.indd 322
Date Type
Conversion Symbol
Octal number
%o
Displays hexadecimal number in small case
%hx
Displays hexadecimal number in upper case
%p
Aborts program with error
%n
3/9/2011 2:47:07 PM
Input and Output in C
323
The printf() and scanf() statements follow a combination of characters called as escape sequences. Escape sequences are special characters starting with ‘\’ (backslash). They are used to break the normal sequence of a computer. For example, with \n new line is selected. They are given in Table 11.4 Table 11.4 Escape Sequences with Their ASCII Values Escape Sequence
Use
ASCII Value
\n
New line
010
\b
Backspace
008
\f
Form feed
012
\’
Single quote
039
\\
Backslash
092
\0
Null
000
\t
Horizontal Tab
009
\r
Carriage Return
013
\a
Alert (Bell)
007
\”
Double quote
034
\v
Vertical tab
011
\?
Question Mark
063
The programs illustrated below use printf() and scanf() statements.
Example 11.3
Write a program to print the third power of 2 using pow() function. Assume the floating point numbers. void main() { double x = 2.0, y = 3.0; clrscr(); printf(“%lf raised to %lf is %lf\n”, x, y, pow(x,y)); } OUTPUT: 2.000000 raised to 3.000000 is 8.000000
Explanation In the above program, two variables, x and y are declared and initialized. In the printf() statement using pow() function, expression xy(23) is calculated and displayed.
11-Computer_Program-11.indd 323
3/9/2011 2:47:07 PM
324
Computer Programming
Example 11.4
Write a program to calculate average of three real numbers. void main() { float a,b,c,d; clrscr(); printf(“\n ENTER THREE FLOAT NUMBERS:\n”); scanf(“\n %f%f%f”, &a,&b,&c); d=a+b+c; printf(“\n Average of Given Numbers: %f”,d/3); } OUTPUT: ENTER THREE FLOAT NUMBERS: 2.5 3.5 4.5 Average of Given Numbers: 3.5
Explanation In the above program, three float values are assigned to the variables a, b, and c. Sum of these variables is assigned to d. By dividing the sum by three, the average is calculated and displayed.
11.4 FLAGS, WIDTH, AND PRECISION WITH THE FORMAT STRING We can also insert flags, width, and precision with the format string. Flags: Flags are used for output justification, numeric signs, decimal points, trailing zeros, etc. The flag (−) left justifies the result. If it is not given, the default is right justification. The (+) signed conversion result always starts with a plus or minus sign. Width Specifier: It sets the minimum field width for an output value. Width can be specified through a decimal point or using asterisk, ‘*’. A few programs are provided on width requirement.
Example 11.5
Write a program to demonstrate the use of width specifier. void main() { clrscr(); printf(“\n%.2s”,“abcdef”); printf(“\n %.3s”,“abcdef”); printf(“\n %.4s”,“abcdef”); }
11-Computer_Program-11.indd 324
3/9/2011 2:47:07 PM
Input and Output in C
325
OUTPUT ab abc abcd
Explanation Observe the above program carefully and watch the width specified along with the conversion specification character, %s. Though the actual string length is 6 characters the number of printed characters as per printf() statements are 2, 3, and 4 respectively.
Example 11.6
Write a program to demonstrate the use of width specifier. void main() { int x=55,y=33; clrscr(); printf(“\n %3d”,x−y); printf(“\n %6d”,x−y); } OUTPUT 22 22
Explanation In this program, in the first printf() statement width is given as 3 and in the second, width is given as 6. Hence, the results are displayed at different positions on the screen.
Example 11.7
Write a program to demonstrate use of ‘*’ for formatting. void main() { int x=55,y=33; clrscr(); printf(“\n %*d”,15,x−y); printf(“\n %*d”,5,x−y); } OUTPUT 22 22
11-Computer_Program-11.indd 325
3/9/2011 2:47:07 PM
Computer Programming
326
Explanation In this program, the ‘*’ is used along with the format string or conversion specification character, %d. An extra parameter is required to set the starting column for printing. This value is given along the set of variables. You can observe that in the printf() statements the values 15 and 5 indicate the position from where printing on screen begins. Precision specifiers: Precise results on screen can be obtained. The precision specifier always starts with a period or dot in order to separate it from any preceding width specifiers. Consider the following program: Example 11.8
Write a program to demonstrate the use of precision specifiers. void main() { float g=123.456789; clrscr(); printf(“\n %.1f”,g); printf(“\n %.2f”,g); printf(“\n %.3f”,g); printf(“\n %.4f”,g); } OUTPUT 123.5 123.46 123.457 123.4568
Explanation In the above program the precision value is specified before format string. Fractional part after decimal point can be precisely shown in various printf() statements. The output shows these numbers.
From the above examples, it is now clear that outputs can be shown in different formats. Table 11.5 describes the various formats for presenting various outputs. Table 11.5 Formats for Various Outputs Sr.No.
Format
Meaning
Explanation
1
%wd
Format for integer output
W, width in integer and d, conversion specification
2
%w.cf
Format for float numbers
W, width in integer, c, specifies number of digits after decimal point, and f, conversion specification
3
%w.cs
Format for string output
W, width for total characters, c, used for displaying leading blanks and s, conversion specification
11-Computer_Program-11.indd 326
3/9/2011 2:47:07 PM
Input and Output in C
327
A programming example is provided on the above formats for the understanding of the readers. Example 11.9
Write a program to display the integers, float point numbers, and string with different formats as explained above. void main() { clrscr(); printf(“\n%5d”,12); printf(“\n%5d”,123); printf(“\n%5d”,1234); printf(“\n printf(“\n printf(“\n printf(“\n
%4.5f”,6.12); %4.6f”,16.12); %4.7f”,167.12); %4.8f”,1678.12);
printf(“\n %8s”,”Amitkumar”); printf(“\n %8.2s”,”Amitkumar”); getche(); } OUTPUT:12 123 1234 6.12000 16.120000 167.1200000 1678.12000000 Amitkumar Am
An example is illustrated for a formatted input below. Example 11.10
Write a program to demonstrate the use of scanf() with different formats. void main() { int a,b; float x; char name[20]; clrscr();
11-Computer_Program-11.indd 327
3/9/2011 2:47:07 PM
Computer Programming
328
printf(“Enter two integers:-\n”); scanf(“%4d %4d”,&a,&b); printf(“\nEntered integers are”); printf(“\n%4d %4d”,a,b); printf(“\n”); printf(“\nEnter a real number :-\n”); scanf(“%f”,&x); printf(“\n Entered float number is”); printf(“\n%f”,x); printf(“\n”); printf(“\n Enter a string :-\n”); scanf(“%7s”,name); printf(“\n Entered string”); printf(“\n%7s”,name); getche(); } OUTPUT:Enter two integers:1 2 Entered integers are 1 2 Enter a real number :12.3 Entered float number is 12.300000 Enter a string :Deelipkumar Entered string Deelipk
Explanation In the scanf() statements, format for various inputs are taken. Similarly, the outputs are also provided with various formats.The readers can verify the input and output and are advised to another more programs.
11.5 UNFORMATTED FUNCTIONS C has three types of I/O functions. a) Character I/O b) String I/O c) File I/O a) Character I/O I. getchar() This function reads character type data from the standard input. It reads one character at a time till the user presses the enter key.
11-Computer_Program-11.indd 328
3/9/2011 2:47:08 PM
Input and Output in C
329
The syntax of getchar() is as follows: Variable name=getchar(); Example char c; c=getchar(); A program using getchar() function.
Example 11.11
Write a program to accept characters through keyboard using getchar() function. void main() { char c; clrscr(); printf(“\nEnter a char :”); c=getchar(); printf(“a=%c”,c); } OUTPUT Enter values :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 printf() statement.
Example 11.12
Write a program to accept characters through keyboard using getchar() function. void main() { char ch[20]; int c=0; clrscr(); while((ch[c]=getchar())!=‘\n’) c++; ch[c]=‘\0’; printf(“\n%s”,ch); } OUTPUT: COMPILER COMPILER
11-Computer_Program-11.indd 329
3/9/2011 2:47:08 PM
330
Computer Programming
Explanation In the above program, a character array is declared. Using the while loop continuously, characters are read through the keyboard using getchar() function till the user presses enter. Using printf() statement, the entered string is displayed. Note: For while loop, refer Chapter 13 on ‘Loop control statements’. II. putchar() This function prints one character on the screen at a time, which is read by the standard input. The syntax is as follows: putchar(variable name); Example char c=‘C’; putchar(c); A program is provided on putchar().
Example 11.13
Write a program to use putchar() in work. void main() { char c=‘C’; clrscr(); putchar(c); } OUTPUT C
Explanation In this program, the character variable c assigned char ‘C’ and the same is displayed by the putchar() statement. The argument c is used with putchar() statement.
Example 11.14
Write a program to print the characters using putchar() functions. void main() { char ch[20]; int c=0; clrscr();
11-Computer_Program-11.indd 330
3/9/2011 2:47:08 PM
Input and Output in C
331
printf(“\n Enter Text Here:”); scanf(“%s”,ch); printf(“\n The Entered Text:”); while(ch[c]!=‘\0’) { putchar(ch[c]); c++; } } OUTPUT: Enter Text Here : Characters The Entered Text : Characters
Explanation In the above program, the scanf() statement reads the string from the terminal.The putchar() function displays one character at a time on the console.The while loop causes repetitive execution of putchar() function and increases the counter c. Counter c is used to display the successive characters. When ‘\0’ is encountered, the program is terminated.
III. getch() and getche() These functions read the alphanumeric characters from the standard input device. The character entered is not displayed by getch() function.
Example 11.15
Write a program to show the effect of getche() and getch(). void main() { clrscr(); printf(“Enter any two alphabets”); getche(); getch(); } OUTPUT: Enter any two alphabets A
Explanation In the above program, even though the 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.
11-Computer_Program-11.indd 331
3/9/2011 2:47:08 PM
332
Computer Programming
IV. putch() This function prints any alphanumeric character taken by the standard input device. Example 11.16
Write a program to read and display the character using getch() and
putch().
void main() { char ch; clrscr(); printf(“Press any key to continue”); ch=getch(); printf(“\n You Pressed :”); putch(ch); } OUTPUT: Press any key to continue You Pressed: 9
Explanation The function getch() reads a key stroke and assigns to the variable ch. putch() displays the character pressed.
(b) String I/O I. gets() This function is used for accepting any string through stdin (keyboard) until enter key is pressed. Example 11.17
Write a program to accept string through the keyboard using gets() function. void main() { char ch[30]; clrscr(); printf(“Enter the String :”); gets(ch); printf(“\n Entered String: %s”, ch); } OUTPUT: Enter the String : USE OF GETS() Entered String : USE OF GETS()
Explanation In the above program, gets() reads string through the keyboard and stores it in character array ch[30]. The printf() function displays the string on the console.
11-Computer_Program-11.indd 332
3/9/2011 2:47:08 PM
Input and Output in C
333
II. puts() This function prints the string or character array. Example 11.18
Write a program to print the accepted character using puts() function. void main() { char ch[30]; clrscr(); printf(“Enter the String :”); gets(ch); puts(“Entered String :”); puts(ch); } OUTPUT: Enter the String: puts is in use. Entered String: puts is in use.
Explanation This program is same as the previous one. Here, to display the string puts() function is used.
III. cgets() This function reads string from the console. The syntax is given below. Syntax cgets(char *st); It requires character pointer as an argument. The string begins from st[2]. IV. cputs() This function displays string on the console. The syntax is given below. Syntax cputs(char *st);
Example 11.19
Write a program to read string using cgets() and display it using cputs(). void main() { static char *t; clrscr() printf(“\n Enter Text Here:”); cgets(t); t+=2;
11-Computer_Program-11.indd 333
3/9/2011 2:47:08 PM
Computer Programming
334
printf(“\n Your Entered Text:”); cputs(t); getche(); } OUTPUT: Enter Text Here: How are you? Your Entered Text: How are you?
Explanation In this example, character pointer t is declared. The cgets() function reads string through the keyboard and the cputs() function displays the string on the console.
(c) File I/O File I/O functions are described in detail in Chapter 22.
11.6 COMMONLY USED LIBRARY FUNCTIONS (a) clrscr(); This function is used to clear the screen. It clears the previous output from the screen and displays the output of the current program from the first line of the screen. It is defined in conio.h header file. The syntax is as follows: Syntax clrscr(); (b) exit(); This function terminates the program. It is defined in process.h header file. The syntax is as follows: Syntax exit(); (c) sleep(); This function pauses the execution of the program for a given number of seconds. The number of seconds is to be enclosed between parentheses. It is defined in dos.h header file. The syntax is as follows: Syntax sleep(1); (d) system(); This function is helpful in executing the different dos commands. It returns 0 on success and −1 on failure. The syntax is as follows: Syntax system(“dir”); The command should be enclosed within double quotation marks.
11-Computer_Program-11.indd 334
3/9/2011 2:47:08 PM
Input and Output in C
335
SUMMARY This chapter deals with formatted functions, such as printf() and scanf() statements.The unformatted 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. Few of the functions that are commonly used in the programs, such as clrscr() and exit() are described in this chapter.
EXERCISES A. Answer the following questions. 1. What are formatted and unformatted functions? 2. What is the difference between character I/O and string I/O? 3. What are escape sequences? 4. List any three escape sequences with their uses. 5. What is the difference between puts() and putch()? 6. What is the difference between getch() and getche()? 7. How is cgets() different from gets()? 8. How will you execute a dos command through C? 9. What is the use of exit() function? B. Select the appropriate options from the choices given below. 1. What will be the output of the following program? void main() { printf(“\n%d%d%d%d”,‘A’,‘B’,‘C’,‘D’); } (a) 65666768 (b) ABCD (c) 91929394 (d) none of the above 2. What will be the values of a and b after execution of the following program? void main() { int a, b; a=65*66; b=‘A’ *‘B’;
11-Computer_Program-11.indd 335
3/9/2011 2:47:08 PM
Computer Programming
336
clrscr(); printf(“a=%d b=%d”,a,b); }
3.
4.
5.
6.
7.
(a) a=4290 b=4290 (b) a=4290 b=AB (c) a=4290 b=0 (d) none of the above What function is appropriate for accepting a string? (a) gets( ) (b) getch( ) (c) getche( ) (d) scanf( ) What is the ASCII range for 0 to 9 digits? (a) 48 to 57 (b) 65 to 90 (c) 97 to 122 (d) none of the above What is the ASCII range for A to Z letters? (a) 65 to 90 (b) 48 to 57 (c) 97 to 122 (d) none of the above The escape sequence ‘\t’ is a (a) tab (b) next line (c) backspace (d) none of the above What would be the value of x on execution of the program? void main() { float x=2.3; clrscr(); x+=.2; printf(“%g”,x); }
(a) 2.5 (b) 4.3 (c) 4 (d) none of the above 8. What will be the output of the following program? void main() { system(“”); } (a) control goes to the dos prompt (b) syntax error (c) bad command or file name (d) none of the above 9. Which is the correct statement for finding the cube of 2? (a) pow(2,3); (b) pow(3,2); (c) pow(3); (d) none of the above 10. The abs() function displays (a) absolute value (b) negative value (c) zero value (d) none of the above
11-Computer_Program-11.indd 336
3/9/2011 2:47:09 PM
Input and Output in C
337
C. Attempt the following programs. 1. Write a program to input the rainfall of three consecutive days in CMS and find its average. 2. Find simple interest? Inputs are principal amount, period in years, and rate of interest. 3. Write a program to find total number of minutes in 12 hours. 4. Find the area and perimeter of a) square b) rectangle? Input the side(s) through the keyboard. 5. Accept any three numbers and find their squares and cubes. 6. The speed of a van is 80 km/hour. Find the number of hours required for covering a distance of 500 km? Write a program in this regard. 7. 8. 9. 10.
Write a program to convert inches to centimetres. Write a program to enter the name of this book and display it. Write a program to store and interchange two float numbers in variables a and b. Write a program to enter text with gets() and display it using printf() statement. Also find the length of the text. 11. Write a program to ensure that the difference between any two-digit number and its reverse (number interchanged) is always a multiple of nine. For example, entered number is 54 and its reverse is 45. The difference between them is 9. 12. Write a program to convert kilograms to grams. 13. Write a program to find the total amount when there are 5 notes of Rs.100, 3 notes of Rs.50, and 20 notes of Rs.20. 14. Write a program to enter the temperature in Fahrenheit and convert it to Celsius. Formula to be used is tc= ((tf−32)*5)/9 where tc and tf are temperatures in Celsius and Fahrenheit respectively. 15. Write a program to display list of C program files and directories. Use system() function to execute Dos commands. D. What is/are the output(s) of the following programs? 1 void main() } clrscr(); printf(“\n %o %hx %p”,45,65,65); } OUTPUT 55 37 0041
2 void main() { int x=67,y=68,z=69; clrscr();
11-Computer_Program-11.indd 337
3/9/2011 2:47:09 PM
Computer Programming
338
printf(“\n%c %c %c ”,x,y,z); getche(); } OUTPUT C D E
3 void main() { char str=“C Programming”; clrscr(); puts(str); getche(); } OUTPUT No Output
E. Find the bug(s) in the following programs. 1 void main() { int x=2; char y=’A’; float f=2.05; clrscr(); printf(“%d %c %f”,f,y,x); getche(); }
Bug: Formatted data cannot be displayed through unformatted functions. After putting them in sequence output will be 2 A 2.050000 2 void main() { int x; clrscr(); printf(“Enter a Number :”); scanf(“%d”,x); printf(“%d”,x); }
Bug: In scanf () & is not prefixed before variable name.
11-Computer_Program-11.indd 338
3/9/2011 2:47:09 PM
Input and Output in C
339
3 void main() { char x,d; clrscr(); printf(“Enter an alphabet:”);x=getchar(); }
Bug: No Bug. Warning “‘x’ is assigned a value which is never used” is displayed.
4 void main() { clrscr(); printf(“I \nam /n an\t Indian”); }
Bug: No Bug.
5 void main() { putchar(“x”); }
Bug: putchar () cannot be used to display string. Linker error will be shown.
F. Identify the following as to whether they are true or false. 1. 2. 3. 4. 5. 6. 7. 8. 9.
Formatted functions require format string to format the data. The function gets() is an unformatted function. The ‘\n escape sequence inserts a tab. Formatted functions return values. The function gets() is defined in . Any signed data type can have negative as well as positive values. The functions cgets() and cputs() work with character pointer as argument. While inputting values through scanf(), & is required before variable name. The getche () is used to read data character by character.
11-Computer_Program-11.indd 339
3/9/2011 2:47:09 PM
Computer Programming
340 10. 11. 12. 13. 14. 15. 16.
The char requires one byte space in the memory. ‘\a’ is the escape sequence for alert bell. The format string %g is used for float type. The %s is used to format the string. The format string %P is used to display hexadecimal in lower case. The %lf is used for long integer. ‘&’ is necessary in the printf() for displaying the result on the console.
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 16. F
11-Computer_Program-11.indd 340
3/9/2011 2:47:09 PM
Chapter
12
Decision Statements Chapt e r O u t lin e 12.1 Introduction
12.5 The goto Statement
12.2 The if Statement
12.6 The switch Statement
12.3 The if-else Statement
12.7 Nested switch case
12.4 Nested if-else Statement
12.8 The switch case and Nested If
12.1 INTRODUCTION A program is nothing but the execution of sequence of one or more instructions. In the monolithic program, the sequences of instructions are executed in the same order as they appear in the program. Quite often, it is desirable to alter the sequence of the statements in the program depending upon certain circumstances. In practical applications, there are numerous situations where one has to change the order of the execution of statements based on conditions. This involves a decision-making condition to see whether a particular condition is satisfied or not. Decision-making statements in a programming language help the programmer to transfer the control from one part to other part of the program. Thus, these decision-making statements facilitate the programmer in determining the flow of control. On the basis of applications it is essential to •• alter the flow of a program, •• test the logical conditions, and •• control the flow of execution as per the selection.
12-Computer_Program-12.indd 341
3/9/2011 2:53:13 PM
342
Computer Programming
These conditions can be placed in the program using decision-making statements. C language supports the control statements as listed below. •• •• •• ••
The if statement The if-else statement The if..else..if ladder statement. The switch case statement.
The decision-making statement checks the given condition and then executes its sub-block. The decision statement decides the statement to be executed after the success or failure of a given condition. The conditional statements use relational operators, which have been explained in Chapter 6. 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 which one is smaller/greater than the other.
12.2 THE if STATEMENT C uses the keyword if to execute a set of command lines or a command line when the logical condition is true. It has only one option. The set of command lines or command line are executed only when the logical condition is true. Syntax for the simplest if statement is as follows. Syntax if (condition) /* no semi-colon */ statement; The statement is executed only when the condition is true. In case the condition is false, the compiler skips the lines within the if block. The condition is always enclosed within a pair of parenthesis. The conditional statements should not be terminated with semicolons (;). The statements following the if statement are normally enclosed with curly braces. The curly braces indicate the scope of the if statement. The default scope is one statement. But it is a good practice to use curly braces even with a single statement. Given below are few programs that demonstrate the use of if statements.
Example 12.1
Write a program to declare the price of the book with if statement and check its price. If its price is less than 575, print the output with some comment, else terminate. Algorithm: Step 1: Start. Step 2: Declare price of a book with some variable. Step 3: Check the condition with if-statement i.e. price