You are on page 1of 117
eM ee eed A mde et & Second Edition Gomputer Prosramming, and Utilization E Balagurusamy Code: 110003 Common to all ENGINEERING branches CompuTER PROGRAMMING AND UTILIZATION CC: 110003 (Common for all Engineering Branches) GTU - June 2011 7 About the Author E Balagurusamy, former Vice Chancellor, Anna University, Chennai and Member, Union Public Service Commission, New Dethi, is currently the Chairman of EBG Foundation, Coimbatore. He is a teacher, trainer, and consultant in the fields of Information Technology and Management. He holds an ME (Hons) in Electrical Engineering and PhD in Systems Engineering form the Indian Institute of ‘Technology, Roorkee. Hisareasofinterest include Object-Oriented Software Engineering, E-Governance, Technology Management, Business Process Re-engineering, and Total Quality Management A prolific writer, he has authored a large number of research papers and several books. His best selling books, among others include Fundamentals of Computers Computing Fundamentals and C Programming Programming in ANSI C, Se Programming in Java, 4e Programming in BASIC, 3¢ Programming in Ci, 3¢ Numerical Methods Reliability Engineering A recipient of numerous honors and awards, E Balagurusamy has been listed in the Directory of Who's Who of Intellectuals and in the Directory of Distinguished Leaders in Education. M Published by Tata McGraw Hill Education Pri "7 West Patel Nagar, New Delhi 110 008 Tata McGraw-Hill te Limited, Computer Programming and Utilization, 2e (For GTU 2011) Copyright © 2011 by the Tata MeGraw Hill Education Private Limited No part of this publication may be reproduced or distributed in any form or by any means, electronic, mechanical, photocopying, recoeding, of otherwise or stored in a database or retrieval system without the prior written permission of the author. The program listings (ifany) may be entered, stored and executed in a computer system, but they may not be reproduced for publication This edition can be exported from India ony by the publishers, ‘Tala McGraw Hill Education Private Limited ISBN (13): 978-0-07-132992-7 ISBN (10): 0-07-132992-7 Vice President and Managing Director—MeGraw-Hill Education, Asi-Pacifie Region: Ajay Shukla Head-—Higher Education Publishing and Marketing: Tibia Mahajan Publishing Manager (SEM and Tech Ed): Shalini Jha ‘Asst Sponsoring Eulitor: Tia Jajarva Asst Development Editor: Shikha Jain Executive—Eaitorial Sorviees: Sohini Mukherjee Sr Production Manager: Satinder § Baveja ‘Asst Production Manager: AnjaltRazdan Dy Marketing Manager (SEM and Tech Ed,: Biju Gesan Sr Product Specialist (SEM and Tech Ed): Joh Mathews General Manager Production: Rajender P Ghansela Asst General Manager Production: B L Dagra Information contained inthis work has been obtainod by Tata MeGraw-Hill, From sources believed to be reliable However, neither Tata MeGraw-Hill nor its authors guarantee the accuracy or completeness of any information published hetein, and neither Tata McGraw-Hill nor its authors shall be responsible for any’ erors, omissions, or {damages arising out of use ofthis information. This work is published with the understanding that Tata McGraw-Hill and its authors are supplying information but are not attempting to render engineering or other professional services, such services are required, the assistance of an appropriate professional should be sought “Typeset at Anvd Composers, AL B Block, Paschim Var, New Delhi 110063 and print at Pashupati Printers Pvt. Lu, 1429/16, Gali No.1, Friends Colony Ind. Area, G-T- Road, Shahdara, Delhi 110095 ‘Cover Printer: SDR Printers RBXLCRACRAZRY Bae Contents Preface Roadmap to the Syllabus 1. Introduction to Computer and Programming ua 12 13 14 Ls 16 7 18 19 La La La Ll Introduetion /.1 Basic Anatomy of a Computer System 1.2 Input Devices 1.3 Output Devices 1.5 Software 1.7 Hardware 1.9 Programming Languages 1.9 Programming Environment 1.12 Introduction to the Design and Implementation of Correct, Efficient and Maintainable Programs 1.13 Structured Programming [.14 Problem Solving J.14 Algorithms /./4 Floweharis 1.17 Just Remember 1.24 Review Questions 1.24 Multiple Choice Questions 1.25 2. Fundamentals of C History of C27 Importance of C 2.2 ‘Sample Program I: Printing a Message 2.3 ‘Sample Program 2: Adding Two Numbers 2. ‘Sample Program 3: Interest Calculation 2.7 ‘Sample Program 5: Use of Math Functions 2.9 Basie Structure of C Programs 2/7 Programming Style 2./2 Executing a*C” Program 2.13 6 1.1-1.25 2.1-2.19 We Contes Just Remember 2.14 Review Questions 2.14 Programming Exercises 2.16 Debugging Exercises 2.18 3. Data Types in C 3.1-3.27 3 32 33 34 35 36 37 38 39 3.10 BL 3.12 3.13 Introduction 3.1 Character Set 3.1 CTokens 3.3 Keywords and Identifiers 3.3 Constants 3.4 Variables 3.8 Data Types 3.9 Declaration of Variables 3.12 Assigning Values to Variables 3.5 Defining Symbolic Constants 3.20 Declaring a Variable as Constant 3.22 Declaring a Variable as Volatile 3.22 Overflow and Underflow of Data 3.22 Just Remember 3.23 Review Questions 3.23 Programming Bxercises 3.25 Debugging Exercises 3.26 Operators and their Hierarchy 41-431 4d 42 43 44 45 46 47 48 49 410 alt 4d 413 414 als 416 Introduction 4.1 Arithmetic Operators 4. Relational Operators 4.4 Logical Operators 4.5 Assignment Operators 4.6 Increment And Decrement Operators 4.8 Conditional Operator 4.9 Bitwise Operators 4.9 Special Operators 4.10 Arithmetic Expressions 4.12 Evaluation of Expressions 4./2 Precedence of Arithmetic Operators 4.13 Some Computational Problems 4.15 ‘Type Conversions In Expressions 4.16 Operator Precedence And Associativity 4.20 Mathematical Functions 4.22 Just Remember 4.23 Review Questions 4.23 Programming Exercises 4.27 Debugging Exercises 4.29 5. Input-Output Functions 5. 52 53 54 58 Introduetion 5.1 Reading a Character 5.2 Writing a Character 5.5 Formatted Input 5.6 Formatted Output 5.15 Just Remember $.22 Review Questions 5.23 Programming Exercises 5.25 6. Control Structures: Decision Making and Branching 6 62 63 64 65 66 67 68 69 Introduction 6. Decision Making with if Statement 6.7 Simple if Statement 6.2 The ifmuElse Statement 6.6 Nesting of if..Else Statements 6.9 The Else if Ladder 6.12 ‘The Switeh Statement 6.15 The? : Operator 6.19 The Goto Statement 6.21 Just Remember 6.24 Review Questions 6.25 Programming Exercises 6.29 Debugging Exercises 6.32 7. Control Structures: Decision Making and Looping 7 72 3 14 18 16 Introduetion 7.1 The While Statement 7.3 ‘The Do Statement 7.5 The for Statement 7.8 Jumps in Loops 7.20 Concise Test Expressions 7.27 Just Remember 7.28 Review Questions 7.28 Programming Exercises 7.32 Debugging Exercises 7.35 8. Arrays 8 82 83 84 83 Introduction 8.1 One-dimensional Arays 8.3 Declaration of One-dimensional Arrays 8.4 Initialization of One-dimensional Amays | $6 ‘Two-dimensional Arrays 8.10 contects i 5.1-5.27 6.1-6.35 7A-7.37 8.1-8.33 Contents 8.6 Initializing Two-dimensional Arrays 8.21 8.7 Multi-dimensional Arrays 8.24 88 Dynamic Arrays 8.25 Just Remember 8.26 Review Questions 8.26 Programming Exercises 8.29 Debugging Exercises 8.32 9. Strings 10. User—Defined Fun 9.1 Introduction 9.1 9.2 Declaring and Initializing String Variables 9,2 9.3 Reading Strings from Terminal 9.3 9.4 Writing Strings to Screen 9.8 9.5 Arithmetic Operations on Characters 9.12 9.6 Putting Strings Together 9.13 9.7 Comparison of Two Strings 9.15 9.8 String-Handling Functions 9.15 9.9 Table of Strings 9.21 9.10 Other Features of Strings 9.22 Just Remember 9.23 Review Questions 9.23 Programming Bxercises 9.26 Debugging Exercises 9.27 \s and Recursion 10.1 Introduction 10.7 10.2. Need for User-defined Functions 10.7 10.3 A Multi-function Program 10.2 10.4 Elements of User-defined Funetions 10.5 10.5 Definition of Functions 10.5 10.6 Retum Values and Their Types 10.8 10.7 Funetion Calls 10.9 10.8 Function Declaration 10.11 10.9 Category of Functions 10.12 10.10 No Arguments and no Return Values 10.12 10.11 Arguments but no Return Values 10.14 10.12 Arguments with Return Values 10.18 10.13 No Arguments but Returns a Value 10.2/ 10.14 Functions that Return Multiple Values 10.22 10.15 Nesting of Functions 10.23 10.16 Recursion 10.24 10.17 Passi 10.18 Passing Strings to Functions 10.30 10.19 The Scope, Visibility and Lifetime of Variables Arrays to Functions 10.25 10.30 9.1-9.30 10.1-10.49 Just Remember 10.40 Review Questions 10.41 Programming Bxercises 1045 Debugging Exercises 10.47 11. Pointers 41.1-11.32 LLL Introduction 1.1 11.2 Understanding Pointers 11.2 11.3 Accessing the Address of a Variable 11.4 114 Declaring Pointer Variables 11.5 11.5 Initialization of Pointer Variables 11.6 11.6 Accessing a Variable through its Pointer 11.7 11.7 Chain of Pointers 11.9 11.8 Pointer Expressions 11.10 11.9 Pointer Increments and Scale Factor 1.1 11,10 Pointers and Arrays 11.12 ILL Pointers and Character Strings 11.15 11.12 Amray of Pointers 11.17 11.13 Pointers as Function Arguments 11.18 11.14 Functions Returning Pointers 1.27 IL.15 Pointers to Functions 1/.2/ 11.16 Pointers and Structures 1.24 11.17 Troubles with Pointers 11.26 Just Remember 11.27 Review Questions 11.27 Programming Exercises 1.30 Debugging Exercises 11.31 12. Structures and Unions 12.1-12.32 12.1 Introduetion 12.1 12.2 Defining @ Structure 12.7 12.3 Declaring Structure Variables 12.3 12.4 Accessing Strueture Members 124 12.5 Structure Initialization 12.6 12.6 Copying and Comparing Structure Variables 12.7 12.7 Operations on Individual Members 12.9 12.8 Amrays of Structures 12.9 12.9 Arrays within Structures 12.12 12.10 Structures within Struetures 12.13 12.11 Structures and Functions 12.15 12.12 Pointers and Structures 12.18 12.13 Unions 12.20 12.14 Size of Structures 12.22 12.15 Bit Fields 12.22 13, Principles of Object-Oriented Program: Contant Just Remember 12.24 Review Questions 12.25 Programming Exercises 12.29 Debugging Exercises 12.31 13.1 Software Crisis 13.1 13.2 Software Evolution 13.3 13.3 A Look at Procedure-oriented Programming 13.4 13.4 Object-oriented Programming Paradigm 13.5 13.5 Basie Concepts of Object-oriented Programming 13.6 13.6 Benefits of OOP 13.10 13.7 Object-oriented Languages 13.17 13.8 Applications of OOP 13.13 Just Remember 13.13 Review Questions 13.14 14, Beginning with C++ 141 Whatis +42 14.1 14.2 Applications of Cr+ 14.2 143 ASimple C++ Program 14.2 144 More C++ Statements 14.6 14.5 An Example with Class 14.8 14.6 Structure of C++ Program 14.9 14.7 Creating the Source File 14.10 148 Compiling and Linking 14.10 Just Remember 14.11 Review Questions 14.11 Programming Exercises 14.12 Debugging Exercises 14.12 15. Tokens, Expressions and Control Structures 18.1 Introduetion 15.7 15.2 Tokens 15.1 18.3 Keywords 15.1 15.4 Identifiers and Constants 15.2 15.5 Basie Data Types 15.3 15.6 User-defined Data Types 15.5 15.7 Derived Data Types 15.7 15.8 Symbolic Constants 15.8 15.9 Type Compatibility 15.9 15.10 Declaration of Variables 15.9 13.1-13.15 14.1-14.13 15.1-15.33 Contents at 15.11 Dynamic Initialization of Variables 15.10 15.12 Reference Variables 15.10 15.13 Operators in C+ 15.12 15.14 Scope Resolution Operator 15.13 15.15 Member Dereferencing Operators 15.15 15.16 Memory Management Operators 15.15 15.17 Manipulators 15.17 15.18 Type Cast Operator 15.18 15.19 Expressions and Their Types 15.19 15.20 Special Assignment Expressions 15.21 15.21 Implicit Conversions 15.27 15.22 Operator Overloading 15.23, 15.23 Operator Precedence 15.23 15.24 Control Structures 15.24 Just Remember 15.28 Review Questions 15.29 Programming Exereises 15.30 Debugging Exercises 15.32 16. Functions in C++ 16.10-16.16 16.1 Introduction 16.7 16.2 The Main Function 16.2 16.3 Function Prototyping 16.3 16.4 Call by Reference 16.4 16.5 Retum by Reference 16.5 16.6 Inline Functions 16.5 16.7 Default Arguments 16.7 16.8 const Arguments 16.9 16.9 Funetion Overloading 16.9 16.10 Friend and Virtual Functions 16.12 16.11 Math Library Funetions 16.12 Just Remember 16,12 Review Questions 16.13 Programming Bxercises 16.14 Debugging Exercises 16.15 17. Classes and Objects 17.1-17.39 17.1 Introduction 17.7 17.2 C Structures Revisited 77. 173 Specifying aClass 17.3 17.4 Defining Member Functions 17.6 17.5 AC# Program with Class 17.8 17.6 Making an Outside Function Inline 17.10 17.7 Nesting of Member Functions 17.10 18. Contos 17.8 Private Member Functions J7./1 17.9 Arrays within a Class 17.12 17.10 Memory Allocation for Objects 17.16 17.11 Statie Data Members 17.17 17.12 Static Member Functions 17.19 17.13 Arrays of Objects 17.20 17.14 Objects as Function Arguments 17.23 17.15 Friendly Funetions 17.25 17.16 Retuming Objects 17.30 17.17 const Member Functions 17.31 17.18 Pointers to Members 17.31 17.19 Local Classes 17.33 Just Remember 17.34 Review Questions 17.34 Programming Exercises 17.35 Debugging Exercises 17.36 Constructors and Destructors 18.1 Introduction 18.7 18.2 Constructors 18.2 18,3 Parameterized Constructors 18.3, 18.4 Multiple Constructors in a Class 18.6 18.5 Constructors with Default Arguments 18.8 18.6 Dynamic Initialization of Objects 78.9 18.7 Copy Constructor 18.11 18.8 Dynamic Constructors 18.13 18.9 Constructing Two-dimensional Arrays 18.14 18.10 const Objects 18.16 IS.I1 Destructors 18.16 Just Remember 18.19 Review Questions 18.19 Programming Exercises 18.19 Debugging Exercises 18.20 GTU Solved Question Paper-June 2010 GTU Solved Question Paper-Remedial Nov./Dec. 2010 GTU Solved Question Paper—Jan 2011 18.1-18.23 Q.1-O.16 Q.17-0.29 Q.30-Q.38 Preface ‘The developments in digital electronics and related technologies during the last few decades have ushered in the second Industrial Revolution, popularly referred to as the Information Revolution, ‘Computer technology plays an ever-increasing role in this new revolution. Application of computers is all-pervasive in the life of every human today. A sound knowledge of how computers work and how they process data and information has, therefore, become indispensable for anyone who seeks employment not only in the area of IT but also in any other fields Rightly so, many institutions and universities in India have introduced a subject covering the fundamentals of computers and programming in C and C++ at the undergraduate and diploma levels of arts, science and engineering disciplines. This book is designed for the students taking the first-semester paper Computer Programming and Utilization (CC 110003) common to all BTech courses in Gujarat Technological University (GTU). Highlights of the Book ‘The book is for the programmer who wishes to know all about computer fundamentals, C and C++ languages and object-oriented programming. It explains in a simple and easy-to-understand style the what, why and how of € Programming and object-oriented programming with C-+ Itensures that the reader will go from knowing nothing about programming to having a strong grasp of C, C+ and object-oriented programming with the support of numerous programs and exercises for practice. The book will prove be a self-study guide. Salient Features ‘Independent, up-to-date and complete coverage of entire syllabus of GTU ‘+ Precise theory presented in. lucid language * Codes with comments provided throughout the book to illustrate the use of various features of the language # Excellent coverage of flowcharts and algorithms ‘© Supplementary information and notes that complement but stand apart from the text are included in special boxes ‘+ Just Remember given at the end of each chapter for quick recap of the concepts # Includes latest Solved Question Paper of GTU (June 2010, Remedial Nov/Dec. 2010, Jan 2011) * Rich pedagogy: © 258 Review Questions provide ample opportunities to test the conceptual understanding of features lv Pies © 197 Programming Exercises and 68 Debugging Exereises stimulate interest to practice programming applications © 71 Fill in the Blanks and 206 Truc/False type Questions serve as effective assessment techniques Chapter Organisation ‘The book has been divided into 18 chapters. Chapter 1 gives an overview of computers, their development, characteristics and evolution. Next, the fundamentals of C are introduced in Chapter 2. Chapter 3 explains data types in C. Operators and their hierarchy, and the concept of header files and VO operations are taken up in Chapters 4 and 5 respectively. Controlstructures—decision making, branching and looping—arecovered subsequently in Chapters 6 and 7. Arrays in ANSI C are presented in Chapter 8. Chapter 9 deals with strings. Funetions and recursion forms the subject of discussion in Chapter 10, while pointers, structures and unions are covered in Chapters IT and 12 respectively. The principles of object-oriented programming and C++ are introduced in Chapter 13, while Chapter 14 guides the reader on developing elementary C++ programs. Tokens, instructions and control structures are taken up in Chapter 13, while functions in C++, classes, objects, constructors and destructors are covered subsequently in Chapters 16 to 18. The book provides numerous examples, illustrations and complete programs. The sample programs are meant to be both simple and educational. Wherever necessary, pictorial descriptions of concepts are included to improve clarity and facilitate better understanding. The book also presents the concept of oriented approach and discusses briefly the important clements of object programming. ‘Acknowledgements I would like to thank all those who provided me with valuable feedback and inputs during the preparation of this book, and especially those at Tata McGraw Hill Education, without whose help and cooperation, this book would not have had a timely release. Special thanks are also due to all my teacher friends and students for their encouragement. I hope everyone who desires to be a part of the next generation of computing will find this book interesting and useful. Further suggestions for improvement will always bbe welcome. —E Balagurusamy Publisher's Note Constructive suggestions and criticism always go a long way in enhancing any endeavour. We request all readers to email us their valuable comments/views\feedback for the betterment of the book at tmh.corefeedback@email.com, mentioning the title and author name in the subject line. Also, please feel free to report any piracy of the book spotted by you. R oadmap to the Syllabus Computer Programming and Utilization Unit1 Fundamentals of Computers Introduction; Basic block diagram and functions of various components of a computer; Concept of hardware and software; Concept of basic types of software; Introduction to programming and programming languages; Flow charts and algorithms cond» Chapter 1 Introduction to Computers and Programming Unit2 Introduction to C Language Operators and their hierarchy; Concept of header files, rrays and strings Fundamemals of C—Data types in VO functions; Control structures in C; Looping structures in C; Chapter 2 Fundamentals of C coro) Chapter 3 Data Types in C Chapter 4 Operations and their Hierarchy, Chapter 5 Concept of Header Files and /O Operation Chapter 6 Control Structures—Decision Making and Branching Chapter 7 Control Structures —Decision Making and Looping Chapter 8 Arrays in Ansi C Chapter 9 Strings Functions and Recursion Concepts of functions with various types of parameters; Various types of parameter-passing mechanisms; Recursive functions and implementation of these concepts inc coro Chapter 10 Functions and Recursion Fossa tothe Sodus xh Pointers and Structures—Concepts of pointers and simple programs using pointers; Introduction to simple structure and its implementations I Chapter 11 Pointers Chapter 12 _ Structures and Unions Unit 3 Introduction To C++ Language Principles of Object Oriented Programming —Comparison with procedural languages; Tokens, expressions and control structures; Introduction to functions, classes, objects, constructoi destructors in CH Classes and Objects Declaring classes; Defining member functions; Making an outside function inline; Nesting of member functions; Private member funetions; Arrays with in a class; Memory allocation of objects; Static data members; Static member functions; Arrays of objects; Objects a function arguments; Friend function, Returning of objects; const member function, Ww Chapter 13 Principles of Object Oriented Programming Chapter 14 Beginning With C++ Chapter 15 Tokens, Expressions and Control Structures Chapter 16 Functions In C++ Chapter 17 Classes and Objects Chapter 18 Constructors and Destructors ee = Introduction to Computer and Programming 14 || Introduction The term computer is derived from the word compute. A computer is an electronic device that takes data and instructions as an input from the user, processes data, and provides useful information known as outpu. This cycle of operation of a computer is known as the input-process-ourput eycle and is shown in Fig. 1.1, The electronic device is known as hardware and the set of instructions is known as oom tet | proces | OUTPUT normaton Instructions Input-process-output concept ‘The spurt of innovations and inventions in computer technology during the ast few decades has led t0 the development of a variety of computers. They are so versatile that they have become indispensable to engineets, scientists, business executives, managers, administrators, accountants, teachers and students. They have strengthened man’s powers in numerical computations and information processing, Modern computers possess certain characteristics and abilities peculiar to them. They can: (i) perform complex and repetitive calculations rapidiy and accurately, (ii) store large amounts of data and information for subsequent manipulations, (ii), hold a program of a modet which can be explored in many different ways, (iv) compare items and make decisions, (¥) provide information to the user in many different forms, (vi) automatically correct or modify the parameters of a system under control, 12. Computer Programming and Ustzaton (vii) draw and print graphs, (sili) converse with users interactively, and (ix) receive and display audio and video signals. These capabilities of computers have enabled us to use them for a variety of tasks. Application areas may broadly be classified into the following major categories. Data processing (commercial use) Numerical computing (scientific use) Text (word) processing (office and educational use) Message communication (e-mail) Image processing (animation and industrial use) ‘Voice recognition (multimedia) Engineers and scientists make use of the high-speed computing capability of computers to solve complex mathematical models and design problems. Many calculations that were previously beyond contemplation have now become possible. Many of the technological achievements such as landing on the moon would not have been possible without computers, ‘The areas of computer applications are too numerous to mention, Computers have become an integral part of man’s everyday lile. They continue to grow and open new horizons of discovery and application such as the electronic office, electronic commerce, and the home computer center. The microelectronics revolution has placed enormous computational power within the reach of not only every organisation but also individual professionals and businessmen. However, it must be rememiered that computers are machines created and managed by human beings. A computer has no brain of its own. Anything it does is the result of human instruetions. It is an obedient slave which carries out the master’s instructions as long as it can understand them, no matter whether they are right ‘or wrong. A computer has no common sense. 12 | Basic Anatomy of a Computer System. A computer system comprises of hardware and software components. Hardware refers to the physical parts of the computer system and software is the set of instructions or programs that are necessary for the functioning of a computer to perform certain tasks. Hardware includes the following components: + Input devices — They are used for accepting the data on which the operations are to be performed. ‘The examples of input devices are keyboard, mouse and track ball + Processor — Also known as CPU, it is used to perform the calculations and information processing on the data that is entered through the input device. + Output devices — They are used for providing the output of a program that is obtained after performing the operations specified in a program. The examples of output devices are monitor and printer. + Memory —It is used for storing the input data as well as the output of a program that is obtained after performing the operations specified in a program. Memory can be primary memory as well as secondary memory. Primary memory includes Random Access Memory (RAM) and secondary memory includes hard disks and floppy disks. Inveducion fo Computer and Programing 1.3 Software supports the functioning of a computer system internally and cannot be seen. It is stored on secondary memory and can be an application software as well as system software. The application software is used to perform a specific task according to requirements and the system software is mandatory for running application software. The examples of application software include Excel and MS Word and the examples of system software include operating system and networking system. All the hardware components interact with each other as well as with the software. Similarly, the different types of software interact with each other and with the hardware components. The interaction between various hardware components js illustrated in Fig. 1.2. Magnetic Magnetic Tape Disk EXTERNAL STORAGE UNITS Memory Output Unit Unit ou Data and results flow Control Instructions to units Instructions to contrat unit FERED interaction among hardware components 1.3 || Input Devices Input devices can be connected to the computer system using cables. The most commonly used input devices among others are: + Keyboard + Mouse + Scanner 14 Computer Programming and Uitzaton 134 Keyboard A standard keyboard includes alphanumeric keys, function keys, modifier keys, cursor movement keys, spacebar, escape key, numeric keypad, and some special keys, such as Page Up, Page Down, Home, Insert, Delete and End. The alphanumeric keys include the number keys and the alphabet keys. The function keys are the keys that help perform a specific task such as searching a file or refreshing @ Web page. The modificr keys such as Shift and Control keys modify the casing style of a character or symbol. The cursor movement keys include up, down, left and right keys and are used to modify the direction of the cursor on the screen. The spacebar key shifts the cursor to the right by one position. The numeric keypad uses separate keypads for numbers and mathematical operators. A keyboard is shown in Fig. 13 eee oN spesalkeys coporod "orn ‘oe ERED Kroon 1.3.2. Mouse The mouse allows the user to select elements on the screen, such as tools, icons, and buttons, by pointing and clicking them, We can also use a mouse to draw and paint on the sereen of the computer system. The mouse is also known as a pointing device because it helps change the position of the pointer or cursor on the sereen, N L Ram uten "The mouse consists of two buttons, a wheel at the s top and a ball at the bottom of the mouse, When the ball roves, the cursor on the sereen moves in the direction in Which the ball rotates. The let button ofthe mouse is used g to select an element and the right button, when clicked, displays the special options such as open and explore and EY siouse shorteut menus. The wheel is used to serall down in a document or a Web page. A mouse is shown in Fig. 1.4 Wheel Left Button 133° Scanner A scanner is an input device that converts documents and images as the digitized images understandable by the computer system. The digitized images ean be produced as black and white images, gray images, ‘or colored images, In ease of colored images, an image is considered as a collection of dots with each dot representing a combination of red, green, and blue colors, varying in proportions. The proportions Inveducon fo Computer and Programming 1.5 of red, green, and blue colors assigned to a dot are together called as color description. The scanner uses the color description of the dots to produce a digitized image. Fig. 1.5 shows a scanner. ‘There are the following types of scanners that can be used to produce digitized images: ‘+ Flatbed seanner — It contains a scanner head that moves across a page from top to bottom to read the page and converts the image or text available on the page in digital form, The flatbed scanner is used to sean graphics, oversized documents, and pages from books. + Drum scanner — In this type of seanner, a fixed scanner head EERES scanner 4a med and the image to be scanned is moved across the head ‘The drum scanners are used for scanning prepress materials + Slide scanner — It is a scanner that can scan photographic slides directly to produce files understandable by the computer + Handheld seanner — It isa scanner that is moved by the end user aeross the page to be scanned. ‘This type of scanner is inexpensive and small in size. 1.4 | Output Devices The data, processed by the CPU, is made available to the end user by the output devices. The most ‘commonly used output devices are + Monitor + Printer + Speaker + Plotter 1.44 Monitor A monitor is the most commonly used output device that produces visual displays generated by the computer. The monitor, also known as a screen, is connected as an external device using cables or connected either as a part of the CPU case. The monitor connected using cables, is connected to the video card placed on the expansion slot of the motherboard. The display device is used for visual presentation of textual and graphical information, ‘The monitors can be classified as cathode ray tube (CRT) monitors of liquid crystal display (LCD) ‘monitors. The CRT monitors are large, occupy more space in the computer, whereas LCD monitors are thin, light weighted, and occupy lesser space. Both the monitors are available as monochrome, gray scale and color models. However, the quality of the visual display produced by the CRT is better than that produced by the LCD. The inner side of the sereen of the CRT contains the red, green, and blue phosphors. When a beam of electrons strike the screen, the beam strikes the red, green and blue phosphors on the screen and itradiates it to produce the image. The process repeats itself for a change in the image, thus refreshing the changing image. To change the color displayed by the monitor, the intensity of the beam striking the screen is varied. Ifthe rate at which the screen gets refreshed is large, then the sereen starts flickering, when the images are refreshed. 1.6 Computer Programming and Uitzaton The LCD monitor is a thin display device that consists of a number of color or monochrome arrayed in front of a light source or reflector. LCD monitors consume a very small amount of electric power. A monitor can be characterized by its monitor size and resolution. The monitor size is the length of the screen that is measured diagonally, The resolution of the sereen is expressed as the number of picture ‘elements or pixels of the screen, The resolution of the monitor is also called the dot pitch. The monitor with a higher resolution produces a clearer image. 142. Printer The printer is an output device that transfers the text displayed on the sereen, onto paper sheets that can be used by the end user. The various types of printers used in the market are generally categorized as ddot matrix printers, inkjet printers, and laser printers. Dot matrix printers are commonly used in low quality and high volume applications like invoice printing, cash registers, ete. However, inkjet printers are slower than dot matrix printers and generate high quality photographie prints. Since laser printers ‘consist of microprocessor, ROM and RAM, they can produce high quality prints in quicker time without being connected to a computer. The printer is an output device that is used to produce a hard copy of the electronic text displayed on the sereen, in the form of paper sheets that can be used by the end user. The printer is an extemal device that is connected to the computer system using cables. The computer needs to convert the document that is to be printed to data that is understandable by the printer. The printer driver software ot the print driver software is used to convert a document to a form understandable by the computer. When the ‘computer components are upgraded, the upgraded printer driver software needs to be installed on the computer. ‘The performance of a printer is measured in terms of dots per inch (DPD) and pages per minute (PPM) produced by the printer. The greater the DPI parameter of a printer, the better is the quality of the output generated by it. The higher PPM represents higher efficiency of the printer. Printers can be classified based on the technology they use to print the text and images: + Dot matrix printers — Dot matrix printers are impact printers that use perforated sheet to print the text, The process to print a text involves striking a pin against a ribbon to produce its impression on the paper. As the striking motion of the pins help in making carbon copies of a text, dot matrix printers are used to produce multiple copies of a print out. + Inkjet printers — Inkjet printers are slower than dot matrix printers and are used to generate high quality photographic prints. Inkjet printers are not impact printers. The ink cartridges are attached to the printer head that moves horizontally, from left to right. The print out is developed 1s the ink of the cartridges is sprayed onto the paper. The ink in the inkjet is heated to create a bubble. The bubble bursts out at high pressure, emitting a jet of the ink on the paper thus producing images, + Laser printers — The laser printer may or may not be connected to a computer, to generate an ‘output, These printers consist of a microprocessor, ROM and RAM, which can be used to store the textual information. The printer uses a cylindrical drum, a toner and the laser beam, The toner stores the ink that is used in generating the output. The fonts used for printing in a laser printer are stored in the ROM ot in the cartridges that are attached to the printer. The laser printers are available as gray scale, black and white or color models. To print high quality pages that are ‘graphic intensive, laser printers use the PageMaker software. Inveducon to Computer and Programming 1.7 143° Speaker ‘The speaker is an electromechanical transducer that converts an electrical signal into sound. They are attached to a computer as output devices, to provide audio output, such as warning sounds and Internet audios. We can have built-in speakers or attached speakers in a computer to warn end users with error audio messages and alerts. The audio drivers need to be installed in the computer to produce the audio ‘output. The sound card being used in the computer system decides the quality of audio that we listen using music CDs or over the Internet. The computer speakers vary widely in terms of quality and price, ‘The sophisticated computer speakers may have a subwoofer unit, to enhance bass output. 144 Plotter ‘The plotter is another commonly used output device that is connected to a computer to print large documents, such as engineering or constructional drawings. Plotters use multiple ink pens or inkjets with color cartridges for printing. A computer transmits binary signals to all the print heads of the plotter. Each binary signal contains the coordinates of where a print head needs to be positioned for printing. Plotters are classified on the basis of their performance, as follows: + Drum plotter — They are used to draw perfect circles and other graphic images. They use a drawing arm to draw the image. The drum plotter moves the paper back and forth through a roller and the drawing arm moves across the paper. + Flat-bed plotter — A flat bed plotter has a flat drawing surface and the two drawing arms that ‘move across the paper sheet, drawing an image. The plotter has a low speed of printing and is large in size. + Inkjet plotter — Spray nozzles are used to generate images by spraying droplets of ink onto the paper. However, the spray nozzles can get clogged and require regular cleaning, thus resulting in a high maintenance cost. + Electrostatic plotter — As compared to other plotters, an electrostatic plotter produces quality print with highest speed. It uses charged electric wires and special dielectric paper for drawing. ‘The electric wires are supplied with high voltage that attracts the ink inthe toner and fuses it with the dielectric paper. 45 [| Sotware In the field of computer science, software is defined as a computer program, which includes logical instructions used for performing a particular task on a computer system using hardware components. The following are the two major categories of software under which different types of computer programs ‘ean be classified: + System software + Application software Figure 1.6 shows the relationship among hardware, software, and user. ‘The figure shows a layered architecture, which represents different components of a computer such as hardware, system software, application software, and user in @ hierarchical manner, 18 Computer Programming and Ustzaton ‘Systom software ‘Application software User ERED Relationship among hardware, sofware, and user 1.54 System Software System software refers to a computer program that manages and controls hardware components of ‘2 computer system. In other words, the system software is responsible for handling the functioning of the computer hardware, The system software is also responsible for the proper functioning of the application software on a computer system. The system software includes general programs, which are written to provide an environment for developing new application software using programming languages. In computer science, there are several types of system software, such as operating systems and utility programs. The operating system is the primary system software, which controls the hardware and software resources of a computer system. It also performs various operations, such as memory allocation, instruction processing, and file management. The most commonly used operating systems are MS DOS, MS Windows, and UNIX. The following are the various funetions of system software: + Process management + Memory management + Secondary storage management *+ VO system management ile management 15.2 Application Software Application software is a computer program that is executed on the system software, It is designed and developed for performing specific tasks and is also known as end-user program. Application software is unable to run without the system software, such as operating system and utility programs. It includes several applications, such as word-processing and spreadsheet. The word-processing application helps in creating and editing a document. Using this application software, we can also format and print the document, For word-processing, many applications are available, stich as WordStar, WordPerfect, and Open-source. The most commonly used word-processing application is MS Word, which is a part of the MS Office suite. Spreadsheet application helps in creating a customized ledger, which has number Inreducion fo Computer ard Programming 1.9 of columns and rows for entering the data values. The most commonly used spreadsheet application is MS Excel, which is also a part of MS Office suite. It helps in storing and maintaining a database in a structural manner. 16 || Hardware ‘The physical devices that make up the computer are called Hardware. The hardware units are responsible for entering, storing and processing the given data and then displaying the output to the users, The basic hardware units of a general purpose computer are keyboard, mouse, memory, CPU, monitor and printer. Among these hardware units, keyboard and mouse are used to input data into the computer, memory is used to store the entered data, CPU is used to process the entered data and monitor and printer are used to display the processed data to the users. CPU is the main component inside the computer that is responsible for performing various operations and also for managing the input and output devices. It includes two components for its functioning, Arithmetic Logic Unit (ALU) and Control Unit (CU). ALU is used to perform the arithmetic operations such as addition, subtraction, etc, and logic operations such as AND, OR, etc. on the data obtained from the memory. CU is used to control the activities related to the input and output devices. It obtains the instructions from the memory, decodes them and then, executes them so as to deliver output to the users, The XNOR gate can be logically expressed as: 408 Table 1.1 shows the truth table of XNOR gate. ‘The Truth Table of XNOR Gate Input Input ‘Output Y ° 0 1 ° 1 a 1 0 a 1 1 1 17 ll Programming Languages ‘The operations of a computer are controlled by a set of instructions (called a computer program). Thes instructions are writen to tell the computer: 1, what operation to perform 2. where to locate data 3. how to present results, 4, when to make certain decisions ‘The communication between two parties, whether they are machines or human beings, always needs a common language or terminology. The language used in the communication of computer instructions is known as the programming language. The computer has its own language and any communication with the computer must be in its language or translated into this language. 440° Computer Programming and Utizaon Three levels of programming languages are available. They are: 1. machine languages (low level languages) 2. assembly (or symbolic) languages 3. procedure-oriented languages (high level languages) 4.7 Machine Language As computers are made of two-state electronic devices they can understand only pulse and no-pulse (or “I” and *0") conditions. Therefore, all instructions and data should be written using binary codes 1 and 0. The binaty code is called the machine code or machine language. Computers do not understand English, Hindi or Tamil. They respond only to machine language. Added to this, computers are not identical in design, therefore, each computer has its own machine language. (However, the seript 1 and 0, is the same for all computers). This poses two problems for the user. First, it is difficult to understand and remember the various combinations of 1s and 0's representing numerous data and instructions. Also, writing error-free instructions is a slow process. Secondly, since every machine has its own machine language, the user cannot communicate with other computers (If he does not know its language). Imagine a Tamilian making his first trip to Delhi. He would face enormous obstacles as the language barrier would prevent him from communicating Machine languages are usually referred to as the first generation languages. 1.72 Assembly Language ‘The Assembly language, introduced in 1950s, reduced programming complexity and provided some standardization to build an application. The assembly language, also referred to asthe second-generation programming language, is also a low-level language. In an assembly language, the Os and Is of machine language are replaced with abbreviations or mnemonic code. ‘The main advantages of an assembly language over a machine language are: + Aswe can locate and identify syntax errors in assembly language, it is easy to debug it + Itis easier to develop a computer application using assembly language in comparison to machine language, + Assembly language operates very efficiently. An assembly language program consists of a series of instructions and mnemonics that correspond to a stream of executable instructions. An assembly language instruction consists of a mnemonic code followed by zero or more operands. The mnemonic code is called the operation code or opcode, which specifies the operation to be performed on the given arguments. Consider the following machine code 10110000 01100001 Its equivalent assembly language representation is: moy al, 061 In the above instruction, the opcode “move” is used to move the hexadecimal value 61 into the processor register named ‘al’, The following program shows the assembly language instructions to subtract two numbers: ORG 500 /Origin of program is location 300 LDA SUB /Load subtrahend to AC Inredton fo Comuter and Programming 1.14 MA ‘Complement AC INC Inerement AC ADD MIN, /Add minuend to AC STA DIF Store difference HLT /Halt computer MIN, DEC 56 /Minuend SUB, DEC-2 /Subtrahend DIF, HEXO (Difference stored here END /End of symbolic program It should be noted that during execution, the assembly language program is converted into the machine code with the help of an assembler. The simple assembly language statements had one-to-one correspondence with the machine language statements. This one-to-one correspondence still generated complex programs. Then, macroinstructions were devised so that multiple machine language statements could be represented using a single assembly language instruction. Even today programmers prefer to use an assembly language for performing certain tasks such + To initialize and test the system hardware prior to booting the operating system. This assembly language code is stored in ROM + To write patches for disassembling viruses, in anti-virus product development companies + To attain extreme optimization, for example, in an inner loop in a processor-intensive algorithm + For direct interaction with the hardware + In extremely high-security situations where complete control over the environment is required + To maximize the use of limited resources, in a system with severe resource constraints 1.73 High-Level Languages High evel languages further simplified programming tasks by reducing the number of computer operation details that had to be specified. High level languages like COBOL, Pascal, FORTRAN, and C are more abstract, easier to use, and more portable across platforms, as compared to low-level programming languages. Instead of dealing with registers, memory addresses and call stacks, @ programmer can concentrate more on the logic to solve the problem with help of variables, arays or Boolean expressions. For example, consider the following assembly language code: LOAD A ADDB STORE C Using FORTRAN, the above code can be represented as C=A+B The above high-level language code is executed by translating it into the corresponding machine language code with the help of a compiler or interpreter. High-level languages can be classified into the following three categories: + Procedure-oriented languages (third generation) + Problem-oriented languages (fourth generation) + Natural languages (fifth generation) 442 Computer Programming and Utizaen Procedure-oriented Languages High-level languages designed to solve general-purpose problems are called procedural languages or third-generation languages. These include BASIC, COBOL, FORTRAN, C, C++, and JAVA, which are designed to express the logic and procedure of a problem. Although, the syntax of these programming, languages is different, they use English-like commands that are easy to follow. Another major advantage of third-generation languages is that they are portable. We can put the compiler (or interpreter) on any computer and create the object code. The following program represents the source code in the C language GEC P10) ( do ‘ Jwnite ( n<50)7 Problem-oriented Languages Problem-oriented languages are used to solve specific problems and are known as the fourth- generation languages. These include query Languages, Report Generators and Application Generators which have simple, English-like syntax rules. Fourth-generation languages (4 GLs) have reduced programming efforts and overall cost of software development. These languages use either a visual environment or a text environment for program development similar to that of third-generation languages. A single statement in a fourth-generation language can perform the same task as multiple lines of a third-generation language. Further, the programmer just needs to drag and drop from the toolbar, to create various items like buttons, text boxes, labels, etc. Also, the programmer can quickly create the prototype of the software application. Natural Languages Natural languages are designed to make a computer to behave like an expert and solve problems. The programmer just needs to specify the problem and the constraints for problem-solving. Natural languages such as LISP and PROLOG are mainly used to develop artificial intelligence and expert systems. These languages are widely known as fh generation languages. 8 ll Programming Environment programming environment comprises ll those components that facilitate the development of aprogram. ‘These components are largely divided under two categories—programming tools and Application Programming Interfaces (APIs). They are regarded as the building blocks of any programming ‘environment. An API can be defined as a collection of data structures, classes, protocols, and pre-defined functions stored in the form of libraries. These libraries are included in the software packages of the programming languages like C, C++, ete. An API makes the development task easier for the programmers, as in-built API components are used again and again, ensuring reusability Irrton to Computer and Programming 1.13 The software application wich is used for the development, maintenance and debugging of a software program is known as programming tool. A good programming tool ensures that the programming activities are performed in an efficient manner. The following are some of the main categories of programming tools: + Integrated Development Environment (IDE) _It is the most commonly used tool that offers an integrated environment to the programmers for software development. It contains almost all the components for software development such as compiler, editor, debugger, ete + Debugging tool _Itis a specialized tool that helps the programmer to detect and remove bugs or errors from a program, + Memory usage tool As the name suggests, memory usage tool helps the programmer to ‘manage the memory resources in an efficient manner. ‘The design and development of a correct, efficient, and maintainable program depends on the approach followed by the programmer. A programmer should follow standard methodologies throughout the cycle of program development. The entire program development process is divided into a number of phases, with each phase serving a definite purpose. Also, the output of one phase acts as an input for the next phase. Let us now understand these standard sct of phases in the program development process: 1, Analysis phase As the name suggests, the first phase of program development involves analyzing the problem in order to ascertain the objectives that the program is supposed to ‘meet. All the identified requirements are documented so as to avoid any doubts or uncertainties pertaining to the funetionality of the program. This phase also emphasizes on determining the input and output values of the program. 2. Designing phase This phase involves making the plan of action before actually starting the development work. The plan is made on the basis of the program specifications identified in the previous phase. Different programs require different designing patterns depending on the program specifications. Thus, this phase helps in framing the core structure of the program, In addition, the designing phase has an added advantage of modularity. It basically helps to break the program into small modules or chunks. This breaking of the large program into smaller chunks results in the development of a well-organized program, Furthermore, it gives the programmer liberty of planning and creating the algorithm for each module separately. Development phase This phase involves writing the instructions or code for the program on the basis of the design document created in the previous phase. The choice of the programming language in which the program will be developed is made on the basis of the type of program For example, if itis a system program, then it is better to choose C language instead of Visual Basie (VB), which is more suited for applications programming. 4, Implementation and testing In this stage, the developed program is implemented in its target environment and its key parameters are closely observed in order to ensure that the program runs correctly, Apart from ensuring the correct functioning of the program this phase primarily focuses on identifying the hidden bugs in the program. No matter how many preventive measures are taken in the development phase there is always the possibility of prevalence of hidden bugs in 4 program. Thus, to identify such bugs a program needs to be tested using large number of varied input values. Once identified the bugs are removed with the help of software patches. 1.9 |} Introduction to the Design and Implementation of Correct, Efficient and Maintainable Programs 1 Compt Prana an taton 1.10 |] Structured Programming Structured programming is a subset of one of the key programming paradigms, ie., procedural programming. It helps in making a program easily understandable and debuggable. A program that is hot based on the structured programming approach is very difficult to maintain, debug and understand. Structured programming approach mainly focuses on the order of execution of the statements within 4 program. It suggests the use of sequential execution of statements in a program, Thus, structured programming approach suggests the use of mainly three types of control structures—sequential repetitive and selective. Further, it suggests avoiding the use of goto, break and continue statements in 4 program as all these are unconditional branch statements. 444 l Problem Solving Problems that can be solved through a computer may range in size and complexity. Since computers do not possess any common sense and cannot make any unplanned decisions, the problem, whether it is simple or complex, has to be broken into a well-defined set of solution steps for the computer to implement. Problem solving is the process of solving a problem in a computer system by following a sequen« of steps, which include: 1, Developing the algorithm An algorithm is @ sequence of steps written in the form of English phrases that specify the tasks that are performed while solving a problem. It involves identifying the variable names and types that would be used for solving the problem, 2. Drawing the flowehart A flowchart is the graphical representation of the flow of control and. logic in the solution of a problem. The flowchart is a pictorial representation of an algorithm. 1.12 || Algorithms Algorithms help a programmer in breaking down the solution of problem into a number of sequential steps. Corresponding to each step a statement is written in a programming language; all these statements are collectively termed as a program, ‘The following is an example of an algorithm to add two integers and display the result: Algorithm Step 1 ~ Accept the first integer as input from the user. (oun) Step 2 - Accept the second integer as input from the user. (oum2) Step 3 - Calculate the sum of the two integers (sum = numi + num) Step 4 - Display sum as the result. Inrton to Computer and Programming 1.18 ‘There isa time and space complexity associated with each algorithm. Time complexity specifies the amount of time required by an algorithm for performing the desired task. Space complexity specifies the amount of memory space required by the algorithm for performing the desired task. While solving complex problem, it is possible to have multiple algorithms for obtaining the required solution. The algorithm that ensures best time and space trade off should be chosen for obtaining the desired solution 1.421 Characteristics of Algorithms ‘The typical characteristics that are necessary for a sequence of instructions to qualify as an algorithm are the following: + The instructions must be in an ordered form. + ‘The instructions must be simple and concise. They must not be ambiguous. + ‘There must be an instruction (condition) for program termination, + The repetitive programming construets must possess an exit condition. Otherwise, the program ‘might run infinitely. + The algorithm must completely and definitely solve the given problem statement, 1.122. Advantages of Algorithms Some of the key advantages of algorithms are the following: + It provides the core solution to a given problem. This solution ean be implemented on a computer system using any programming language of user’s choice. + It facilitates program development by acting as a design document or a blueprint of a given problem solution + It ensures easy comprehension of a problem solution as compared to an equivalent computer program. + It eases identification and removal of logical errors in a program. + It facilitates algorithm analysis to find out the most efficient solution to a given problem. 1.12.3 Disadvantages of Algorithms Apart from the advantages, algorithms also posses certain limitations, which are the following: + In large algorithms, the flow of program control becomes difficult to track. + Algorithms lack visual representation of programming constructs like flowcharts; thus, unde- ‘standing the logie becomes relatively difficult. Example 1.1 Writean algorithm to find out whether a given number is prime or not Solution Algorithm Step 1 - start Step 2 - Accept a number from the user (num) Step 3 - Initialize looping counter i = 2 Contd. 4146 Computer Programming and Utizaen Step 4 - Repeat Step 5 while 1 < nun Step 5 - If remainder of num divided by i (numbi) is Zero then goto step 6 else goto step 4 = Display “nom is not a prime number” and break from the loop - If 4 = num then goto Step 8 Else goto step 9 - Display “num is a prime number” Example 12 wri Solution ¢ an algorithm to find the average of marks obtained by a student in three subjects. Algorithm Step 1 - start Step 2 - Accept the marks in three subjects from the user (marks1, marks2, marks3) Step 3 - Calculate average marke using formla, average = (markel + marke? + marks3)/3 Step 4 - Display the computed average of three subject marks Step 5 - Stop Example 1.3 Write an algorithm wo determine whether the given year isa leap year o not, Solution Rigorithm Step 1 - start Step 2 - Accept an year value from the user (year) Step 3 - If remainder of year value divided by 4 (yeart4) is 0 then goto Step 4 else goto Step 5 Step 4 - Display *’year’ Le a leap year” and goto Step 6 Step 5 - Display “’year’ is not a leap year] Step 6 - Stop Example 1.4 Write an algorithm to find out whether a given number is even or odd Solution Algorithe Step 1 - start Step 2 - Accept a number from the user (nun) Step 3 - If remainder of num divided by 2 (num/2) is zero then goto Step 4 else goto Stop 5 Contd. lnrodcton to Comput and Programming 1.17 Step 4 = Display “num is an even number” and goto step 6 Step 5 - Display “num is an odd number” Step 6 = Stop Example 1.5 Write an algorithm determine whether a given ting is a palindrome or not. Solution gorithm step 1 - start Step 2 = Accept 4 etsing fron the user (etx) Step 3 - Calculate the length of string str (len) Step 4 - Initialize looping counters left-0, right-len-1 and chk = ‘t’ Step 5 - Repeat Steps 6-8 while left < right and chk ~ vt’ step 6 - If atr(eft) ~ atr(right) goto Step 8 else goto step 7 Step 72 Get chk = 18) Step @ - Set left ~ left + 1 and right ~ right +1 Step 9 - If chke’t’ goto Step 10 else goto Step 11 Step 10 - Display “the string is» palinerome” and goto Step 12 She fi teeley re ste teeg ceteer tps ete Step 12 ~ stop aE 1.3 || Flowcharts A flowchart can be defined as the pictorial representation of a process, which describes the sequence and flow of control and information within the process. The flow of information is represented inside the flowchart in a step-by-step form. This technique is mainly used for developing business workflows and solving problems using computers. Flowchart uses different symbols for depicting different activities, which are performed at different stages of a process. The various symbols used in a flowehart are: + Start and end I represented by an oval or a rounded rectangle. It represents the starting and the ending of a process. Every process starts and ends at some point so a flowchart always contains one start as well as one end symbol. Figure 1.13 shows the start and the end symbols used in a flowchart. < >E 3 Start and end symbol 18 Computer Programming and Utzaten + Input o output _ It is represented by a parallelogram. It represents the inputs given by the user to the process and the outputs given by the process to the user. Figure 1.14 shows the input or output symbol + Action or process It is represented by a rectangle. It Input or output symbol represents the actions, logies and calculations taking place ina process, Figure 1.15 shows the action or process symbol, Action or process symbol. + Decision or condition It is represented by a rhombus oF a diamond shape. It represents the condition or the decision-making step in a flowchart. The result of the decision is a Boolean value, which is either true o false. Each of these values takes the flow of the program to a certain point, which is shown with the help of arrows. Figure 1.16 shows the decision or condition symbol Decision or condition symbol + Arrow Itisrepresented by adirected line. It represents the flow of process and the sequence of steps in a flowchart. It guides the process about the direction and the sequence, which is to be followed while performing the various steps in the process. Figure 1.17 shows the arrow symbol Arrow symbol + Connector It is represented by a circle in a flowchart It represents the continuation of the flow of steps when a flowchart continues to the next page. A character such as an alphabet (a to z) or a symbol (ct, B ot 7), ete. can be placed in the circle at : the position where the flow is broken and the same character is Connector symbol. also placed in the circle at the position from where the flowchart continues. Figure 1.18 shows the connector symbol. In addition to the above-mentioned basic flowchart symbols, certain other symbols are also used inside flowcharts for depicting advanced operations, Table 1.2 shows some of these advanced flowchart symbols; ‘Symbol Description Represenis he internal memory ofa computer system, such as RAM and ROM Represents a database Contd. Irrton to Computer and Programming 1.19 Symbol Description Represents subroutine Represents a set of documents Represents an ile or waling state Merges multiple datasets ito one Extracts individual sos of data tems rom a singe data sot > JOY Represenis a combination of merge and extrac actos. Itextracs mulpe data ses from multiple input data ses. In order to understand how a flowchart represents the flow of information; consider an example of a flowchart for adding two numbers, as shown in Fig. 1.19, GC san > Result = num 1 = num 2 Display (result) _—_t_ i) Flowchart for addition of two numbers. Flowchart 4120 Computer Programming and Utizaen 1.43.1 Flowchart Design Rules Some of the standard guidelines or rules that must be followed while designing a flowchart are the following: + Icmust begin with a "Start” and end with a "Stop" symbol. + The standard process flow should be either from top to bottom or from left to right, + The instructions specified in the flowchart must be crisp and concise + The arrows must be aligned properly so as to clearly depict the flow of program control + The use of connectors should be generally avoided as they make the program look more complex. + A process or action flowchart symbol must have only one input arrow and one output arrow, + Two arrows must never intersect or cross each other; if such a need arises, then appropriate bridge or crossover symbols must be used. 1.13.2 Advantages of Flowcharts Some of the key advantages of using a flowchart in program design are the following: + Ithelps to understand the flow of program control in an easy way. + Developing program code by referring its flow chart is easier in comparison to developing the program code from scratch. + Ithelps in avoiding semantic errors. + Any concept is better understood with the help of visual representation. This fact also holds true for flowcharts. It is easier to understand the pictorial representation of a programming logic. + A flowchart acts as documentation for the process or program flow. + The use of flowcharts works well for small program design. 1.13.3 Disadvantages of Flowcharts Flowcharts also have certain limitations, such as the following: + Fora large program, the flow chart might become very complex and confusing + Modification of a flowchart is difficult and requires almost an entire rework. + Since flowcharts require pictorial representation of programming elements, tedious and time consuming to create a flowchart + Excessive use of connectors in a flowchart may at times confuse the programmers. becomes a little Example 1.6 Draw a flowchart forthe problem statement given in Example 1.1 Solution Flowchart to find out whether a given number is prime or not: Inrtent Computer and Programming 124 Real om Dey "Nota Prime Zz Example 1.7 Draw a flowchart forthe problem statement given in Example 1.2 Solution Flowchart to find the average of marks obtained by a student: [West oai at ] jemi [Asc = mark + marks] Sot << Sep > 4122 Computer Programming and Utzaen Example 1.8 Draw a flowchart forthe problem statement given in Example 1.3, Solution Flowchart to determine whether the given year is a leap year or not: Example 1.9 Draw a flowchart forthe problem statement given in Example 1 Solution Flowchart to find out whether a given number is even o odd: sac (eum %42)= 03 Yes Display “Even Number” J l Display “Odd Number” Cae Inrton to Computer and Programming 1.23 Example 1.10 Draw a flowchart forthe problem statement given in Example 1.5 Solution Flowchart to determine whether a given string isa palindrome or not: Start Is str (left) =, Yes str (eight)? No. ch Display Sui Display “Nota Palindrome String” 126 Computer Programing and Utzaton Just Remember | + Computer: It is an electronic device that takes data and instructions as input from the user, processes the data, and generates useful information as an output. + Input devices: Input devices accept the data from the end users on which the operations are to be performed + Output devices: Output devices are used for providing the output of a program that is obtained after performing the operations specified in a program. + CPU: It is the heart of a computer that is used to process the data entered through the input device. + Memory: Itis used for storing the input data as well as the output ofa program that is obtained after performing the operations in a program. + Scanner: It is an input device that converts documents and images as the digitized images understandable by the computer system. + Motherboard: Itis a device used for connecting the CPU with the input and output devices. + Monitor: It is an output device that produces visual displays generated by the computer: + Printer: It is an output device that prints the computer generated information onto the paper sheets, + Speaker: It is an electromechanical transducer that converts an electrical signal into sound. + Plotter: It is an output device that is connected to a computer to print large documents, such as engineering and constructional drawings. + System software: It refers to a computer program that manages and controls hardware components, + Application software: It is 2 computer program that is designed and developed for performing specific utility tasks; itis also known as end-user program. + Operating System: It is the system software that helps in managing the resources of a computer system, It also provides a platform for the application programs to run on the computer system + Algorithm: It is a complete, detailed, and precise step-by-step method for solving a problem independently. + Flowchart: It is a pictorial representation of an algorithm depicting the flow of various steps. Review Questions 1M tate whether the following statements are true or false. (i) Dot matrix printers are slower than inkjet printers and are used to generate high quality photographic prints (ii) Deseribing the process step by step is called as flowchart ii) Algorithm involves very complex process. (iv) When we break up a big task into smaller steps, what we actually do isto ereate an algorithm, (v) Each step in an algorithm can be called as an instruction. (vi) In general, the steps in an algorithm can be divided in five basic categories. (vii) Avoiding a goto in a program, makes it a goto-less or top-down or structured. (viii). goto-less programs are difficult to understand. (ix) Sequence, selection and iteration form the building blocks for writing any algorithm, 12 13 14 1s 16 17 18 19) 1.10 Inrten to Computer and Programming 1.28 What are input devices? Briefly explain some popular input devices. What is the purpose of an output device? Explain various types of output devices. What is assembly language? What are its main advantages? What is high-level language? What are the different types of high-level languages? What is a flow chart? How is it different from an algorithm? What are the functions of a flow chart? Point down the differences between an algorithm and a flowchart Write an algorithm for withdrawing Rs. 1000 from the bank, Draw a flowchart for the above. Multiple Choice Questions 1 Which of the following is used to perform computations on the entered data? (a) Memory (b) Processor (©) Input device (d) Output device Which of the following is not an input device? (a) Plotter (b) Scanner (©) Keyboard (@) Mouse Which of the following is not an output device? (a) Plotter (b) Scanner (©) Printer (d) Speaker Which of the following is defined as a computer program for performing a particular task on the computer system? (a) Hardware (b)_ Software (6) Processor (d) Memory In which of the following languages, the instructions are written in the form of Os and 13? (a) Assembly language (b)_ Programming language (6) High-level language (@) Machine language Which one of the following is known as the ‘language of the computer”? (a) Programming language (b) High-level language (©) Machine language (d)_ Assembly language What are the three main categories of high-level language? (@) Low-level languages (b) Procedure oriented languages (©) Mechanical languages (a) Natural languages (©) Problem oriented languages Any C program (a) Must contain at least one function (b) Need not contain any function (©) Needs input data (d)_ None of the above — = ——_— ——— << ~ se ~ ——— ee a a Fundamentals of C Qa | History of C *C° seems a strange name for a programming language. But this strange sounding language is one of the most popular computer languages today because it is a structured, high-level, machine independent language. It allows software developers to develop programs without worrying about the hardware itforms where they will be implemented, C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972. C uses many concepts from these languages and added the conscepts of data types and other powerful features. Since it was developed along with the UNIX operating system, iti strongly associated with UNIX. This operating system, which was also developed at Bell Laboratories, was coded almost entirely in C. UNIX is one of the most popular network operating systems in use today and the heart of the Internet data superhighway. During 1970s, C had evolved into what is now known as "traditional C". To assure that the C language remains standard, in 1983, American National Standards Institute (ANSD appointed a technical committee to define a standard for C. The committee approved a version ‘of C in December 1989 which is now known as ANSI C. It was then approved by the International ‘Standards Organization (ISO) in 1990. This version of C is also referred to as C89. During 1990s, C++, a language entirely based on C, underwent a number of improvements and changes and became an ANSW/ISO approved language in November 1977. C++ added several new features to C to ‘make it not only a tre objectoriented language but also a more versatile language. During the same period, ‘Sun Microsystems of USA created a new language Java modelled on C and C+ Al popular computer languages are dynamic in nature, They continue to improve their power and scope by incorporating new features and C is no exception. Although C++ and Java were evolved out of , the standardization committee of C felt thata few features of C+/Java, if added to C, would enhance the usefilness ofthe language. The result was the 1999 standard for C. This version is usually referred to as C99, The history and development of C is illustrated in Fig. 2.1 22 Computer Programming and Uteaton so [Atco International Group aso | aceL Manin Ricnarse eee wom Km esc sora [Trait] oom te sore [pane] Remon ane a swe [avsie ANB connie sw [Tere ) Srdenton cones HERR) History of nse Although C99 is an improved version, still many commonly available compilers do not support all of the new features incorporated in C99, We, therefore, discuss all the new features added by C99 in an appendix separately so that the readers who are interested can quickly refer to the new material and use them wherever possible. 2.2 I Importance of C ‘The increasing popularity of C is probably due to its many desirable qualities. It is a robust language whose rich set of built-in functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a high-level language and therefore itis well suited for writing both system software and business packages. In fact, many of the C compilers available in the market are written in C. Programs written in C are efficient and fast. This is due to its variety of data types and powerful ‘operators. [tis many times faster than BASIC. For example, a program to increment a variable from 0 to 15000 takes about one second in C while it takes more than 50 seconds in an interpreter BASIC. Fundamenias of 23, There are only 32 keywords in ANSI C and its strength lies in its built functions are available which can be used for developing programs. Cis highly portable. This means that C programs written for one computer can be run on another with little or no modification. Portability is important if we plan to use a new computer with a different ‘operating system, C language is well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or blocks. A proper collection of these modules would make a complete program. This modular structure makes program debugging, testing and maintenance easier, ‘Another important feature of Cis its ability to extend itself. A C program is basically a collection of | functions that are supported by the C library. We can continuously add our own funetions to C library. With the availability of a large number of functions, the programming task becomes simple. Before discussing specific features of C, we shall look at some sample C programs, and analyze and understand how they work. functions, Several standard 2.3 | Sample Program I: Printing a Message Consider a very simple program given in Fig. 2.2. main() ‘ ProcouPELnting beginsnnnn*/ Printf("I see, I remember”); M printing ends. */ b A program to print one line of text This program when executed will produce the following output: 1 see, I renenber Let us have a close look at the program. The first line informs the system that the name of the program is main and the execution begins at this line. The main( ) is a special function used by the C system to tell the computer where the program starts. Every program must have exactly one main function, If we use more than one main funetion, the compiler cannot understand which one marks the beginning of the program. ‘The empty pair of parentheses immediately following main indicates that the function main has no arguments (or parameters). The concept of arguments will be discussed in detail later when we discuss functions (in Chapter 10) The opening brace “{ in the second line marks the beginning of the function main and the closing brace “}” in the last line indicates the end of the function. In this ease, the closing brace also marks the tend of the program. All the statements between these two braces form the function body. The function body contains a set of instructions to perform the given task, In this case, the function body contains three statements out of which only the printf line is an executable statement, The lines beginning with /* and ending with */ are known as comment lines. These are used in a program to enhance its readability and understanding, Comment lines are not executable 24 Computer Programming and Uteaton statements and therefore anything between /* and */ is ignored by the compiler. In general, a comment can be inserted wherever blank spaces can oecur—at the beginning, middle or end ofa line—“but never in the middle of a word” Although comments can appear anywhere, they cannot be nested in C, That means, we cannot have ‘comments inside comments. Once the compiler finds an opening token, it ignores everything. until it finds a closing token. The comment line eS a eee is not valid and therefore results in an error. Since comments do not affect the execution speed and the size of a compiled program, we should use them liberally in our programs. They help the programmers and other users in understanding the various functions and operations of a program and serve as an aid to debugging and testing. We shall see the use of comment lines more in the examples that follow. Let us now look at the printf( function, the only executable statement of the program. printe(*r 34 , t remember”); printf is a predefined standard C funetion for printing output, Predefined means that it i a function that has already been written and compiled, and linked together with our program atthe time of linking. ‘The concepts of compilation and linking are explained later in this chapter. The printf function cau: everything between the starting and the ending quotation marks to be printed out. In this ease, the output will be: 1 see, I remember Note that the print line ends with a semicolon. Every statement in C should end with a semicolon () mark. Suppose we want to print the above quotation in two lines as I see, I remember! This ean be achieved by adding another printf tion as shown below print£ (“I see, \n”); print ("I remember !"); The information contained between the parentheses is called the argument of the function, This argument of the first printf function is * I see, ‘n” and the second is “I remember !". These arguments, are simply strings of characters to be printed out Notice that the argument of the first printf contains a combination of two characters \ and m at the end of the string. This combination is collectively called the newline character. A newline character instructs the computer to go to the next (new) line. Its similar in concept to the carriage retum key on «typewriter. After printing the character comma (,) the presence of the newline character \m causes the string “I remember !" to be printed on the next line. No space is allowed between \ and n If we omit the newline character from the first printf statement, then the output will again be a single line as shown below. Fundomentas of 28 see, I remenber | This is similar to the output of the program in Fig. 2.2. However, note that there isno space between , and 1. It is also possible to produce two or more lines of output by one printf statement with the use of ‘newline character at appropriate places. For example, the statement print£(*I see,\n Z remember 1”) will output I see, T renenber ! while the statement print{( “1\n.. see,\n... .. T\n. . remember 1”); will print out I r xemember ! Note _|some authors recommend the inclusion ofthe statement include atthe beginning of all programs that use any input/output library functions. However, this is not necessary for the functions printf and scanf which have been defined as a part of the C languag Before we proceed to discuss further examples, we must note one important point. C does make a distinetion between uppercase and lowercase letters. For example, printf and PRINTF are not the same. In C, everything is written in lowerease letters. However, uppercase letters are used for symbolic names representing constants, We may also use uppercase letters in output strings like “I SEE” and “I REMEMBER” The above example that printed 1 see, I remember is one of the simplest programs. Figure 2.3 highlights the general format of such simple programs. All C programs need a main function. main () = }— suneton nme { }— ston of program =| Frooram statements pf nd ot rogram Format of simple C programs 26 Computer Programming and Ustzaton The main Function The main is a part of every C program. C permits different forms of main statement. Following forms are allowed. + main() + int main) * void main) + main(void) *+ void main(void) + int main(void) ‘The empty pair of parentheses indicates that the function has no arguments. This may be explicitly indicated by using the keyword void inside the parentheses. We may also specify the keyword int or void before the word main. The keyword void means that the function does not return any information to the operating system and int means thatthe function retums an integer value to the operating system. ‘When int is specified, the last statement in the program must be “return 0”. For the sake of simplicity, ‘we use the first form in our programs. 4 I Sample Program 2: Adding Two Numbers Consider another program, which performs addition on two numbers and displays the result, The complete program is shown in Fig. 2.4 7* Program ADDITION 7 /* Written by EBG " main() i ” ( ” int number; I o) float amount; i ” a ” number = 100; * +” a " amount = 30.75 + 75.35 + line-10 */ prints ("d\n” number) ; /* line-11 */ Printé("5.2£", amount) ; J+ Line-12 */ , i E] Program to add two numbers This program when executed will produce the following output: 100 106.10 The fitst two lines of the program are comment lines, It is a good practice to use comment lines in the beginning to give information such as name of the program, author, date, etc. Comment characters are also used in other lines to indicate line numbers Fundamentals of 27 ‘The words number and amount are variable names that are used to store numeric data, The numeric data may be either in integer form or in real form. In C, all variables should be declared to tell the compiler what the variable names are and what type of data they hold. The variables must be declared before they are used. In lines 5 and 6, the declarations int number; float amount; tell the compiler that number is an integer (int) and amount is a floating(float) point number. Declaration statements must appear at the beginning of the functions as shown in Fig. 2.4. All declaration statements end with a semicolon; C supports many other data types and they are discussed in detail in Chapter 3, The words such as int and float are called the keywords and cannot be used as variable names. A list of keywords is given in Chapter 3. Data is stored in a variable by assigning a data value to it, This is done in lines 8 and 10. In line- an integer value 100 is assigned to the integer variable number and in line-10, the result of addition of two real numbers 30.75 and 75.35 is assigned to the floating point variable amount. The statements number = 100 30.75 + 75.35; amount are called the assignment statements. Every assignment stafement must have a semicolon at the end. The next statement is an output statement that prints the value of number. The print statement printf (*éd\n", number) ; contains two arguments. The first argument “9d” tells the compiler that the value of the second argument number should be printed as a decimal integer. Note that these arguments are separated by a comma, The newline character \n causes the next output to appear on a new line. The last statement of the program print£("t5.2£", amount); prints out the value of amount in floating point format. The format specification %5.2/tells the compiler that the output must be in floating point, with five places in all and two places to the right of the decimal point. 2.5 || Sample Program 3: Interest Calculation ‘The program in Fig. 2.5 calculates the value of money at the end of each year of investment, assuming ‘an interest rate of 11 percent and prints the year, and the corresponding amount, in two columns. The ‘output is shown in Fig, 2.6 for a period of 10 years with an initial investment of 5000.00. The program uses the following formula Value at the end of year = Value at start of year (1 + interest rate) In the program, the variable value represents the value of money at the end of the year while amount represents the value of money at the start of the year. The statement anount = value ; makes the value at the end of the current year as the value at start of the next yeat. 28 Computer Programming and Uteaton 7 ivestuent PROBLEM ——————*7 #define PERIOD 10 define PRINCIPAL 5000.00 /*———— an PROGRAM BEGINS —————*/ main() { /*———— DECLARATION STATEMENTS ————*/ int ye float ancunt, value, inrate: /*-———— assicnven? starements ————*/ amount = PRINCIPAL? inrate = 0.11; year = 0; — COMPUTATION STATEMENTS — COMPUTATION USING While Loop ————*/ while(year <- PERIOD) ( printe ("2d $8.2£\n”,year, amount) ; value = amount + inrate * amount; year ~ year +1; while Loop ENDS ———+/ PROGRAM ENDS —————*/ Program for investment problem Let us consider the new features introduced in this program. The second and third lines begin with fHdefine instructions. A¥define instruction defines value to a symbolic constant for use in the program Whenever a symbolic name is encountered, the compiler substitutes the value associated with the ‘name automatically. To change the value, we have to simply change the definition. In this example, we have defined two symbolic constants PERIOD and PRINCIPAL and assigned values 10 and 5000.00 respectively. These values remain constant throughout the execution of the program 5000.00, 5550.00, 6160.50, 6838.15, 7590.35 8425.29 9352.07 10380.00 11522.69 12750.00 14197.11, EX] Output of the investment program Fundamentals of 28 The #define Directive A define is a preprocessor compiler directive and not a statement. Therefore #define lines should not end with a semicolon, Symbolic constants are generally written in upperease so that they are easily distinguished from lowercase variable names, #dlefine instructions are usually placed at the beginning before the main() function. Symbolic constants are not declared in declaration section, We must note that the defined constants are not variables. We may not change their values within the program by using an assignment statement. For example, the statement PRINCIPAL = 1000.00; is illegal The declaration section declares year as integer and amount, value and inrate as floating point numbers. Note all the floating-point variables are declared in one statement, They can also be declared float inrate; When two or more variables are dectared in one statement, they are separated by a comma, All computations and printing are accomplished in a while loop. while is a mechanism for evaluating repeatedly a statement or a group of statements. In this ease as long as the value of year is less than or equal to the value of PERIOD, the four statements that follow while are executed, Note that these four statements are grouped by braces. We exit the loop when year becomes greater than PERIOD. The ‘concept and types of loops are discussed in Chapter 7 C supports the bas discussed in Chapter 4. four arithmetic operators (-, +, *, /) along with several others. They are 2.6 I Sample Program 5: Use of Math Functions We often use standard mathematical functions such as cos, sin, exp, etc. We shall see now the use of @ mathematical function in a program. The standard mathematical functions are defined and kept asa part of C math library. If we want to use any of these mathematical functions, we must add an #inelude instruction in the program. Like #define, it is also a compiler directive that instructs the compiler to link the specified mathematical functions from the library. The instruction is of the form include math.h is the filename containing the required function. Figure 2.7 illustrates the use of cosine function ‘The program calculates cosine values for angles 0, 10, 20.....---...-180 and prints out the results with headings. /*———— PROGRAM USING COSINE FUNCTION ——— */ Hinelude Fdefine — FI3,1116 Fdefine — MAX150 main () { ant angle: Contd. 230 Computer Progamming ond Utizaton float x, angle ~ printf(" Angle cos(angle) \n\n"); while(angle <= AX) i x = (PI/MAX) tangles y = cos (x); prints("$15d $13.4\n", angle, y); angle = angle + 10; output Angle Cos (angle) 0 1.0000 10 0.9848 20 0.9397 30 0.8660 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 Program using a math function Another #inelude instruction that is often required is finclude stdio.h refers to the standard /O header file containing standard input and output functions The #include Directive As mentioned earlier, C programs are divided into modules or functions. Some functions are written by users, like us, and many others are stored in the C library. Library functions are grouped category- wise and stored in different files known as header files. If we Want to access the functions stored in the library itis necessary to tel the compiler about the files to be accessed. Fundamentals of 211 ‘This is achieved by using the preprocessor directive #include as follows: include=filename> filename is the name of the library file that contains the required function definition. Preprocessor directives are placed atthe beginning of a program. 2.7 || Basic Structure of C Programs ‘The examples discussed so far illustrate that a C program can be viewed as a group of building blocks, called functions. A function is a subroutine that may include one or more statements designed to perform ‘a specific task. To write aC program, we first create funetions and then put them together. A C program may contain one or more sections as shown in Fig. 2.8, Documentation Section Link Section. Definition Section Global Declaration Section ‘main () Function Section { Declaration part Executable part po Subprogram section| Function 1 Fuetion 2 5 (User-defines funetions) Fuetion An overview ofa C program The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. The link section provides instructions to the compiler to link functions from the system library. The definition section defines all symbolic constants There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined funetions. 242 Compute Progamming ond Uttzaton Every C program must have one main() function section. This section contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. ‘There is atleast one statement in the executable part. These two parts must appear between the opening, and the closing braces. The program execution begins at the opening brace and ends atthe closing brace. The closing brace of the main function section is the logical end of the program. Alll statements in the declaration and executable parts end with a semicolon(:) The subprogram section contains all the user-defined functions that are called in the main funetion. User-defined funetions are generally placed immediately after the main function, although they may appear in any order. All sections, except the main function section may be absent when they are not required. 2.8 I Programming Style C is a free-form language. That is, the C compiler does not care, where on the line we begin typing. While this may be a licence for bad programming, we should try to use this fact to our advantage in developing readable programs. Although several alternative styles are possible, we should select one style and use it with total consistency. First of all, we must develop the habit of writing programs in lowercase leters. C program statements are written in lowercase letters. Uppercase letters are used only for symbolic constants Braces, group program statements together and mark the beginning and the end of functions. A proper indentation of braces and statements would make a program easier to read and debug. Note how the braces are aligned and the statements are indented in the program of Fig. 2.5. Since C is a free-form language, we can group statements together on one line. The statements ab: xeyea ccan be written on one line as a= bp x= yt; 2 = ate: ‘The program main( ) t printf ("hello ¢”); ) ‘may be written in one line like main( ) (printe(*Hello C”)); However, this style makes the program more difficult to understand and should not be used. In this book, each statement is written on a separate line. The generous use of comments inside a program cannot be overemphasized. Judiciously inserted ‘comments not only increase the readability but also help to understand the program logic. This is very important for debugging and testing the program. Fundamontae of 213, 2.9 || Executing a‘C’ Program Executing a program written in C involves a series of steps. These are: 1. Creating the program; 2. Compiling the program; 3. Linking the program with functions that are needed from the C library; and 4. Executing the program. Figure 2.9 illustrates the process of ereating, compiling and executing a C program. Although these steps remain the same irrespective of the operating system, system commands for implementing the steps and conventions for naming files may differ on different systems. {_System Ready} ~{_ Ener Prowram_| 7 Sauce Program ea cost hen (_cccemier }—-| sours Program oY on T cesousti ones code [rotons | —{ ogre Data Error Logie Error No Errors ¥ ‘CORRECT OUTPUT| Process of compiling and running a C program Computer Programing and Utzaton An operating system is a program that controls the entire operation of a computer system. All input/output operations are channeled through the operating system. The operating system, which is an interface between the hardware and the user, handles the execution of user programs, The two most popular operating systems today are UNIX (for minicomputers) and MS-DOS (for microcomputers). Just Remember + Every C program requires a main() function (Lise of more than one main( is illegal). The place iain is where the program execution begins + The execution of a function begins at the opening brace of the function and ends at the corresponding closing brace. + C programs are written in lowercase letters. However, uppercase letters are used for symbolic ‘names and output strings. + All the words in a program line must be separated from each other by at least one space, or a tab, or a punctuation mark, + Every program statement in a C language must end with a semicolon, + All variables must be declared for their types before they are used in the program, + We must make sure to include header files using #include directive when the program refers to special names and functions that it does not define. + Compiler directives such as define and include are special instructions to the compiler to help it compile a program. They do not end with a semicolon. + The sign # of compiler directives must appear in the first column of the fine. + When braces are used to group statements, make sure that the opening brace has a corresponding closing brace. *+ Cis free-form language and therefore a proper form of indentation of various sections would improve legibility of the program + A comment can be inserted almost anywhere a space can appear. Use of appropriate comments in proper places increases readability and understandability of the program and helps users in debugging and testing. Remember to match the symbols /* and */ appropriately. Review Questions 2.1, State whether the following statements are true or false. (@) Every line ina C program should end with a semicolon, (b) In C language lowercase letters are significant. (6) Every C program ends with an END word. (4) main() is where the program begins its execution, (©) Aline in a program may have more than one statement. (8) A printf statement can generate only one line of output. (g) The closing brace of the main( ) in a program is the logical end of the program. (h) The purpose of the header file such as stdi.h is to store the source code of a program, Fundamoniae of 218 (i) Comments cause the computer to print the text enclosed between /* and */ when executed. (i) Syntax errors will be detected by the compiler. 2.2. Which of the following statements are srue? (a) Every C program must have at least one user-defined function. (b) Only one function may be named main( (6) Declaration section contains instructions to the computer. 2.3. Which of the following statements about comments are false? (a) Use of comments reduces the speed of execution of a program. (b) Comments serve as internal documentation for programmers, (6) Acomment can be inserted in the middle of a statement. (@ InC, we ean have comments inside comments 2.4 Fill in the blanks with appropriate words in each of the following statements, (a) Every program statement in a € program must end with a (b) The ____Funetion is used to display the output on the sereen. (©) The ___ header file contains mathematical functions. (@) The escape sequence character ‘causes the cursor to move to the next line on the screen 2.5 Remove the semicolon at the end of the printf statement in the program of Fig. 1.2 and execute it, What is the output? 2.6 In the Sample Program 2, delete line-5 and execute the program, How helpful is the error message? 2.7 Modify the Sample Program 3 to display the following output Year Amount 1 5500.00 2 6160.00 10 14197.11 2.8 Find errors, if any, in the following program: /* simple program int maint) ( /* Does nothing */ b 2.9 Find errors, if any, in the following program Hinelude (stdio.n yoid main (void) ( print ("Hello c*); , 2.10 Find errors, if any, in the following program: Inelude main ( ‘ 216 Compute Progamming ond Utiaton FLOAT Xz x= 2.5 Y= exptx) Print Gy) 7 2.11 Why and when do we use the #aefine directive? 2.12. Why and when do we use the #include directive? 2.13 What does void main(void) mean? 2.14 Distinguish between the following pairs: (a) main( ) and void main(void) (b) int main( ) and void main( ) 2.15, Why do we need fo use comments in programs? 2.16 Why is the look of a program is important? 2.17, Where are blank spaces permitted in a C program? 2.18 Describe the structure of a C program. 2.19 Describe the process of creating and executing a C program under UNIX system. 2.20. How do we implement multiple source program files? Programming Exercises 2.1 Write a program that will print your mailing address in the following form: First line Name Second line : Door No, Street Third line : City, Pincode 2.2. Modify the above program to provide border lines to the address. 2.3 Write a program using one print statement to print the pattern of asterisks as shown below: 2.4 Write a program that will print the following figure using suitable characters, a—_-oBa 2.5 Given the radius of a circle, write a program to compute and display its area, Use a symbolic constant to define the m value and assume a suitable value for radius. 2.6 Write a program to output the following multiplication table: Sxl =5 5x2 =10 5x3 =15 5x 10=50 27 28 29 2.10 Das Fundamontas of 2.17 Given two integers 20 and 10, write a program that uses a function add( ) to add these two ‘numbers and sub( ) to find the difference of these two numbers and then display the sum and difference in the following form: 20+ 10-30 20-1010 Given the values of three variables a, b and e, write a program to compute and display the value of x, where boc Execute your program for the following values: (a) a= 250,b=85,¢= 25 (b) a= 300, b=70,¢= 70 ‘Comment on the output in each case, Relationship between Celsius and Fahrenheit is governed by the formula 32 3 Write a program to convert the temperature (a) from Celsius to Fahrenheit and (b) from Fahrenheit to Celsius. ‘Area of a triangle is given by the formula A = BCalSHE) Where a, b and c are sides of the triangle and 2S = a + b + c, Write a program to compute the area of the triangle given the values of a, b and c Distance between two points (x), y,) and (x, y2) is governed by the formula F a -X 102-91 Write a program to compute D given the coordinates ofthe points A point on the circumference of a circle whose center is (0, 0) is (4.5). Write a program to ‘compute perimeter and area of the circle, (Hint: use the formula given in the Ex. 2.11) The line joining the points (2,2) and (5,6) which lie on the circumference of a circle is the diameter of the circle. Write a program to compute the area of the circle. Write a program to display the equation ofa line in the form axthy for a=5,b=8 and c=18 Write a program to display the following simple arithmetic calculator 218 Computer Progamming ond Utizaton Debugging Exercises |] 2.1. Identify the error in the following program: Finclude Hinclude void main() eng sun: printf ("Enter the value of nt"); 1/*Reading value of n*/ wen) sum=sun+pow (2,1) ;/*Calculating the sun of the series*/ } printf ("sum of series = $1d\n",sum) ; ’ 2.2 Identify the error in the following program: Hinelude Hinclude void main() ‘ int xy long printf ("snter the value of x: "); scan ("sd", §x);/*Reading the value of x*/ print£("Enter the value of y: "); seant ("ia", by) 1/*Reading the value of y*/ zepower(x,y)#/*Calling the built-in function*/ print£("id to the power of Sd is equal to $a", x, yy 2)? , 2.3. Identify the error in the following program: Hinelude void main() ‘ iat nuns print£("\nEnter a number: "); ‘scant ("sa", énun) :/*Reading an Integer*/ Lf (num#2=0) /+Using % operator to compute the remainder value*/ Fundamontas of 2 print£("\ntd is an even number", num); else printf ("\ntd is an odd number", num); > 24 Identify the error in the following statements: (a) void xi ©) For is0;iclOsietye © int i= 10 char *ptr = G4; @ char ch = *377 printé (*\n\nta", ch) 7 © int i = 106; printé(*\n\nte", i); “ int int iz — = — —Ss Se = = Sa Ss a Data Types in C Ba | Introduction A programming language is designed to help process certain kinds of data consisting of numbers, ‘characters and strings and to provide useful output known as information. The task of processing of data is accomplished by executing a sequence of precise instructions called a program, These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules (or grammar), Every program instruction must confirm precisely to the syntax rules of the language. Like any other language, C has its own vocabulary and grammar. In this chapter, we will discuss the concepts of constants and variables and their types as they relate to C programming language. 32 ll Character Set ‘The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run, However, a subset of characters is available that can be used on most personal, micro, mini and mainframe computers, The characters in C are grouped into the following categories: 1. Letters 2. Digits 3. Special characters 4. White spaces The entire character set is given in Table 3.1 The compiler ignores white spaces unless they are a part of a string constant. White spaces may be used to separate words, but are prohibited between the characters of keywords and identifiers. 3.24. Trigraph Characters Many non-English keyboards do not support all the characters mentioned in Table 3.1. ANSI introduces the concept of “irigraph” sequences to provide a way to enter certain characters that are not available on Smtues an Unions 1237 ‘Note that the compile-time initialization of a structure variable must have the following elements: ‘The keyword struct. ‘The structure tag name, ‘The name of the variable to be declared. ‘The assignment operator =, ‘A set of values for the members of the structure variable, separated by commas and enclosed in braces. 6. A terminating semicolon. Rules for Initializing Structures ‘There are a few rules to keep in mind while initializing structure variables at compile-time, 1. We eannot initialize individual members inside the structure template, 2. The order of values enclosed in braces must match the onder of members in the structure definition. 3. Iis permitted to have a partial initialization. We can initialize only the first few members and leave the remaining blank. The uninitialized members should be only at the end of thelist 4. The uninitialized members will be assigned default values as follows: + Zero for intoger and floating point numbers. "0 for characters and strings. 12.6 || Copying and Comparing Structure Variables ‘Two variables of the same structure type can be copied the same way as ordinary variables. If personl and person2 belong to the same structure, then the following statements are valid: personi = persen: person? = personl; However, the statements such as person != person2 are not permitted. C does not permit any logical operations on structure variables. In case, we need t0 ‘compare them, we may do so by comparing members individually. Example 12.2 Write a program to illstrate the comparison of sructure variables. The program shown in Fig. 12.2 illustrates how a structure variable can be copied into another of the same type. It also performs member-wise comparison to decide whether two structure variables are identical, Program struct class ‘ int number; char name [20]? float marks; Com. 128 Computer Programming and Utizaen main() ‘ struct class studentl = (111,"Ra0", 72.50); struct class student2 = (222, "Reddy", 67.0017 struct class student3; student3 = studenta; x = ((student3.number (student3.marks student?.nunber) 55 student2.marks)) ? 1 if(x == 1) ‘ printf ("\nstudent2 and student3 are same\n\n"); printf ("$d %s $f\n", student3.nunber, student3.name, student3.marks) ; ) else printé(*"\nstudent2 and student3 are different\n\n") ; > output student? and student3 are sane 222 Reddy 67.000000 Comparing and copying structure variables Word Boundaries and Slack Bytes Computer stores structures using the concept of “word boundary”, The size of a word boundary is ‘machine dependent, In a computer with two bytes word boundary, the members of a structure are stored Teft_aligned on the word boundary, as shown below. A character data takes one byte and an integer takes two bytes, One byte between them is left unoccupied. This unoccupied byte is known as the slack byte. i 1 — slack byle ‘When we declare structure variables, each one of them may contain slack bytes and the values stored in such slack bytes are undefined. Due to this, even if the members of two variables are equal, their Contd, 1210 Gamputey Programming and Uzaton struct class student {100}; defines an array called student, that consists of 100 elements. Each element is defined to be of the type struct class. Consider the following declaration: struct marks { int subject: int subject2; int subj} struct marks student (3] = (45, 68,81}, (75,53, 69}, (57,36, 72) he ‘This declares the student as an array of three elements student{0}, student{1}, and student{2] and initializes their members as follows: student (0) .subject1 student (0] .subject2 student [2] .subject3 = 71; Note that the array is declared just as it would have been with any other array. Since student is an array, we use the usual array-accessing methods to access individual elements and then the member ‘operator to access members. Remember, each clement of student array isa structure variable with three members. An array of structures is stored inside the memory in the same way as a multi-dimensional array. ‘The array student actually looks as shown in Fig. 123. student] subject 1 65 subject 2 68 subject 3 8 student [1] subject 1 75 subject 2 53 subject’3 cy student [2 subject 1 57 subject 2 36 subject 3 a The arvay student inside memory Example 12.3 For the student aray discussed above, write a program to calculate the subject and studentwvise totals and store them as apart of the structure. Stoctes and Unions 12:31 Write a program to do the following ‘To read details for 5 cities randomly using an array variable To sont the list alphabetically ‘To sont the list based on literacy level To sor the list based on population ‘+ To display sorted lists 12.13 Define a structure that can describe a hotel. It should have members that include the name, address, grade, average room charge, and number of rooms, Write functions to perform the following operations: ‘+ To print out hotels of a given grade in order of charges ‘© To print out hotels with room charges less than a given value 12.14 Define a structure called erieket that will deseribe the following information: player name team name batting average Using erieket, declare an array player with 50 elements and write a program to read the information about all the 50 players and print a team-wise list containing names of players with their batting average. 12.15. Design a structure student_record to contain name, date of birth and total marks obtained. Use the date structure designed in Exercise 12.4 to represent the date of birth. Develop a program to read data for 10 students in a class and list them rank-wise. Debugging B l 12.1. Identify the error in the following code, if any: tincludecstdio.n> void main() ‘ int *pter a=50; Dt int? print? ("address of ptr = wu\tvalue of ptr = § davess of a = Su\tvalue of a = Sd\n" ptr, Trapteys ",apte, ptr); ’ 12.2. Identify the error the following code, if any: ¥includecstdio.h> void main() = 1 a = oN Principles of Object-Oriented Programming 13.1 || Software Crisis Developments in software technology continue to be dynamic. New tools and techniques are announced in quick succession. This has forced the software engineers and industry to continuously look for new approaches to software design and development, and they are becoming more and more critical in view of the increasing complexity of software systems as well as the highly competitive nature of the industry. These rapid advances appear to have ereated a situation of crisis within the industry. The following issues need to be addressed to face this cri + How to represent real-life entities of problems in system design? + How to design systems with open interfaces? + How to ensure reusability and extensibility of modules? + How to develop modules that are tolerant to any changes in future? + How to imptove software productivity and decrease software cost? + How to improve the quality of software? + How to manage time schedules? + How to industrialize the software development process? Many software products are either not finished, or not used, or else are delivered with major errors. Figure 13.1 shows the fate of the US defence software projects undertaken in the 1970s. Around 50% of the software products were never delivered, and one-third of those which were delivered were never used. It is interesting to note that only 2% were used as delivered, without being subjected to any changes. This illustrates that the software industry has a remarkably bad record in delivering products. Principles of Object Orerea Programming 13.5 In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Figure 13.5 shows the relationship of data and functions in a procedure-oriented program. Global data are more vulnerable to an inadvertent change by a function, In a large program it is very difficult to identify what data is used by which function. In case we need to revise an extemal data structure, ‘we also need to revise all functions that access the data. This provides an opportunity for bugs to creep in. Another serious drawback with the procedural approach is that it does not model real world problems ‘very well. This is because functions are action-oriented and do not really correspond to the elements of the problem. ob data otal data Functon Function 2 Functon 3 Loca deta Local ata Loca data Relationship of data and functions i procedural programming Some characteristics exhibited by procedure-oriented programming are: + Emphasis is on doing things (algorithms). + Large programs are divided into smaller programs known as functions. + Most of the functions share global data + Data move openly around the system from funetion to funetion. + Functions transform data from one form to another. + Employs top-down approach in program design. 13.4 l Object-Oriented Programming Paradigm ‘The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The organization of data and functions in object-oriented programs is, shown in Fig. 13.6. The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects. 136 Computer Progranming and Uiteation ‘Some of the striking features of object-oriented programming are: + Emphasis is on data rather than procedure. + Programs are divided into what are known as objects. + Data structures are designed such that they characterize the objects. + Functions that operate on the data of an object are tied together in the data structure. + Data is hidden and cannot be accessed by external funetions + Objects may communicate with each other through funetions, + New data and functions can be easily added whenever necessary. + Follows bottom-up approach in program design. Object A Object B [Bata] [ata] Communication Functions Functions Object C Functions| aa] Organization of data and functions in OOP Object-oriented programming is the most recent concept among programming paradigms and still means different things to different people. It is therefore important to have a working definition of object-oriented programming before we proceed further, We define “object-oriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.” ‘Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modifications 13-5 {| Basic Concepts of Object-Oriented Programming It is necessary to understand some of the concepts used extensively in object-oriented programming, ‘These include: + Objects + Classes + Data abstraction and encapsulation + Inheritance Principles of Object Oreres Programing 13.7 + Polymorphism + Dynamic binding + Message passing We shall discuss these concepts in some detail in this section. 13.54 Objects Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle, They may also represent user-defined data such as vectors, time and lists. Programming problem is analyzed in terms of objects and the nature of communication between them. Program objects should be chosen such that they match closely with the real-world objects. Objects take up space in the memory and have an associated address like a record in Pascal, or a structure in C ‘When a program is executed, the objects interact by sending messages to one another. For example, if “customer”and “account” are two objects in a program, then the customer object may send a message to the account object requesting for the bank balance. Each object contains data, and code to manipulate the data. Objects can interact without having to know details of each other’s data or code. I is sufficient to know the type of message accepted, and the type of response returned by the objects. Although different authors represent them differently, Fig. 13.7 shows two notations that are popularly used in object-oriented analysis and design. (Object: STUDENT STUDENT DATA Total Name Date-of-bith Marks ‘Average FUNCTIONS: Total ‘Average Display Display "oo ways of representing an abject 13.5.2 Classes ‘We just mentioned that objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In fact, objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit. Classes are user-defined data types and behave like the built-in types of a programming language. The syntax used to create an object is no different than the syntax used to create an integer object in C. If fruit has been defined as a class, then the statement fruit mango; will create an object mango belonging to the class fruit. Pine Cj! Cred Proaming 1.13 13.8 || Applications of OOP OOP has become one of the programming buzzwords today. There appears to be a great deal of excitement and interest among software engineers in using OOP. Applications of OOP are beginning to gain importance in many areas. The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as windows. Hundreds of ‘windowing systems have been developed, using the OOP techniques. Real-business systems are often much more complex and contain many more objects with complicated attributes and methods. OOP is useful in these types of applications because it can simplify a complex problem. The promising areas for application of OOP include: + Real-time systems + Simulation and modeling + Object-oriented databases + Hypertext, hypermedia and expertext + AL and expert systems + Neural networks and parallel programming. + Decision support and office automation systems + CIMCAMICAD systems The richness of OOP environment has enabled the software industry to improve not only the quality of software systems but also its productivity. Object-oriented technology is certainly changing the way the software engincers think, analyze, design and implement systems saa + Software technology has evolved through a series of phases during the last five decades. + ‘The most popular phase till recently was procedure-oriented programming (POP), + POP employs top-down programming approach where a problem is viewed as a sequence of tasks to be performed, A number of functions are written to implement these tasks. + POP has two major drawbacks, viz. (1) data move freely around the program and are therefore ‘vulnerable to changes caused by any function in the program, and (2) it does not model very well the real-world problems. + Object-oriented programming (OOP) was invented to overcome the drawbacks of the POP. It employs the bottom-up programming approach, It treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data mote closely to the functions that operate on it in a data structure called elass. This feature is called data encapsulation. + In OOP, a problem is considered as a collection of a number of entities called objects. Objects are instances of classes, + Insulation of data from direct access by the program is called data hiding. + Data abstraction refers to putting together essential features without including background details ou Computer Programming and ization Inheritance is the process by which objects of one class aequire properties of objects of another class, Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program. It also allows overloading of operators so that an operation can exhibit different behaviours in different instances. Dynamic binding means that the code associated with a given procedure is not known until the time of the call at run-time. ‘Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent Object-oriented technology offers several benefits over the conventional programming methods- ~the most important one being the reusability. Applications of OOP technology has gained importance in almost all areas of computing including real-time business systems. There are a number of languages that support object-oriented programming paradigm. Popular among them are C++, Smalltalk and Java. C+ has become an industry standard language today. Review Questions 134 13.2 13.3 134 135 136 137 13.8 13.9 13.10 13.11 13.12 13.13 1314 13.15 ‘What do you think are the major issues facing the software industry today? Briefly discuss the software evolution during the period 1950 — 1990, What is procedure-oriented programming? What are its main characteristics? Discuss an approach to the development of procedure-oriented programs. Describe how data are shared by functions in a procedure-oriented program. What is object-oriented programming? How is it different from the procedure-oriented programming? How are data and funetions organized in an object-oriented program? What are the unique advantages of an object-oriented programming paradigm? Distinguish between the following terms (a) Objects and classes (b) Data abstraction and data encapsulation (©) Inheritance and polymorphism (@) Dynamic binding and message passing ‘What kinds of things can become objects in OOP? Describe inheritance as applied to OOP. What do you mean by dynamic binding? How is it useful in OOP? How does object-oriented approach differ from object-based approach? List a few areas of application of OOP technology. State whether the following statements are TRUE or FALSE. (a) In procedure-oriented programming, all data are shared by all functions. (b) The main emphasis of procedure-oriented programming is on algorithms rather than on ata Pinapes of Object Oneted Programming 13:18 (©) One of the striking features of object-oriented programming is the division of programs into “objects that represent real-world entities (4) Wrapping up of data of different types into a single unit is known as encapsulation. (e) One problem with OOP is that once a class is ereated it can never be changed (f) Inheritance means the ability to reuse the data values of one object by (g) Polymorphism is extensively used in implementing inheritance, (b) Object-oriented programs are executed much faster than conventional programs. (i) Object-oriented systems can scale up better from small to large. () Object-oriented approach cannot be used to create databases, Beginning with C++ 14.1 || Whatis C++? C+ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980's. Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the languages and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of C. The result was C++, Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula67, Since the class was a major addition to the original C language, Stroustrup initially called the new language *C with classes’, However, later in 1983, the name was changed to C++. The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is an augmented (incremented) version of C. During the early 1990's the language underwent a number of improvements and changes. In November 1997, the ANSI/ISO standards committee standardised these changes and added several new features to the language specifications. C+ is a superset of C. Most of what we already know about C applies to C+ also. Therefore, almost all C programs are also C-++ programs. However, there are a few minor differences that will prevent a C program to run under C++ compiler. We shall see these differences later as and when they are encountered, ‘The most important f . function overloading, and operator overloading, These features enable creating of abstract data types, inherit properties from existing data types and support polymorphism, thereby making C++ a truly object-oriented language. The object-oriented features in C++ allow programmers to build large programs with clarity, extensibility and ease of maintenance, incorporating the spirit and efficieney of C. The addition of new features has transformed C from a language that currently facilitates top-down, structured design, to one that provides bottom-up, object-oriented design. 44 Computer Progranming and Uiteation The object cout has a simple interface. IF string represents a string variable, then the following statement will display its contents: cout << strings You may recall that the operator << is the bit-wise left-shift operator and it can stil be used for this purpose. This is an example of how one operator can be used for different purposes, depending on the context. This concept is known as operator overloading, an important aspect of polymorphism. It is important to note that we can still use printf() for displaying an output, C++ accepts this notation, However, we will use cout << to maintain the spirit of C+ 14.3.4 The iostream File We have used the following include directive in the program: #include This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier eout and the operator <<, Some old versions of C++ use a header file called iostream.h. This is one of the changes introduced by ANSI C++. (We should use iostream.h if the compiler does not support ANSI C++ features.) The header file iostream should be included at the beginning of all programs that use input/output statements. Note that the naming conventions for header files may vary. Some implementations use iostream.hpp: yet others iostream.hxx. We must include appropriate header files depending on the contents of the program and implementation, Tables 14.1 and 14.2 provide lists of C+ standard library header files that may be needed in C+ programs. The header files with .h extension are “old style” files which should be used with old compilers, Table 14.1 also gives the version of these files that should be used with the ANSI standard compilers. Commonly used old-style header files Header file Contents and purpose New version “ Contains macros andinformaion foradding agnosis that ad program debugging Contains function protolypes fr functions that tst charactors fr certain. ropertes, and function prottypes for functions that can be used to Convert lowercase ltes o uppercase ltrs and vice versa, stot i> Contains the floating-point size limits ofthe system, Contains the integral size limits ofthe system.
Contains function prtetypes for math ibrar functions Contains function prototypes forte standard inputlouput brary functions and informaton used by them. Contains function prototypes for conversion of numbers to text, texto numbers, memory allocation, random numbers, and various other utlty functions. Contd. BEE Cooney Begining wh C++ 145 Header file Contents and purpose ‘New version «sting > Contzins function protatypes for Cte sting processing functions. Contains function prototypes and types for manipulating the te and dele. Contains function protatypes forthe standard input and standard output functions. Contains funcion protlypes for the stream manipulators that enable formating of steams of data. ‘stream te Contains funcion prototypes for functions that perform input fom fles on disk and utputtofles on disk. New header files included in ANSI C++ Header file ‘uty vector, , , ,, ‘stacks, functional» memory» terato> , Contents and purpose Contains dasses and functions that are used by many standard library headar files. The header fles contain classes that implement the standard brary containers. Containers ‘lore data during a program's execution. Contains lasses and functions used by algorithms ofthe standard ibray. Contains classes and functions used bythe standard iar to allocate memory to the standard brary containers. Contains classes for manipulating data in the standard library containers. Contains functions for manipulating data in the standard ibrar containers. ‘These header files contain classes that are used for exception handing, Contains the definition of class string from the standard library. Contains funtion protclyps fr functions that perform input rom stings in memory and output to strings in memory Contains casses andfuncons narmaly used by steam processing to process data inthe natural form for ciferent languages (e., monetary formats, sorting stings, character presentation, ec) Contains a class for dfring the numerical data type limi on each computer platform. Contains dass for runtime type identification (determining datatypes at execution time). 14.35 Namespace Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope for the identifiers that are used in a program. For using the identifiers defined in the namespace scope we ‘must include the using directive, like ‘using nanespace std; Here, std is the nams programs must space where ANSI C++ standard class libraries are defined, All ANSI C-+* clude this directive. This will bring all the identifiers defined in std to the current global scope. using and namespace are the new keywords of C++. Begining wh c++ 149 p.getdatai); p-display(); return 0; output Enter Nane: Ravinder Enter age: 30 Name: Ravinder Age: 30 Use ofelass ina C++ program [Note] ein can ead only one word and therefore we cannot use names with Blank spaces The program defines person as a new data of type class. The class person includes two basic data type items and two functions to operate on that data. ‘These functions are called member functions, The main program uses person to declare variables of its type. As pointed out earlier, class variables are known as objects. Here, p is an object of type person. Class objects are used to invoke the functions defined in that class, More about classes and objects is discussed in Chapter 17. 14.6 || Structure of C++ Program As it can be seen a typical C+ program would contain four sections as shown in Fig, 14.6. These sections may be placed in separate code files and then compiled independently or jointly. Include fles Class declaration Member functions definitions Main function program Structure of a C++ program It is a common practice to organize a program into three separate files. The class declarations are placed in a header file and the definitions of member functions go into another file, This approach enables the programmer to separate the abstract specification of the interface (class definition) from the implementation details (member functions definition). Finally, the main program that uses the class is placed in a third file which “includes” the previous two files as well as any other files required ogling wih C++ 1413 142 Identify the error in the following program, Hinclude void main() ( short 1=2500, j=3000; cout >> + J = * >> - UH)? , 143 What will happen when you run the following program? Hinclude void main() i modResult = 1347 cout << modResult << divResult = i/modResult; cout <¢ divResult; ' 144 Find errors, if any, in the following C++ statements. (a) cout <<“x=" x; (>) m=S5;//n=10;// (©) cin>>x;>>y; (@) cout <<\n “Name:” << name; (©) cout <<"Enter value:”; cin >> x; () /*Addition*/ z= x + =m+n; = 1 Tokens, Expressions and Control Structures 15.1 || Introduction ‘As mentioned earlier, C++ is a superset of C and therefore most constructs of C are legal in C++ with their meaning unchanged. However, there are some exceptions and additions. In this chapter, we shall discuss these exceptions and additions with respect to tokens and control structures, 15.2 |] Tokens As we know, the smallest individual units in a program are known as toker tokens: (C+ has the following © Keywords © Identifiers © Constants Strings © Operators A C+ program is written using these tokens, white spaces, and the syntax of the language. Most of the C++ tokens are basically similar to the C tokens with the exception of some additions and minor modifications, 15 {| Keywords ‘The keywords implement specific C++ language features. They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements. 152 Computer Progranming ant Uizaton Table 15.1 gives the complete set of C++ keywords. Many of them are common to both C and C+. ‘The ANSI C keywords are shown in boldface. Additional keywords have been added to the ANSI C keywords in order to enhance its features and make it an object-oriented language, ANSI C+ standards committee has added some more keywords to make the language more versatile. These are shown separately. Meaning and purpose of all C++ keywords are given in Appendix D. Ces kepwords asm double new ‘switen auto else operator template break enum private this case extern protected throw catch float public ty char for register typedet cass fiend return union const goto short unsigned continue # signed virtual default ining sizeof void delete it static volatile do tong, struct while ‘Adied by ANSIC+* boo! export reinterpret cast ‘typename const_cast false stabc_cast using dynamic_east mutable we wehart explicit namespace ‘ypeid [Note] rhe Awsr keywords are shown in botd face. 15.4 I Identifiers and Constants Identifiers refer to the names of variables, functions, arrays, classes, ete. created by the programmer. ‘They are the fundamental requirement of any language. Each language has its own rules for naming these identifiers. The following rules are common to both C and C+: Only alphabetic characters, digits and underscores are permitted. The name cannot start with a digit Uppercase and lowercase letters are distinct A declared keyword cannot be used as a variable name. A major difference between C and C+ the limit on the length of a name. While ANSI C recognizes only the first 32 characters in a name, ANSI C++ places no limit on its length and, therefore, all the characters in @ name are significant. Tokens, Expressions and ContolStucues 153 Care should be exercised while naming a variable which is being shared by more than one file containing C and C++ programs. Some operating systems impose a restriction on the length of suel variable name. Constants refer to fixed values that do not change during the execution of a program. Like C, C+ supports several kinds of literal constants. They include integers, characters, floating. point numbers and strings. Literal constant do not have memory locations. Examples: 123 // decimal integer 12.34 —// floating point integer 037 // octal integer ox2 (/ hexadecimal integer vce" // string constant sar // character constant Lab’ // wide-character constant The wehar_t type is a wide-character literal introduced by ANSI C+ and is intended for character sets that cannot fit a character into a single byte, Wide-character literals begin with the letter L. (C+ also recognizes all the backslash character constants available in C. [Note] c++ supports ovo types of string representation — the C-style character string and the string classtype jntroduced with Standard C+. Although the use ofthe string classtype is recommended. iti advisable to understand and use C-syle strings in some situations. 15.5 ll Basic Data Types Data types in C++ can be classified under various categories as shown in Fig. 15.1. eo a boone pe ane cnnesie oat ny whee tren con ow a rence Integral type Void Floating ype | om] Lew vet} [i ierarehy of C++ datatype 154 Computer Prograrming and Uiteation Both C and C+ compilers support all the built-in (also known as basic or fundamental) data types. With the exception of void, the basic data types may have several modifiers preceding them to serve the needs of various situations. The modifiers signed, unsigned, long, and short may be applied to character and integer basic data types. However, the modifier long may also be applied to double. Data type representation is machine specific in C++. Table 15.2 lists all combinations of the basic data types and modifiers along with their size and range for a 16-bit word machine. Size and range of C++ basie data types Tyee. Bytes Range char 1 12810 127, unsigned char 1 010255, signed char 1 = 12810 127, int 2 = 32768 to 32767 unsigned int 2 01065535 signed int 2 ~ 31768 to 32767 shor int 2 = 31766 to 32767 unsigned shor int 2 01065535 signed shot int 2 32768 to 32767 Jong int 4 2147483648 to 2147489647 signed long int 4 2147483648 to 2147489647 unsigned lng int 4 00 4204967205 float 4 346-88 0 34E+38 double 8 176-308 0 1.7E+308 Jong double 10 346-4932 to 1.164992 ANSI C++ committee has added two more data types, bool and wehar_t, The type void was introduced in ANSI C. Two normal uses of void are (1) to specify the return type ofa function when itis not returning any value, and (2) to indicate an empty argument list to a function. Example: void functl (void) : Another interesting use of void is in the declaration of generic pointers. Example: U1 gp becomes generic pointer void *g} ‘A genetic pointer can be assigned a pointer value of any basic data type, but it may not be dereferenced. For example, nt Mp gp = ip: are valid statements, But, the statement, sip = “ape is illegal. It would not make sense to dereference a pointer to a void value Uf Ant pointer V/ assign int pointer to void pointer Tokens, Expressions and ContolStucues 155 Assigning any pointer type to a void pointer without using a cast is allowed in both C++ and ANSI C. In ANSI C, we can also assign a void pointer to a non-void pointer without using a cast to non-void pointer type. This is not allowed in C++. For example, void *ptrl; char *ptr2; ptr? = perl; are all valid statements in ANSI C but not in C++. A void pointer cannot be directly assigned to other type pointers in C++. We need to use a cast operator as shown below ptr2 = (char *)ptrly ||| User-Defined Data Types 15. 15.6.1 Structures and Classes We have used user-defined data types such as struet and union in C. While these data types are legal in C++, some more features have been added to make them suitable for object-oriented programming, C+ also permits us to define another user-defined data type known as eass which can be used, just like any other basic data type, to declare variables. The class variables are known as objects, which are the central focus of object-oriented programming. More about these data types is discussed later in Chapter 17. 15.6.2 Enumerated Data Type ‘An enumerated data type is another user-defined type which provides a way for attaching names to numbers, thereby increasing comprehensibility of the code. The enum keyword (from C) automatically enumerates alist of words by assigning them values 0,1,2, and so on. This facility provides an alternative ‘means for creating symbolic constants. The syntax of an enum statement is similar to that of the struct statement, Examples enum shape{circle, square, triangle): enum colour(red, blue, green, yellow}: enum position{off, on}: ‘The enumerated data types differ slightly in C+-+ when compared with those in ANSI C. In C++, the tag names shape, colour, and position become new type names. By using these tag names, we can declare new variables. Examples: shape ellipse: // ellipse is of type shape colour backsround; // background is of type colour ANSI C defines the types of enums to be ints. In C++, each enumerated data type retains its own. separate type. This means that C++ does not permit an int value to be automatically converted to an enum value. Examples: colour background blues I altowed colour background = 73, UI Error in CH colour background = (colour) 7 // OK However, an enumerated value can be used in place of an int value. int c= red; // valid, colour type promoted to int 156 Computer Prograrming and Uiteation By default, the enumerators are assigned integer values starting with 0 for the first enumerator, | for the second, and so on, We can over-ride the default by explicitly assigning integer values to the enumerators. For example, enum colour{red, blue=4, gree enum colour(red-5, blue, gzeen}; are valid definitions. In the first case, red is 0 by default. In the second case, blue is 6 and green is 7. Note that the subsequent initialized enumetators are larger by one than their predecessors. C++ also permits the creation of anonymous enums (i.e, enums without tag names). Example: enunfoff, on}s Her Examples: off is O and on is 1. These constants may be referenced in the same manner as regular constants, int switch = o: nt switeh_2 = ons In practice, enumeration is used to define symbolic constants for a switch statement as shown in Fig 15.2. enum shape ‘ circle, rectangle, triangle re int main() ( cout << “Enter shape cod: int code; cin >> code: while(code > c circle && code triangle) switch (code) ‘ case circle: rectangle: case triangle: ) cout << “Enter shape code: "+ cin >> codes Contd. Tokens, Expressions and ContolStucues 187 cout << "BYE \n"s return 05 } Defining symbole constants fora sotech statement by enumeration ANSIC permits an enum to be defined within a structure or a class, but the enum is globally visible. In C++, an enum defined within a class (or structure) is local to that class (or structure) only. 15.7 l Derived Data Types 15.7.4 Arrays ‘The application of arrays in C+ is similar to that in C. The only exception is the way character arrays are initialized. When initializing a character array in ANSI C, the compiler will allow us to declare the array size as the exact length of the string constant. For instance, char stringl3] - “xyz”? is valid in ANSIC. Itassumes that the programmer intends to leave out the null character \0 in the definition. But in C+, the size should be one larger than the number of characters in the string. char string[4] = “xyz"7 // 0K. for cee 15.7.2 Functions Functions have undergone major changes in C++. While some of these changes are simple, others require ‘anew way of thinking when organizing our programs. Many of these modifications and improvements were driven by the requirements of the object-oriented concept of C++. Some of these were introduced to make the C+ program more reliable and readable. All the features of C++ functions are discussed in Chapter 16. 15.7.3 Pointers Pointers are declared and initialized as in C. Examples Jf int pointer U1 address of x assigned to ip / 10 assigned to x through indirection (C++ adds the concept of constant pointer and pointer to a constant, char * const ptrl = "GOOD"; // constant pointer We cannot modify the address that ptr1 is initialized to, int const * ptr2 = tm; // pointer to a constant, ptr2 is declared as pointer to a constant. It can point to any variable of correct type, but the contents of ‘what it points to cannot be changed. We can also declare both the pointer and the variable as constants in the following way: const char * const op = “xy This statement declares ep as a constant pointer to the string which has been declared a constant. In this case, neither the address assigned to the pointer cp nor the contents it points to can be changed. Tokens, Expressions and ContolStucues 158 15.9 ll Type Compatibility C++ is very strict with regard to type compatibility as compared to C. For instance, C++ defines int, short int, and long int as three different types. They must be cast when their values are assigned to one another. Similarly, unsigned char, char, and signed char are considered as different types, although each of these has a size of one byte. In C++, the types of values must be the same for complete compatibility, or else, a cast must be applied. These restrictions in C++ are necessary in order to support function overloading where two functions with the same name are distinguished using the type of function arguments. Another notable difference is the way ehar constants are stored. In C, they are stored as ints, and therefore, sizeof 1x") is equivalent to sizeof (int) in. In C++, however, char is not promoted to the size of int and therefore sizeof (*x! equals sizeof (char) 15.10 || Declaration of Variables We know that, in C, all variables must be declared before they are used in executable statements. This, is true with C++ as well. However, there is a significant difference between C and C++ with regard to the place of their declaration in the program. C requires all the variables to be defined at the beginning of a scope. When we read a C program, we usually come across a group of variable declarations at the beginning of each scope level. Their actual use appears elsewhere in the scope, sometimes far away from the place of declaration. Before using a variable, we should go back to the beginning of the program to see whether it has been declared and, if so, of what type. C+ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write and reduces the errors that may be caused by having to scan back and forth. It also makes the program easier to understand because the variables are declared in the context of their use. Figure 15.3 illustrates this point. int main() a float xs 11 dectaration float sum = 0; for(int del; icS; i++) // declaration ‘ Contd. 1540 Computer Programming and Uiizaton float average; Wf declaration average = sum/(i-1); cout << average; return 0; Declaration of Variables The only disadvantage of this style of declaration is that we cannot see all the variables used in @ scope at a glance. 15.11 l Dynamic Initialization of Variables In C, a variable must be initialized using a constant expression, and the C compiler would fix the initialization code at the time of compilation. C++, however, permits initialization of the variables at run time. This is referred to as dynamic initialization. In C++, a variable can be initialized at run time using expressions at the place of declaration, For example, the following are valid initialization statements: int n = strlen(string) float area = 3.14189 * vad * vad: Thus, both the declaration and the initialization of a variable can be done simultaneously at the place where the variable is used for the first time. The following two statements in the example of the previous section float average: // declare where necessary aver: sun/iz can be combined into a single statement: float average = sun/i; // initialize dynanically at run tine Dynamic initialization is extensively used in object-oriented programming. We can create exactly the type of object needed, using information that is known only at the run time, 15.42 l Reference Variables (C+ introduces a new kind of variable known as the reference variable. A reference variable provides an alias (eltemative name) for a previously defined variable, For example, if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable, A reference variable is created as follows data-type & reference-name = variable-name Example: float total - 100; float & sum = totals 1542 Computer Programming and Uizaton When the function call f(m) is executed, the following initialization occurs int @ x= my ‘Thus x becomes an alias of m after executing the statement f(a) Such function calls are known as call by reference. This implementation is illustrated in Fig. 15.4 Since the variables x and m are aliases, when the function increments x, m is also incremented. The value of m becomes 20 after the function is executed. In traditional C, we accomplish this operation using pointers and dereferencing techniques. int m=to =m 10 | nomen” call fo) x int x= Call by reference mechanism The call by reference mechanism is useful in object-oriented programming because it permits the ‘manipulation of objects by reference, and eliminates the copying of object parameters back and forth. It is also important to note that references can be created not only for built-in data types but also for user-defined data types such as structures and classes. References work wonderfully well with these user-defined data types. 15.13 || Operators in C++ C+ has a rich set of operators. All C operators are valid in C+ also. In addition, C++ introduces some new operators, We have already seen two such operators, namely, the insertion operator <<, and the extraction operator >>. Other new operators are: Scope resolution operator . Pointer-to-member declarator > Pointer-to-member operator . Pointer-to-member operator delete vemory release operator endl Line feed operator new Memory allocation operator setw Field width operat: In addition, C++ also allows us to provide new definitions to some of the built-in operators. That is, we can give several meanings to an operator, depending upon the types of arguments used. This process is known as operator overloading. Tes Exasson and Cnt Snues 15.13 15.14 || Scope Resolution Operator Like C, C+ isalsoa block-structured language, Blocks and scopes can be used in constructing programs We know that the same variable name can be used to have different meanings in different blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside a block is said to be local to that block. Consider the following segment of a program: int x = 10; int x = The two declarations of x refer to two different memory locations containing different values. ‘Statements in the second block cannot refer to the variable x declared in the first block, and vice versa. Blocks in C+ are often nested. For example, the following style is common: Block2 | Block 1 Block2 is contained in block! Note that declaration in an inner block hides a declaration of the same variable in an outer block and, therefore, each declaration of x causes it to refer to a different data object. Within the inner block, the variable x will refer to the data object declared therein, In C, the global version of a variable cannot be accessed from within the inner block. C+ resolves this problem by introducing a new operator :: called the scope resolution operator. This can be used to uncover a hidden variable, It takes the following form: Teles, Express and Conta hues 151 15.45 ll Member Dereferencing Operators As you know, C++ permits us to define a class containing various types of data and functions as members. (C++ also permits us to access the class members through pointers, In order to achieve this, C++ provides 2 set of three pointer-to-member operators. Table 15.3 shows these operators and their functions. Member dereferencing operators Operator Function : To deciare¢ pointer to a member ofa lass To access a member using object name and a pointer to that member > Toaccess amember using @ pointer tothe abject and a pointer to that member Further details on these operators will be meaningful only after we discuss classes, and therefore we defer the use of member dereferencing operators until then 15.16 | Memory Management Operators C uses malloe() and calloe() functions to allocate memory dynamically at run time. Similarly, it uses the function free() to free dynamically allocated memory. We use dynamic allocation techniques when itis not known in advance how much of memory space is needed. Although C-++ supports these functions, it also defines two unary operators new and delete that perform the task of allocating and freeing the ‘memory in a better and easier way. Since these operators manipulate memory on the free store, they are also known as free store operators. An object can be created by using new, and destroyed by using delete, as and when required. A data object created inside a block with new, will remain in existence until itis explicitly destroyed by using delete. Thus, the lifetime of an object is directly under our control and is unrelated to the block structure of the program, The new operator can be used to create objects of any type. Ittakes the following general form: pointer-variable = new data-type, Here, pointer-variable is a pointer of type data-type. The new operator allocates sufficient memory to hold a data object of type data-type and returns the address of the object. The data-type may be any valid data type. The pointer-variable holds the address of the memory space allocated. Examples’ Pp - new ints = new floats ‘where p is a pointer of type int and q is a pointer of type float. Here, p and q must have already been declared as pointers of appropriate types. Alternatively, we can combine the declaration of pointers and their assignments as follows: ne tp = new ints float *q = new floats Subsequently, the statements assign 25 to the newly created int object and 7.5 to the float object. 1516 Computer Programming and Uizaton We can also initialize the memory using the new operator. This is done as follows: pointer-variable = new data-type (value) ; Here, value specifies the initial value. Examples: int *p = new int (25)+ float *q = new float (7.5); ‘As mentioned earlier, mew can be used to create a memory space for any data type including user- defined types such as arrays, structures and classes. The general form for a one-dimensional array is: pointer-variable = new data-type[sizel; Here, size specifies the number of elements in the array. For example, the statement int *p = new int [10]; creates a memory space for an array of 10 integers. p[0] will refer to the first element, p[I] to the second element, and so on. When creating multi-dimensional arrays with new, all the array sizes must be supplied. array_ptr = new int(3)(S5](4]z // legal array_ptr = new int(m)[5][4]? // legal array ptr = new int(3)(5][ 17 // illegal array ptr = new int{ ]{5](4]7 // illegal The first dimension may be a variable whose value is supplied at runtime. All others must be constants, The application of new to class objects will be discussed later in Chapter 17. When a data object is no longer needed, itis destroyed to release the memory space for reuse, The general form of its use is: delete pointer-variable; ‘The pointer-variable is the pointer that points to a data object created with new. Examples: If. we want to free a dynamically allocated array, we must use the following form of delete: delete [size] pointer-variables The size specifies the number of elements in the array to be freed. The problem with this form is that the programmer should remember the size of the array. Recent versions of C++ do not require the size to be specified. For example, aelete | Ip: will delete the entire array pointed to by p. ‘What happens if sufficient memory is not available for allocation? In such cases, like malloe(), new returns a null pointer. Therefore, it may be a good idea to check for the pointer produced by new before using it. It is done as follows: p= new dnt; if (1p) 1548 Computer Programming and Utzon Program Hinclude Hinelude // for setw using namespace std; int main() int Basic = 950, Allowance ~ 95, Total ~ 1045; cout << setw(10) << “Basic” << setw(10) << Basic << endl << setu(10) << “Allowance” << setw(10) << Allowance << endl << getw(10) << “Total” << setw(10) << Total << endl? return 0: > output Basic 950 Allowance 95 Total 1045 Program illustrating use of manipulators [Note] Character strings are also printed righ-justified. We can also wri our own manipulators as follows: Hinclude ostream & symbol (ostream ¢ output) xeturn output << “\tRs The symbol is the new manipulator which represents Rs. The identifier symbol can be used whenever we need to display the string Rs. 15.18 || ‘Type Cast Operator (C+ permits explicit type conversion of variables or expressions using the type cast operator. ‘Traditional C casts are augmented in C++ by a function-call notation as a syntactic alternative. The following two versions are equivalent: (type-name) expression // C notation ype-name (expression) // C++ notation Examples average = sun/(float}iz // € notation average = sum/float (i)? // C++ notation 1528 Conputer Programming and Uiizaton eo onl: while (condition is true); action2; 15.244 The while Statement This is also a loop structure, but is an entry-controlled one. The syntax is as follows while(condition is true) tion action2; 15.245 The for Statement ‘The for is an entry-entrolled loop and is used when an action is to be repeated for a predetermined ‘number of times. The syntax is as follows: for(initial value; tests increment) actionl; action2; The syntax of the control statements in C+ is very much similar to that of C and therefore they are implemented as and when they are requited. eal © C++ provides various types of tokens that include keywords, identifiers, constants, strings, and operators, © Identifiers refer to the names of variables, functions, arrays, classes, ete © C+ provides an additional use of void, for declaration of generic pointers, © The enumerated data types differ slightly in C+. The tag names of the enumerated data types become new type names. That is, we can declare new variables using these tag names, © In C++, the size of character array should be one larger than the number of characters in the string © C++ adds the concept of constant pointer and pointer to constant, In case of constant pointer ‘we can not modify the address that the pointer is initialized to. In case of pointer to a constant, contents of what it points to cannot be changed. © Pointers are widely used in C'-+ for memory management and to achieve polymorphism. © CH provides a qualifier called const to declare named constants which are just like variables ‘except that their values can not be changed. A const modifier defaults to an in * C+ is very strict regarding type checking of variables. It does not allow to equate variables of two different data types. The only way to break this rule is type casting. 15:0 Computer Programming and Uiizaton 15.17, What are the advantages of using new operator as compared to the funetion malloc)? 15.18 Illustrate with an example, how the setw manipulator works. 15.19 How do the following statements differ? (a) char * const p; (b) char const *p; Programming Exercises 15.1 Write a function integers. 15.2. Write a function that creates a vector of user-given size M using mew operator. 15.3 Write a program to print the following output using for loops. 1 22 333 4444 55555 ng reference variables as arguments to swap the values of a pair of 15.4 Write a program to evaluate the following investment equation V=Pa+n" and print the tables which would give the value of V for various combination of the following values of P, r and n: P: 1000, 2000, 3000, «1. 10,000 75 0.10, 0.11, 0.125 sn 0.20 11,2, By ey 10 (Hint: P is the principal amount and Vis the value of money at the end of n years, ‘This equation can be recursively written as Ptr) Pav In other words, the value of money at the end of the first year becomes the principal amount for the next year, and so on. 155 An election is contested by five candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count In case, a number read is outside the range 1 to 5, the ballot should be considered as a “spoilt ballot’, and the program should also count the number of spoilt ballots. 15.6 A cricket team has the following table of batting figures for a series of test matches: Runs Innings Times not out Sachin 8430 230 8 Saurav 4200 130 ° Rahul 3350 105 1 ‘Tokens, Expressions and Conte Stucues 18.31 Write a program to read the figures set out in the above form, to calculate the batting averages and to print out the complete table including the averages. 15.7. Write programs to evaluate the following functions to 0.001% accuracy. (a) sinx= > (b) SUM=1 + (1/2) + (3p + (Vay + >t ye ©) cosx=1- 4X ) Seo 15.8. Write a program to print a table of values of the function poet for x varying from 0 to 10 in steps of 0.1. The table should appear as follows. Table For ¥ = EXP{-X1 x of 02 03 04056 07 08 09 00 10 90 15.9 Write a program to calculate the variance and standard deviation of N numbers. variance = L(x Variance nye 1 ~ ‘Standard Deviation \e ze -3y 15.10 Anclectricity board charges the following rates to domestic users to discourage large consumption where of energy: For the first 100 units - 60P per unit For next 200 units ~ 80P per unit Beyond 300 units ~ 90P per unit All users are charged a minimum of Rs. 50.00. Ifthe total amount is more than Rs. 300,00 then ‘an additional surcharge of 15% is added, Write a program to read the names of users and number of units consumed and print out the charges with names. Functonsinc++ 163, 16.3 ll Function Prototyping Funetion prototyping is one of the major improvements added to C++ functions. The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. With function prototyping, a template is always used when declaring and defining a function, When a function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. Any violation in matching the arguments or the return types will be caught by the compiler at the time of compilation itself. These checks and controls did not exist in the conventional C functions. Remember, C also uses prototyping. But it was introduced first in C++ by Stroustrup and the success of this feature inspired the ANSI C committee to adopt it. However, there is a major difference in prototyping between C and C++. While C+ makes the prototyping essential, ANSI C makes it optional, pethaps, to preserve the compatibility with classic C. Function prototype isa declaration statement in the calling program and is of the following form: The argument-list contains the types and names of arguments that must be passed to the function. Example: float volune(int x, float yy float 2)z Note that each argument variable must be declared independently inside the parentheses. That is, a combined declaration like float volume (int x, float yr 2) is illegal Ina function declaration, the names of the arguments are dummy variables and therefore, they are ‘optional. That is, the form float volume(int, float, float); is acceptable atthe place of declaration. At this stage, the compiler only checks for the type of arguments ‘when the funetion is called In general, we can either include or exclude the variable names in the argument list of prototypes. The variable names in the prototype just act as placeholders and, therefore, if names are used, they don’t have to match the names used in the function call or function definition. In the function definition, names are required because the arguments must be referenced inside the function. Example: float volune(int a,float b,float ¢) ( float. atbtes Functonsin++ 167 Program Hinclude using namespace std; inline float mul(float x, float y) i return (x*y) 7 : inline double div(double p, double a) i return(p/a) + , int mainQ ( float a = 12.345; float b = 9.827 cout << mul(ayb) << “\a"; cout << diviayb) << “\n"; return 0; } output 121.228 1.25713, PERI? rogram showing use of inline functions. 16.7 | Default Arguments C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call, Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. Here is an example of @ prototype (ic. function declaration) with default values: float amount (float principal, int period,float rate=0.15); ‘The default value is specified in a manner syntactically similar to a variable initialization. The above prototype declares a default value of 0.15 10 the argument rate, A subsequent function call like valve = amount (5000,7); // one argument missing Functonsinc++ 169 int year = 1) float sum = pi while(year <= n) ( sum = sum* (142); year = yeartl; } return (sum) # void printline(char ch, int len) for(int isi; icelen; itt) printé(*$e",ch); printf ("\n"); } output Final Value = 10056.8 PERLE Program showing use of defeat arguments Advantages of providing the default arguments are: 1. We can use default arguments to add new parameters to the existing functions. 2. Default arguments can be used to combine similar functions into one. 16.8 ll const Arguments In C++, an argument to a function can be declared as const as shown below. int strlen (const char *p); int length (const string ss); The qualifier const tells the compiler that the function should not modify the argument, The compiler will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers. 16.9 || Function Overloading As stated earlier, overloading refers to the use of the same thing for different purposes. C++ also permits overloading of functions. This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function polymorphism in OOP. Using the concept of function overloading; we can design a family of functions with one funetion name but with different argument lists. The function would perform different operations depending on the argument list in the function call, The correct function to be invoked is determined by checking 16:14 Computer Programming and Utzon (@) void Vecitint? &Y, int & size); (©) void print(float data (], size 0); 16.5. What is the main advantage of passing arguments by reference? 16.6 When will you make a funetion inline? Why? 16.7 How does an inline function differ from a preprocessor macro? 16.8 When do we need to use default arguments in a function? 16.9 What is the significance of an empty parenthesis in a function declaration? 16.10 What do you meant by overloading of a function? When do we use this concept? 16.11 Comment on the following function definitions (@ int *£¢) { return (6m); ) (b) double £( ) ‘ eturn (1); } ( int © £0 4 int n = 10; n(n) Programming Exercises ll 16.1 Write a function to read a matrix of size m x n_ from the keyboard. 16.2 Write a program to read a matrix of size mx n_ from the keyboard and display the same on the sereen. Use the funetions discudssed in Exercises 4.12 16.3. Rewrite the program of Exercise 16.2 to make the row parameter of the matrix as a default argument 16.4 The effect ofa default argument can be altetnatively achieved by overloading. Discuss with an example, Computer Programming and ization 16.3 Identify the error in the following program: Hinclude int gvalue=107 void extra() ‘ cout << gvalue << * ) void main() ‘ extra ()s 4 int gvalue = 20; cout << gvalue << * + cout << : gvalue << * ) , 164 Find errors, if any, in the following funetion definition for displaying a matrix: void isplay(int A] [], int m, int n) { for(i-0: icms itt) for(j-07 J

You might also like