PROGRAMMING fOR PRObleM SOlvING Gujarat Technological University - 2018 About the Author E Balagurusamy, is presently the Chairman of EBG Foundation, Coimbatore. In the past he has also held the positions of member, Union Public Service Commission, New Delhi and Vice-Chancellor, Anna University, Chennai. 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 from the Indian Institute of Technology, Roorkee. His areas of interest 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. A recipient of numerous honors and awards, he has been listed in the Directory of Who's Who of Intellectuals and in the Directory of Distinguished Leaders in Education. PROGRAMMING fOR PRObleM SOlvING Gujarat Technological University - 2018 E Balagurusamy Chairman EBG Foundation Coimbatore McGraw Hill Education (India) Private Limited CHENNAI McGraw Hill Education Offices Chennai New York St Louis San Francisco Auckland Bogotá Caracas Kuala Lumpur Lisbon London Madrid Mexico City Milan Montreal San Juan Santiago Singapore Sydney Tokyo Toronto McGraw Hill Education (India) Private Limited Published by McGraw Hill Education (India) Private Limited 444/1, Sri Ekambara Naickr Industrial Estate, Alapakkam, Porur, Chennai-600 116 Programming for Problem Solving Copyright © 2019 by McGraw Hill Education (India) Private Limited. No part of this publication may be reproduced or distributed in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise or stored in a database or retrieval system without the prior written permission of the publishers. The program listings (if any) 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 only by the publishers, McGraw Hill Education (India) Private Limited. Print Edition ISBN (13 digit): 978-93-5316-278-8 ISBN (10 digit): 93-5316-278-5 E-book Edition ISBN (13 digit): 978-93-5316-279-5 ISBN (10 digit): 93-5316-279-3 1 2 3 4 5 6 7 8 9 D101417 22 21 20 19 18 Printed and bound in India. Director—Science & Engineering Portfolio: Vibha Mahajan Senior Portfolio Manager—Science & Engineering: Hemant K Jha Associate Portfolio Manager —Science & Engineering: Tushar Mishra Production Head: Satinder S Baveja Copy Editor: Taranpreet Kaur Assistant Manager—Production: Suhaib Ali General Manager—Production: Rajender P Ghansela Manager—Production: Reji Kumar Information contained in this work has been obtained by McGraw Hill Education (India), from sources believed to be reliable. However, neither McGraw Hill Education (India) nor its authors guarantee the accuracy or completeness of any information published herein, and neither McGraw Hill Education (India) nor its authors shall be responsible for any errors, omissions, or damages arising out of use of this information. This work is published with the understanding that McGraw Hill Education (India) and its authors are supplying information but are not attempting to render engineering or other professional services. If such services are required, the assistance of an appropriate professional should be sought. Typeset at The Composers, 260, C.A. Apartment, Paschim Vihar, New Delhi 110 063 and printed at Cover Printer: Cover Designer: APS Compugraphics Cover Image Source: Shutterstock Visit us at: www.mheducation.co.in Write to us at: [email protected] CIN: U22200TN1970PTC111531 Toll Free Number: 1800 103 5875 Preface Programming for Problem Solving requires a deep understanding of C. C is a powerful, flexible, portable and elegantly structured programming language. Since C combines the features of high-level language with the elements of the assembler, it is suitable for both systems and applications programming. It is undoubtedly the most widely used general-purpose language today in operating systems, and embedded system development. Its influence is evident in almost all modern programming languages. Since its standardization in 1989, C has undergone a series of changes and improvements in order to enhance the usefulness of the language. Organization of the Book Programming for Problem Solving starts with an Introduction to Computer Programming, Chapter 2 discusses fundamentals of C. Control Structures in C is presented in Chapter 3. Chapter 4 deals with Arrays and Strings. Chapter 5 discusses Functions. In Chapter 6 students can study Pointers. While Chapter 7 details Structure. Dynamic Memory Allocation is discussed in Chapter 8. Chapter 9 details on File Management. Salient Features of the Book ∑ Learning Objectives ∑ Key Concepts ∑ Content Tagged with LO ∑ Worked Out Problems ∑ Tips ∑ Closing Vignette ∑ Review Exercises – True False, Fill in the blanks, Questions, Programming Exercises – categorized into LO and Difficulty level (E for Easy, M for Medium and H for High) Acknowledgements I owe special thanks to the entire team of McGraw Hill Education India. A note of acknowledgement is due to the following reviewers for their valuable feedback. Ms. Kalpana Mudaliar Gandhinagar Institute of Technology, Gandhinagar, Gujarat H K Patnaik K alinga Institute of Industrial Technology, KIIT University, Bhubaneswar T V Gopal College of Engineering, Anna University, Chennai, Tamil Nadu Unnati Nitin Chaudhari Tolani Maritime Institute, Pune, Maharashtra Tanveer Ahmed Jamia Millia Islamia, Delhi Ravindra Divekar KJ Somaiya College of Engineering, Mumbai, Maharashtra SC Dutta Birsa Institute of Technology, Sindri, Dhanbad, Jharkhand D Lakshmi Adithya Institute of Technology, Coimbatore, Tamil Nadu vi Preface This book is my sincere attempt to make a footprint on the immensely vast and infinite sands of knowledge. I would request the readers to utilize this book to the maximum extent. E Balagurusamy Publisher’s Note McGraw Hill Education (India) invites suggestions and comments from you, all of which can be sent to info. [email protected] (kindly mention the title and author name in the subject line). Piracy-related issues may also be reported. Contents About the Author ii Preface v 1. Introduction to Computer and Programming 1 Learning Objectives 1 Introduction 1 Generations of Computers 2 Classification of Computers 5 Basic Anatomy of a Computer System 7 Input Devices 8 Processor 9 Output Devices 10 Memory Management 12 Types of Computer Software 13 Overview of Operating System 14 MS Word 19 MS Excel System 21 MS Powerpoint System 22 Networking Concepts 23 Network Topologies 25 Network Protocols and Software 29 Decimal System 31 Binary System 32 Hexadecimal System 33 Octal System 34 Conversion of Numbers 35 Binary Arithmetic Operations 44 Logic Gates 52 Programming Languages 55 viii Contents Translator Programs 58 Problem-Solving Techniques 59 Using the Computer 70 Learning Outcomes 70 Key Concepts 71 Review Questions 73 Discussion Questions 84 2. Fundamentals of C 87 Learning Objectives 87 History of C 87 Importance of C 89 Sample Program 1: Printing a Message 89 Sample Program 2: Adding Two Numbers 92 Sample Program 3: Interest Calculation 93 Sample Program 4: Use of Subroutines 95 Sample Program 5: Use of Math Functions 96 Basic Structure of C Programs 97 Programming Style 98 Executing a ‘C’ Program 99 UNIX System 99 MS-DOS System 102 Key Concepts 102 Always Remember 103 Review Questions 103 Debugging Exercises 105 Programming Exercises 105 3. Control Structure in C 107 Learning Objectives 107 Introduction 107 Decision Making with if Statement 108 Simple If Statement 108 The If.....Else Statement 111 Nesting of If....Else Statements 114 The Else If Ladder 117 The Switch Statement 121 The ? : Operator 125 The goto Statement 129 Key Concepts 132 Contents ix Always Remember 132 Brief Cases 132 Review Questions 137 Debugging Exercises 141 Programming Exercises 141 4. Array & String 145 Learning Objectives 145 Introduction 145 One-Dimensional Arrays 147 Declaration of One-dimensional Arrays 148 Initialization of One-dimensional Arrays 151 Two-Dimensional Arrays 156 Initializing Two-dimensional Arrays 161 Multi-dimensional Arrays 168 Dynamic Arrays 169 More About Arrays 170 Declaring and Initializing String Variables 170 Reading Strings from Terminal 171 Writing Strings to Screen 177 Arithmetic Operations on Characters 181 Putting Strings Together 183 Comparison of Two Strings 184 String-Handling Functions 184 Table of Strings 190 Other Features of Strings 192 Key Concepts 192 Always Remember 193 Brief Cases 194 Review Questions 210 Debugging Exercises 214 Programming Exercises 215 5. Functions 220 Learning Objectives 220 Introduction 220 Need for User-Defined Functions 221 A Multi-Function Program 221 Elements of User-Defined Functions 224 x Contents Definition of Functions 224 Return Values and Their Types 227 Function Calls 228 Function Declaration 229 Category of Functions 231 No Arguments and No Return Values 231 Arguments but No Return Values 233 Arguments with Return Values 236 No Arguments but Returns a Value 241 Functions that Return Multiple Values 242 Nesting of Functions 243 Recursion 244 Passing Arrays to Functions 245 Passing Strings to Functions 250 The Scope, Visibility and Lifetime of Variables 251 Multifile Programs 260 Key Concepts 262 Always Remember 262 Brief Cases 263 Review Questions 266 Debugging Exercises 270 Programming Exercises 270 6. Pointers 273 Learning Objectives 273 Introduction 273 Understanding Pointers 274 Accessing the Address of a Variable 276 Declaring Pointer Variables 277 Initialization of Pointer Variables 278 Accessing a Variable Through its Pointer 279 Chain of Pointers 281 Pointer Expressions 282 Pointer Increments and Scale Factor 284 Pointers and Arrays 284 Pointers and Character Strings 288 Array of Pointers 290 Pointers as Function Arguments 291 Functions Returning Pointers 294