<<

Programming in

CS 8251 Programming inPress As per Anna University R17 syllabus

ReemaUniversity Thareja Assistant Professor Department of Science Shyama Prasad Mukherji College for Women University of Delhi Oxford

© Oxford University Press. All rights reserved. 3

Oxford University Press is a department of the University of Oxford. It furthers the University’s objective of excellence in research, scholarship, and education by publishing worldwide. Oxford is a registered trade mark of Oxford University Press in the UK and in certain other countries.

Published in India by Oxford University Press Ground Floor, 2/11, Ansari Road, Daryaganj, New Delhi 110002, India

© Oxford University Press 2018

The moral rights of the author/s have been asserted.

First published in 2018

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, without the prior permission in writing of Oxford University Press, or as expressly permitted by law, by licence, or under terms agreed with the appropriate reprographics rights organization. Enquiries concerning reproduction outside the of the above should be sent to the Rights Department, Oxford University Press, at the address above.

You must not circulate this work in any other Pressform and you must impose this same condition on any acquirer.

ISBN-13: 978-0-19-948552-9 ISBN-10: 0-19-948552-6

Typeset in Times New Roman by Pee-Gee Graphics, New Delhi Printed in India by Magic International (P) Ltd., Greater Noida

Cover image: Nizwa Design / Shutterstock Third-party website addressesUniversity mentioned in this book are provided by Oxford University Press in good faith and for information only. Oxford University Press disclaims any responsibility for the material contained therein.

Oxford

© Oxford University Press. All rights reserved. Features of the Book

Comprehensive Coverage Introduction to Arrays Programming The book provides comprehensive Introduction to C Strings coverage of C programming constructs. Decision Control and Pointers Looping Statements Functions Files

Notes Note These elements highlight the important The printf and returnPress statements have been indented terms and concepts discussed in each or moved away from the left side. This is done to make the chapter. code more readable.

1. Find out the output of the following program. Programming Examples #include int main() As many as 250 C programs are { Universityincluded, which demonstrate the int a, b; applicability of the concepts learned. printf("\n Enter two four digit numbers : "); scanf("%2d %4d", &a, &b); printf("\n The two numbers are : %d and %d", a, b); return 0; } Oxford Output Enter two four digit numbers : 1234 5678 The two numbers are : 12 and 34

12 Programming in C

∑ New data and functions can be easily added as and when In the forthcoming chapters, we are going to study C required. which supports both procedural as ∑ Follows a bottom-up approach for problem solving. well as .

Points to Remember POINTS TO REMEMBER

A list of key topics at the end of ∑ A computer has two parts—computer hardware which from a storage device to main memory, where they can be does all the physical work and computer software which executed. each chapter helps readers to tells the hardware what to do and how to do it. ∑ The fourth generations of programming languages revise all the important concepts ∑ A program is a set of instructions that are arranged in are: machine language, , high-level a sequence to guide a computer to find a solution for a language, and very high-level language. explained in the chapter. given problem. The process of writing a program is called ∑ Machine language is the lowest level of programming programming. language that a computer understands. All the instructions ∑ Computer software is written by computer programmers and data values are expressed using 1s and 0s. using a programming language. ∑ Assembly language is a low-level language that uses ∑ Application software is designed to solve a particular symbolic notation to represent machine language problem for users. instructions. ∑ System software represents programs that allow the ∑ Third-generation languages are high-level languages in hardware to run properly. It acts as an interface between which instructions are written in statements like English the hardware of the computer and the application language statements. Each instruction in this language © softwareOxford that Universityusers need to run on Press.the computer. All rightsexpands reserved. into several machine language instructions. ∑ The key role of BIOS is to load and start the operating ∑ Fourth-generation languages are non-procedural system. The code in the BIOS chip runs a series of tests languages in which programmers define only what they called POST (Power On Self Test) to ensure that the system want the computer to do, without supplying all the details devices are working correctly. BIOS is stored on a ROM of how it has to be done. chip built into the system. ∑ Programs written using monolithic programming ∑ Utility software is used to analyse, configure, optimize, languages such as assembly language and BASIC consist and maintain the computer system. of global data and sequential code. ∑ A compiler is a special type of program that transforms ∑ In procedural languages, a program is divided into written in a programming language (the that can access global data. source language) into machine language comprising of ∑ Structured programming employs a top-down approach just two digits—1s and 0s (the target language). The in which the overall program is broken down into separate resultant code in 1s and 0s is known as the object code. modules. ∑ Linker is a program that combines object modules to form ∑ Object-oriented programming treats data as a critical an executable program. element in the program development and restricts its ∑ A loader is a special type of program that copies programs flow freely around the system.

EXERCISES

Fill in the Blanks 5. ______transforms the source code into binary 1. ______tells the hardware what to do and how to do language. it. 6. ______allows a computer to interact with additional 2. The hardware needs a ______to instruct what has to hardware devices such as printers, scanners, and video be done. cards. 3. The process of writing a program is called ______. 7. ______helps in coordinating system resources and 4. ______is used to write computer software. allows other programs to execute. Glossary GLOSSARY All chapters provide a list of key terms along with their definitions for a quick recapitulation of important terms learned.

C Case Study 1: Chapters 2 and 3 Case Studies Select chapters are followed by case We have learnt the of programming in C language Roman Numeral Table Pressstudies that show how C can be used and concepts to write decision-making programs, let us now apply our learning to write some useful programs. 1 I 14 XIV 27 XXVII 150 CL to create programs demonstrating 2 II 15 XV 28 XXVIII 200 CC real-life applications. 3 III 16 XVI 29 XXIX 300 CCC ROMAN NUMERALS 4 IV 17 XVII 30 XXX 400 CD Roman numerals are written as combinations of the seven 5 V 18 XVIII 31 XXXI 500 D letters. These letters include: 6 VI 19 XIX 40 XL 600 DC I = 1 C = 100 7 VII 20 XX 50 L 700 DCC 8 VIII 21 XXI 60 LX 800 DCCC V = 5 D = 500 9 IX 22 XXII 70 LXX 900 CM X = 10 M = 1000 10 X 23 XXIII 80 LXXX 1000 M L = 50 11 XI 24 XXIV 90 XC 1600 MDC University

Programming Tips Programming Tip: These elements educate readers about If you do not place common programming errors and how a parenthesis after to resolve them. Oxford ‘main’, a compiler error will be generated.

Programming Exercises 1. Write a program which deletes all duplicate elements from Programming Exercises the array. Numerous exercises at the end 2. Write a program that tests the equality of two one- of every chapter test the readers’ dimensional arrays. understanding of the concepts 3. Write a program that reads an array of 100 integers. Display learned. all pairs of elements whose sum is 50.

© Oxford University Press. All rights reserved. Companion Online Resources for Instructors and Students

Companion Site for Higher Education “A Teaching aid for ProfessorsVisit and www.oupinheonline.com a Learning aid for Students” to access both Contents of Companion Site “www.oupinheonline.com”teaching and learning solutions online. The following resources are available to 1 Search By: support the faculty and studentsFeatures: using this book: • Author • Free access via username and password • Title 1 authentication. • ISBN For Faculty • Resources for more than 150 titles and new 2 titles are being added every week. ∑ Solutions4 • ManualResources are developed by Authors 2 Browse by Subjects • 24X7 available 3 ∑ PowerPoint Slides • Unlimited access to read, download or save 1. Biotechnology ∑ C Projects the content (No DRM) 2. Business Management • Non-Subscriber can view the availability of 3. Chemical Engineering the resources For Students 4. Civil Engineering 5 5. Computer Science and IT ∑ Codes of Programming Examples 6. Economics 4 Member Login 7. Electrical Engineering 6 ∑ Multiple Student/InstructorChoice Questions having username and 8. Electronics ∑ Supplementarypassword can Reading login from here Material 9. Engineering General Online Resources available for the following users: 10. Hospitality 11. Life sciences Instructors Students 5 New Instructor Registration: 12. Mechanical Engineering PowerPoint Presentation Web links Press Sign Up for Instructors 13. Media Studies Solutions Manual Projects Teaching Notes Multiple Choice Questions 3 6 New Student Registration: Recent Solutions to Case Studies Scholastic Capability Test Newly Released titles for which and more... and more... Sign Up for Students online resources are available to download. Resources are book specific and may vary from title to title.

Steps to Register

Step 1: Getting Started Step 7: Registration Form Step 10: Visit us again after validation • Go to www.oupinheonline.com Please fill correct details and *marked fields are mandatory • Go to www.oupinheonline.com University • Login from Member Login Step 2: Browse quickly by: Username should • BASIC SEARCH be email ID  Author  Title  ISBN • ADVANCED SEARCH w Subjects Please fill correct Mobile no. w Recent titles to get SMS after verification

Step 3: Select Title Oxford Select title for which you are looking for Step 11: My Subscriptions resources.

Step 4: Search Results with Resources available

Click here

Step 5: To download Results SUBMIT

Step 8: Message after completing the registration form You can view Subscriptions in your account Thank you for registering with us. We shall revert to you within 48 hours Step 6: Login to download • Click on the title after verifying the details provided by you. Once validated please login • Select Chapter or “Select All” using your username and the password and access the resources. • Click on “Download All” Step 9: Verification • Click on “I Accept’” New Instructor? Register You will receive a confirmation on your mobile & email ID. • A zip file will be downloaded on your system. You may use this along with the For any further query please write to us at [email protected] with your mobile number textbook. www.oup.co.in www.oupinheonline.com [email protected] 1

© Oxford University Press. All rights reserved. Preface

C is one of the most popular and successful programming world problems. Unlike existing textbooks on C which languages of all time and considered to be the origin of concentrate morePress on theory, this book focuses on its all modern-day computer languages. Many of the popular applicability angle by providing numerous programming cross-platform programming languages, such as C++, examples and a rich set of programming exercises at the Java, Python, Objective-C, , and Ruby, and scripting end of each chapter. languages, such as PHP, Lua, and Bash, borrow syntaxes The salient features of the book include: and functions from C. ∑ Lucid style of presentation that makes the concepts easy to understand C is also used for programming embedded micropro- ∑ Plenty of illustrations to support the explanations, cessors and device drivers. As many embedded systems which help clarify the concepts in a clear manner do not support C++, learning to develop programs using University ∑ Programming tips in between the text educating a strict C, without advanced C++ features, is critical for readers about common programming errors and how many applications including interface to hardware. to avoid them Thus, studying C provides a good foundation to learn ∑ Notes highlighting important terms and concepts advanced programming skills such as object-oriented ∑ Numerous programs that have been tested and programming, event-driven programming, multi-thread executed programming, real-time programming, embedded pro- Oxford ∑ Glossary of important terms at the end of each gramming, network programming, parallel programming, chapter for recapitulation of the important concepts other programming languages, as well as new and emerg- learnt ing computing paradigms such as grid computing and ∑ Comprehensive exercises at the end of each chapter cloud computing. to facilitate revision ∑ Case studies containing programs that harness the concepts learnt in chapters ABOUT THE BOOK Programming in C is designed to serve as a textbook for CONTENT AND COVERAGE the first year engineering students of Anna University. This book is developed as per the latest syllabus (2017) of The book is organized into 11 chapters. affiliated colleges. Chapter 1 provides an introduction to computer software. This book explains the fundamental concepts of the It also provides an insight into different programming C programming language and shows a step-by-step paradigms, programming languages and the generations approach of how to apply these concepts for solving real- through which these languages have evolved.

© Oxford University Press. All rights reserved. viii Preface

Chapter 2 discusses the building blocks of the C includes the use of structures and unions with pointers, programming language. The chapter discusses keywords, arrays, and functions so that the inter-connectivity between identifiers, data types, constants, variables, and the programming techniques can be well understood. operators supported by the language. Annexure 1 shows Annexure 4 provides an explanation about bit fields and the steps to write, compile, and execute a C program in slack bytes. Unix, Linux, and Ubuntu environments. Chapter 9 explains how data can be stored in files. The Chapter 3 explains decision control and iterative statements chapter deals with opening, processing, and closing of files as well as special statements such as break statement, though a C program. These files are handled in text mode control statement, and jump statement. as well as binary mode for better clarity of the concepts. Case Study 1 includes two programs which harness the Chapter 10 discusses the concept of pre-processor concepts learnt in Chapters 2 and 3. directives. The chapter includes program codes that Chapter 4 deals with declaring, defining, and calling illustrate the use of different directives in a C program. functions. The chapter also discusses the storage classes Annexure 5 provides an introduction to data structures. as well as variable scope in C. The chapter ends with the Chapter 11 discusses linked list which is a preferred data important concept of recursive functions and a discussion structure when memory needs to be allocated dynamically on the Tower of Hanoi problem. Annexure 2 discusses for the data. The chapter gives the techniques to insert and how to create user-defined header files. delete data from linked lists. Chapter 5 focuses on the concept of arrays, including Case Study 4 showsPress how a telephone directory can be one-dimensional, two-dimensional, and multidimensional implemented using C. arrays. Finally, the operations that can be performed on such arrays are also explained. The book also provides two appendices. Appendix A Case Study 2 provides an introduction to sorting and includes additional C programs, and Appendix B provides various sorting techniques such as bubble sort, insertion answers to objective questions. sort, and selection sort. Chapter 6 discusses the concept of strings which are also ACKNOWLEDGMENTS known as character arrays. The chapter not only focuses on operations that can be used to manipulate strings butUniversity also The mammoth task of writing this book required the help explains various operations that can be used to manipulate and support of many individuals. Fortunately, I have the character arrays. had the wholehearted support of my family and friends. I would like to specially thank my father Mr Janak Raj Chapter 7 presents a detailed overview of pointers, pointer Thareja and mother Mrs Usha Thareja, my brother Pallav, variables, and pointer arithmetic. The chapter also relates and sisters Kimi and Rashi who are a source of abiding the use of pointers with arrays, strings, and functions. This helps readers to understand how pointers can be used to inspiration and divine blessings for me. I am especially write better and efficient programs.Oxford Annexure 3 explains thankful to my son Goransh who has been very patient and the process of deciphering pointer declarations. cooperative in letting me realize my dreams. Finally, I would like to thank the editorial team at Case Study 3 includes a program which demonstrates how Oxford University Press India for their help and support. pointers can be used to access and manipulate strings. Chapter 8 introduces two user-defined data types. The first is a structure and the second is a union. The chapter ReemaThareja

© Oxford University Press. All rights reserved. Detailed Contents ix

Brief Contents

Features of the Book iv Companion Online Resources for Instructors and Students Press vi Preface vii Detailed Contents xi Road Map to Syllabus xv 1. Introduction to Programming 1 2. Introduction to C 15 3. Decision Control and Looping Statements 60 4. Functions 108 5. Arrays University 137 6. Strings 183 7. Pointers 216 8. Structure, Union, and Enumerated Data Types 262 9. Files 293 10. Preprocessor DirectivesOxford 328 11. Linked Lists 347 Appendix A: Additional C Programs 367 Appendix B: Answers to Objective Questions 372

© Oxford University Press. All rights reserved. Detailed Contents

Features of the Book iv Preface vii Companion Online Resources for Brief Contents ix Instructors and Students vi Road Map to Syllabus xv

1. Introduction to Programming 1 2.4.1 SourcePress Code Files 19 2.4.2 Header files 19 1.1 Introduction to Computer Software 1 2.4.3 Object Files 20 1.2 Classification of Computer Software 2 2.4.4 Binary Executable Files 20 1.2.1 System Software 2 2.5 Compiling and Executing C Programs 20 1.2.2 Application Software 5 2.6 Using Comments 21 1.3 Programming Languages 5 2.7 C tokens 22 1.4 Generation of Programming Languages 6 2.8 Character Set in C 22 1.4.1 First Generation: Machine Language 6 2.9 Keywords 22 1.4.2 Second Generation: Assembly 2.10 Identifiers 23 Language 7 University 2.10.1 Rules for Forming Identifier Names 23 1.4.3 Third Generation Programming 2.11 Basic Data Types in C 23 Languages 7 2.11.1 How are Float and Double Stored? 24 1.4.4 Fourth Generation: Very High-level 2.12 Variables 25 Languages 8 2.12.1 Numeric Variables 25 1.4.5 Fifth Generation Programming 2.12.2 Character Variables 25 Languages 8 Oxford 2.12.3 Declaring Variables 25 1.5 Programming Paradigms 9 2.12.4 Initializing Variables 25 1.5.1 Monolithic Programming 9 2.13 Constants 26 1.5.2 Procedural Programming 10 2.13.1 Integer Constants 26 1.5.3 Structured Programming 10 2.13.2 Floating Point Constants 26 1.5.4 Object-oriented Programming (OOP) 11 2.13.3 Character Constants 27 2.13.4 String Constants 27 2. Introduction to C 15 2.13.5 Declaring Constants 27 2.14 Input/Output Statements in C 27 2.1 Introduction 15 2.14.1 Streams 27 2.1.1 Background 15 2.14.2 Formatting Input/Output 28 2.1.2 Characteristics of C 16 2.14.3 printf() 28 2.1.3 Uses of C 17 2.14.4 scanf() 31 2.2 Structure of a C Program 17 2.14.5 Examples of printf/scanf 33 2.3 Writing the First C Program 18 2.14.6 Detecting Errors During Data Input 35 2.4 Files Used in a C Program 19 2.15 Operators in C 35

© Oxford University Press. All rights reserved. xii Detailed Contents 2.15.1 Arithmetic Operators 35 4.8 Scope of Variables 118 2.15.2 Relational Operators 37 4.8.1 Scope 118 2.15.3 Equality Operators 38 4.8.2 Function Scope 119 2.15.4 Logical Operators 38 4.8.3 Program Scope 119 2.15.5 Unary Operators 38 4.8.4 File Scope 120 2.15.6 Conditional Operator 40 4.9 Storage Classes 120 2.15.7 Bitwise Operators 41 4.9.1 auto Storage Class 120 2.15.8 Assignment Operators 42 4.9.2 register Storage Class 121 2.15.9 Comma Operator 43 4.9.3 extern Storage Class 122 2.15.10 Sizeof Operator 43 4.9.4 static Storage Class 122 2.15.11 Operator Precedence Chart 43 4.9.5 Comparison of Storage Classes 123 2.16 Type Conversion and Typecasting 49 4.10 Recursive Functions 123 2.16.1 Type Conversion 49 4.10.1 Greatest Common Divisor 125 2.16.2 Typecasting 50 4.10.2 Finding Exponents 125 Annexure 1 59 4.10.3 Fibonacci Series 126 4.11 Types of Recursion 126 4.11.1 Direct Recursion 126 3. Decision Control and Looping 4.11.2 Indirect Recursion 126 Statements 60 4.11.3 Tail Recursion 126 4.11.4 LinearPress and Tree Recursion 127 3.1 Introduction to Decision Control Statements 60 4.12 Tower of Hanoi 127 3.2 Conditional Branching Statements 60 4.13 Recursion Versus Iteration 129 3.2.1 if Statement 60 Annexure 2 136 3.2.2 if–else Statement 62 3.2.3 if–else–if Statement 64 3.2.4 Switch Case 68 5. Arrays 137 3.3 Iterative Statements 72 5.1 Introduction 137 3.3.1 while loop 72 5.2 Declaration of Arrays 138 3.3.2 do-while Loop 75 5.3 Accessing the Elements of an Array 139 3.3.3 for Loop 78 University 5.3.1 Calculating the Address of Array 3.4 Nested Loops 81 Elements 139 3.5 Break and Continue Statements 90 5.3.2 Calculating the Length of an Array 140 3.5.1 break Statement 90 5.4 Storing Values in Arrays 140 3.5.2 continue Statement 91 5.4.1 Initializing Arrays during Declaration 140 3.6 goto Statement 92 5.4.2 Inputting Values from the Keyboard 141 Case Study 1: Chapters 2 and 3 104 Oxford 5.4.3 Assigning Values to Individual Elements 141 4. Functions 108 5.5 Operations on Arrays 141 5.5.1 Traversing an Array 142 4.1 Introduction 108 5.5.2 Inserting an Element in an Array 147 4.1.1 Why are functions needed? 108 5.5.3 Deleting an Element from an Array 149 4.2 Using Functions 109 5.5.4 Merging Two Arrays 151 4.3 Function Declaration/Function Prototype 110 5.5.5 Searching for a Value in an Array 153 4.4 Function Definition 111 5.6 Passing Arrays to functions 156 4.5 Function Call 111 5.7 Two-dimensional Arrays 159 4.5.1 Points to Remember While Calling 5.7.1 Declaring Two-dimensional Arrays 159 Functions 112 5.7.2 Initializing Two-dimensional Arrays 161 4.6 113 5.7.3 Accessing the Elements of Two- 4.6.1 Using Variable Number of Arguments 113 dimensional Arrays 161 4.7 Passing Parameters to Functions 114 5.8 Operations on Two-dimensional Arrays 164 4.7.1 Call by Value 114 5.9 Passing Two-dimensional Arrays to 4.7.2 Call by Reference 115 Functions 167

© Oxford University Press. All rights reserved. Detailed Contents xiii

5.9.1 Passing a Row 167 7.2 Introduction to Pointers 217 5.9.2 Passing an Entire 2D Array 168 7.3 Declaring Pointer Variables 218 5.10 Multidimensional Arrays 170 7.4 Pointer Expressions and Pointer Arithmetic 220 5.11 Sparse Matrices 171 7.5 Null Pointers 224 5.11.1 Array Representation of Sparse 7.6 Generic Pointers 225 Matrices 172 7.7 Passing Arguments to Function Using 5.12 Applications of Arrays 173 Pointers 225 Case Study 2: Chapter 5 178 7.8 Pointers and Arrays 226 7.9 Passing an Array to a Function 230 7.10 Difference Between Array Name and Pointer 231 6. Strings 183 7.11 Pointers and Strings 232 6.1 Introduction 183 7.12 Arrays of Pointers 235 6.1.1 Reading Strings 185 7.13 Pointers and 2D Arrays 237 6.1.2 Writing Strings 185 7.14 Pointers and 3D Arrays 239 6.1.3 Summary of Functions Used to 7.15 Function Pointers 240 Read and Write Characters 186 7.15.1 Initializing a Function Pointer 240 6.2 Suppressing Input 187 7.15.2 Calling a Function Using a Function 6.2.1 Using a Scanset 187 Pointer 240 6.3 String Taxonomy 188 7.15.3 ComparingPress Function Pointers 241 6.4 Operations on Strings 189 7.15.4 Passing a Function Pointer as an Argument to a Function 241 6.4.1 Finding the Length of a String 189 7.16 Array of Function Pointers 241 6.4.2 Converting Characters of a String into 7.17 Pointers to Pointers 242 Upper Case 190 7.18 Memory Allocation in C Programs 243 6.4.3 Converting Characters of a String into 7.19 Memory Usage 243 Lower Case 191 7.20 Dynamic Memory Allocation 243 6.4.4 Concatenating Two Strings to Form 7.20.1 Memory Allocations Process 244 a New String 191 7.20.2 Allocating a Block of Memory 244 6.4.5 Appending a String to Another StringUniversity 192 7.20.3 Releasing the Used Space 245 6.4.6 Comparing Two Strings 192 7.20.4 To Alter the Size of Allocated 6.4.7 Reversing a String 193 Memory 245 6.4.8 Extracting a Substring from Left 194 7.21 Drawbacks of Pointers 247 6.4.9 Extracting a Substring from Right Annexure 3 256 of the String 195 Case Study 3: Chapters 6 and 7 259 6.4.10 Extracting a Substring from the Middle of a StringOxford 195 6.4.11 Inserting a String in Another String 196 8. Structure, Union, and Enumerated 6.4.12 Indexing 197 Data Types 262 6.4.13 Deleting a String from the Main String 197 8.1 Introduction 262 6.4.14 Replacing a Pattern with Another Pattern in 8.1.1 Structure Declaration 262 a String 198 8.1.2 Typedef Declarations 264 6.5 Miscellaneous String and Character 8.1.3 Initialization of Structures 264 8.1.4 Accessing the Members of a Functions 199 Structure 265 6.5.1 Character Manipulation Functions 199 8.1.5 Copying and Comparing Structures 265 6.5.2 String Manipulation Functions 199 8.2 Nested Structures 268 6.6 Arrays of Strings 205 8.3 Arrays of Structures 269 8.4 Structures and Functions 271 7. Pointers 216 8.4.1 Passing Individual Members 271 8.4.2 Passing the Entire Structure 271 7.1 Understanding the Computer’s Memory 216 8.4.3 Passing Structures Through Pointers 274

© Oxford University Press. All rights reserved. xiv Detailed Contents 8.5 Self-referential Structures 279 9.8.4 fgetpos () 322 8.6 Unions 279 9.8.5 fsetpos () 322 8.6.1 Declaring a Union 279 9.9 remove () 323 8.6.2 Accessing a Member of a Union 280 9.10 Renaming the File 323 8.6.3 Initializing Unions 280 9.11 Creating a Temporary File 323 8.7 Arrays of Union Variables 281 8.8 Unions Inside Structures 281 8.9 Structures Inside Unions 282 10. Preprocessor Directives 328 8.10 Enumerated Data Type 282 10.1 Introduction 328 8.10.1 enum Variables 283 10.2 Types of Preprocessor Directives 328 8.10.2 Using the Typedef Keyword 284 10.3 #define 329 8.10.3 Assigning Values to Enumerated 10.3.1 Object-like 329 Variables 284 10.3.2 Function-like Macros 330 8.10.4 Enumeration Type Conversion 284 10.3.3 Nesting of Macros 331 8.10.5 Comparing Enumerated Types 284 10.3.4 Rules for Using Macros 331 8.10.6 Input/Output Operations on Enumerated 10.3.5 Operators Related to Macros 331 Types 284 Annexure 4 291 10.4 #include 332 10.5 #undef 333 10.6 #line 333Press 9. Files 293 10.7 Pragma Directives 334 10.8 Conditional Directives 336 9.1 Introduction to Files 293 10.8.1 #ifdef 336 9.1.1 Streams in C 293 10.8.2 #ifndef 336 9.1.2 Buffer Associated with File Stream 294 9.1.3 Types of Files 294 10.8.3 #if Directive 337 9.2 Using Files in C 295 10.8.4 #else Directive 337 9.2.1 Declaring a File Pointer Variable 295 10.8.5 #elif Directive 337 9.2.2 Opening a File 295 10.8.6 #endif Directive 338 9.2.3 Closing a File Using fclose() 297 University 10.9 Defined Operator 338 9.3 Read Data From Files 297 10.10 #error directive 339 9.3.1 fscanf() 297 10.11 Predefined Macro Names 339 9.3.2 fgets() 298 Annexure 5 343 9.3.3 fgetc() 299 9.3.4 fread() 299 9.4 Writing Data to Files 300 11. Linked Lists 347 9.4.1 fprintf() 300 Oxford 11.1 Introduction 347 9.4.2 fputs () 302 11.2 Linked Lists Versus Arrays 348 9.4.3 fputc () 302 11.3 Memory Allocation and Deallocation for a Linked 9.4.4 fwrite () 302 List 349 9.5 Detecting the End-of-file 303 11.4 Different Types of Linked Lists 350 9.6 Error Handling During File Operations 304 11.5 Singly Linked Lists 351 9.6.1 clearerr() 304 11.5.1 Traversing a Singly Linked List 351 9.6.2 perror() 305 11.5.2 Searching for a Value in a Linked 9.7 Accepting Command Line Arguments 305 List 351 9.8 Functions for Selecting a Record Randomly 319 11.5.3 Inserting a New Node in a Linked 9.8.1 fseek() 319 List 352 9.8.2 ftell() 321 Case Study 4: Chapters 8, 9, and 11 363 9.8.3 rewind () 321

Appendix A: Additional C Programs 367 Appendix B: Answers to Objective Questions 372

© Oxford University Press. All rights reserved. Detailed Contents xv

Road Map to Syllabus

CS8251 Programming in C Press Unit I Introduction to programming paradigms - Structure of C program Chapters 1, 2, 3, 4, 8, 10 Basics of C Programming - C programming: Data types - Storage classes - Constants - Enumeration constants - Keywords - Operators: Precedence and Associativity - Expressions - Input/Output statements, Assignment statements - Decision making statements - Switch statement - Looping statements – Preprocessor directives - Compilation process Unit II Introduction to arrays: Declaration, initialization - One Chapters 5 and 6, Arrays and Strings dimensional array - Example program: Computing mean, median, Appendix A, Case Study and mode - Two-dimensionalUniversity arrays - Example program: Matrix 2 operations (Addition, Scaling, Determinant, and Transpose) - String operations: length, compare, concatenate, copy - Selection sort, linear and binary search Unit III Introduction to functions: Function prototype, Function definition, Chapters 4 and 7, Functions and Pointers Function call, Built-in functions (string functions, math functions) Appendix A - Recursion - Example program: Computation of Sine series, OxfordScientific calculator using built-in functions, Binary search using recursive functions - Pointers - Pointer operators - Pointer arithmetic - Arrays and pointers - Array of pointers - Example program: Sorting of names – Parameter passing: Pass by value, Pass by reference - Example program: Swapping of two numbers and changing the value of a variable using pass by reference Unit IV Structure - Nested structures -– Pointer and Structures - Array of Chapters 8 and 11 Structures structures – Example program using structures and pointers - Self- referential structures - Dynamic memory allocation - Singly linked list - typedef Unit V Files - Types of file processing: Sequential access, Random access Chapter 9, Appendix A File Processing - Sequential access file - Example program: Finding average of numbers stored in sequential access file - Random access file - Example Program: Transaction processing using random access files - Command line arguments

© Oxford University Press. All rights reserved. 1 Introduction to Programming

Takeaways

∑ Hardware ∑ System software ∑ Compiler, , linker, loader ∑ Application software ∑ Generation of programming languages ∑ Machine language ∑ Assembly language ∑ Monolithic programming ∑ PressStructured programming ∑ Procedural programming ∑ Object-oriented programming

1.1 INTRODUCTION TO COMPUTER in interpreting the images that are seen by the eyes and instructing the arms how to lift objects. SOFTWARE University Since computer hardware is a digital machine, it can When we talk about a computer, we actually mean two only understand two basic states: on and off. Computer things (Figure 1.1): software was developed to make efficient use of this binary system which is used internally by all to ∑ First is the computer hardware that does all the physical instruct the hardware to perform meaningful tasks. work computers are known for. The computer hardware cannot think and make ∑ Second is the computer software that commands the decisions on its own. So, it cannot be used to analyse hardware what to do and how to do it. a given set of data and find a solution on its own. The Oxford hardware needs a software (a set of programs) to instruct Computer system what has to be done. A program is a set of instructions that are arranged in a sequence to guide a computer to find a solution for a given problem. The process of writing a program is called programming. Computer hardware Computer software Computer software is written by computer programmers using a programming language. The programmer writes a set of instructions (program) using a specific programming System software Application . Such instructions are known as the source code. Another computer program called a compiler is used Figure 1.1 Parts of a computer system which transforms the source code into a language that the computer can understand. The result is an executable If we think of computer as a living being, then computer program, which is another software. the hardware would be the body that does things like Examples of computer software include: seeing with eyes and lifting objects with hands, where- ∑ Computer games which are widely used as a form of as the software would be the intelligence which helps entertainment.

© Oxford University Press. All rights reserved. 2 Programming in C

∑ Driver software which allows a computer to interact others. Simply put, application software represents with hardware devices such as printers, scanners, and programs that allow users to do something besides video cards. simply running the hardware. ∑ Educational software which includes programs and User 1 User 2 User N games that help in teaching and providing drills to help memorize facts. Educational software can be diversely used—from teaching computer-related activities like Application programs (games, spreadsheets, typing to higher education subjects like Chemistry. word processors, , webbrowsers) ∑ Media players and media development software that are specifically designed to play and/or edit digital media System Software (operating system) files such as music and videos. ∑ Productivity software is an older term used to denote any program that allows users to be more productive Computer Hardware in a business environment. Examples of such software (printer, mouse, scanner,keyboard, CPU, disk) include word processors, database management utilities, and presentation software. Figure 1.2 Relationship between hardware, system ∑ Operating system software which helps in coordinating software, and application software system resources and allows execution of other Press programs. Some popular operating systems are 1.2.1 System Software Windows Vista, Mac OS X, and Linux. System software is software designed to operate the computer hardware and to provide and maintain a platform 1.2 CLASSIFICATION OF COMPUTER for running application software. SOFTWARE The most widely used system software are discussed in the following sections: Computer software can be broadly classified into two groups: system software and application software. UniversityComputer BIOS and Device Drivers ∑ System software [according to Nutt, 1997] provides The computer BIOS and device drivers provide basic a general programming environment in which functionality to operate and control the hardware connected programmers can create specific applications to suit their to or built into the computer. needs. This environment provides new functions that are BIOS or Basic Input/Output System is a de facto not available at the hardware level and performs tasks standard defining a firmware interface. BIOS is built into related to execution of application programs. Oxford the computer and is the first code run by the computer System software represents programs that allow the when it is switched on. The key role of BIOS is to load hardware to run properly. System software is transparent and start the operating system. to the user and acts as an interface between the hardware When the computer starts, the first function that BIOS of the computer and the application software that users performs is to initialize and identify system devices such need to run on the computer. Figure 1.2 illustrates the as the video display card, keyboard and mouse, hard disk, relationship between application software, system CD/DVD drive, and other hardware. In other words, the software, and hardware. code in the BIOS chip runs a series of tests called POST ∑ Application software is designed to solve a particular (Power On Self Test) to ensure that the system devices are problem for users. It is generally what we think of when working correctly. we say the word ‘computer programs’. Examples of BIOS then locates software held on a peripheral device application software include spreadsheets, database such as a hard disk or a CD, and loads and executes that systems, desktop publishing systems, program software, giving it control of the computer. This process is development software, games, web browsers, among known as booting.

© Oxford University Press. All rights reserved. Introduction to Programming 3 BIOS is stored on a ROM chip built into the system and user to configure hardware, set the system clock, enable or has a user interface like that of a menu (Figure 1.3) that disable system components, and most importantly, select can be accessed by pressing a certain key on the keyboard which devices are eligible to be a potential boot device when the computer starts. The BIOS menu can enable the and set various password prompts.

Press

University

Figure 1.3 BIOS menu

To summarize, BIOS performs the following functions: From users’ point of view the primary consideration ∑ Initializes the system hardware is always the convenience. Users should find it easy to launch an application and work on it. For example, we ∑ Initializes system registersOxford use icons which give us clues about applications. We ∑ Initializes power management system have a different icon for launching a web browser, e-mail ∑ Tests RAM application, or even a document preparation application. ∑ Tests all the serial and parallel ports In other words, it is the human–computer interface which ∑ Initializes CD/DVD drive and hard disk controllers helps to identify and launch an application. The interface ∑ Displays system summary information hides a lot of details of the instructions that perform all these tasks. Operating System Similarly, if we examine the programs that help us in using input devices like keyboard/mouse, all the complex details of The primary goal of an operating system is to make the character reading programs are hidden from users. We the computer system (or any other device in which it is as users simply press buttons to perform the input operation installed like a cell phone) convenient and efficient to use. regardless of the complexity of the details involved. An operating system offers generic services to support An operating system ensures that the system resources user applications. (such as CPU, memory, I/O devices) are utilized efficiently.

© Oxford University Press. All rights reserved. 4 Programming in C

For example, there may be many service requests on a web ∑ System profilers can be used to provide detailed server and each user request needs to be serviced. Moreover, information about the software installed and hardware there may be many programs residing in the main memory. attached to the computer. Therefore, the system needs to determine which programs ∑ Anti-virus utilities are used to scan for computer viruses. are currently being executed and which programs need to ∑ Data compression utilities can be used to output a file wait for some I/O operation. This information is necessary with reduced file size. because the programs that need to wait can be suspended temporarily from engaging the processor. Hence, it is ∑ Cryptographic utilities can be used to encrypt and important for an operating system to have a control policy decrypt files. and algorithm to allocate the system resources. ∑ Launcher applications can be used as a convenient access point for application software. Utility Software ∑ Registry cleaners can be used to clean and optimize the Utility software is used to analyse, configure, optimize, and Windows operating system registry by deleting the old maintain the computer system. Utility programs may be registry keys that are no longer in use. requested by application programs during their execution ∑ Network utilities can be used to analyse the computer’s for multiple purposes. Some of them are as follows: network connectivity, configure network settings, check ∑ Disk defragmenters can be used to detect computer files data transfer, or log events. whose contents are broken across several locations on ∑ Command linePress interface (CLI) and Graphical user the hard disk, and move the fragments to one location in interface (GUI) can be used to make changes to the order to increase efficiency. operating system. ∑ Disk checkers can be used to scan the contents of a hard disk to find files or areas that are either corrupted in some Compiler, Interpreter, Linker, and Loader way, or were not correctly saved, and eliminate them in Compiler It is a special type of program that transforms order to make the hard drive operate more efficiently. the source code written in a programming language (the ∑ Disk cleaners can be used to locate files that are source language) into machine language comprising just either not required for computer operation, or take up two digits, 1s and 0s (the target language). The resultant considerable amounts of space. Disk cleaners help users code in 1s and 0s is known as the object code. The object to decide what to delete when their hard disk is full.University code is the one which will be used to create an executable ∑ Disk space analysers are used for visualizing the disk program. space usage by getting the size for each folder (including subfolders) and files in a folder or drive. Therefore, a compiler is used to translate source code ∑ Disk partitions utilities are used to divide an individual from a high-level programming language to a lower level drive into multiple logical drives, each with its own file language (e.g., assembly language or ). system. Each partition is thenOxford treated as an individual If the source code contains errors then the compiler will drive. not be able to perform its intended task. Errors resulting ∑ Backup utilities can be used to make a copy of all from the code not conforming to the syntax of the information stored on a disk. In case a disk failure programming language are called syntax errors. Syntax occurs, backup utilities can be used to restore the entire errors may be spelling mistakes, typing mistakes, etc. disk. Even if a file gets deleted accidentally, the backup Another type of error is logical error which occurs when utility can be used to restore the deleted file. the program does not function accurately. Logical errors ∑ Disk compression utilities can be used to enhance the are much harder to locate and correct. capacity of the disk by compressing/decompressing the The work of a compiler is simply to translate human contents of a disk. readable source code into computer executable machine ∑ File managers can be used to provide a convenient code. It can locate syntax errors in the program (if any) method of performing routine data management but cannot fix it. Until and unless the syntactical errors tasks such as deleting, renaming, cataloguing, moving, are rectified the source code cannot be converted into the copying, merging, generating, and modifying data sets. object code.

© Oxford University Press. All rights reserved. Introduction to Programming 5

Interpreter Like the compiler, the interpreter also software which is involved in integrating a computer’s executes instructions written in a high-level language. capabilities, but typically does not directly apply them in Basically, a program written in a high-level language can the performance of tasks that benefit users. be executed in any of the two ways. First by compiling To better understand application software consider an the program and second, to pass the program through an analogy where hardware would depict the relationship of interpreter. an electric light bulb (an application) to an electric power While the compiler translates instructions written in generation plant (a system) that depicts the software. high-level programming language directly into the machine The power plant merely generates electricity which language, the interpreter, on the other hand, translates is not by itself of any real use until harnessed to an the instructions into an intermediate form, which it then application like the electric light that performs a service executes. This clearly means that the interpreter interprets which actually benefits users. the source code line by line. This is in striking contrast with Typical examples of software applications are word the compiler which compiles the entire code in one go. processors, spreadsheets, media players, education software, Usually, a compiled program executes faster than an CAD, CAM, data communication software, and statistical interpreted program. However, the big advantage of an and operational research software. Multiple applications interpreted program is that it does not need to go through bundled together as a package are sometimes referred to as the compilation stage during which machine instructions an application suite. are generated. This process can be time consuming if the Press program is long. Moreover, the interpreter can immediately 1.3 PROGRAMMING LANGUAGES execute high-level programs. All in all, compilers and interpreters both achieve A programming language is a language specifically similar purposes, but inherently different as to how they designed to express computations that can be performed achieve that purpose. by the computer. Programming languages are used to create programs that control the behaviour of a system, Linker (link editor binder) It is a program that combines to express algorithms, or as a mode of human–computer object modules to form an executable program. Gener- communication. ally, in case of a large program, the programmers prefer Usually, programming languages have a vocabulary to break a code into smaller modules as this simplifiesUniversity the of syntax and semantics for instructing a computer to programming task. Eventually, when the source code of all perform specific tasks. The term programming language the modules has been converted into object code, we need usually refers to high-level languages, such as BASIC, to put all the modules together. This is the job of the linker. C, C++, COBOL, , Ada, and Pascal to name a Usually, the compiler automatically invokes the linker as few. Each of these languages has a unique set of keywords the last step in compiling a program. (words that it understands) and a special syntax for organizing program instructions. Loader It is a special type of programOxford that copies programs While high-level programming languages are easy from a storage device to main memory, where they can be for humans to read and understand, the computer executed. However, in this book we will not go into the actually understands the machine language that consists details of how a loader actually works. This is because of numbers only. Each type of CPU has its own unique the functionality of a loader is generally hidden from the machine language. programmer. As a programmer, it suffices to learn that the In between the machine languages and high-level task of a loader is to bring the program and all its related languages, there is another type of language known as files into the main memory from where it can be executed assembly language. Assembly languages are similar to by the CPU. machine languages, but they are much easier to program because they allow a programmer to substitute names for 1.2.2 Application Software numbers. Application software is a type of computer software that However, irrespective of what language the programmer uses, the program written using any programming employs the capabilities of a computer directly to perform language has to be converted into machine language so a user-defined task. This is in contrast with system

© Oxford University Press. All rights reserved. 6 Programming in C that the computer can understand it. There are two ways to In the 1950s each computer had its own native do this: compile the program or interpret the program language, and programmers had primitive systems for The question of which language is the best depends on combining numbers to represent instructions such as add the following factors: and subtract. Although there were similarities between ∑ The type of computer on which the program has to be each of the machine languages, a computer could not executed understand programs written in another machine language (Figure 1.4). ∑ The type of program ∑ The expertise of the programmer MACHINE LANGUAGE For example, FORTRAN is a particularly good This is an example ofamachine languageprogram that will add two numbers and find their average. It is in hexadecimal language for processing numerical data, but it does not notation instead of binary notation because this is how the lend itself very well to organizing large programs. Pascal computer presented the code to the programmer. can be used for writing well-structured and readable D000000A D000 programs, but it is not as flexible as the C programming language. C++ goes one step ahead of C by incorporating D000000F D009 powerful object-oriented features, but it is complex and D000000B D009 difficult to learn. D009 D009 1.4 GENERATION OF PROGRAMMING Press D0Q 0 LANGUAGES FF55 CF FF54 CF FF53 CF C1 DOD0 FF24 CF FF27 CF D2 C7 D00C We now know that programming languages are the D0E4 primary tools for creating software. As of now, hundreds Dd0D of programming languages exist in the market, some more used than others, and each claiming to be the best. Dd3D However, back in the 1940s when computers were being developed there was just one language—the machine Figure 1.4 A machine language program language. University The concept of generations of programming languages In machine language, all instructions, memory locations, (also known as levels) is closely connected to the advances numbers, and characters are represented in strings of in technology that brought about computer generations. 1s and 0s. Although machine-language programs are The four generations of programming languages include: typically displayed with the binary numbers represented in octal (base 8) or hexadecimal (base 16), these programs ∑ Machine language are not easy for humans to read, write, or debug. ∑ Assembly language Oxford The main advantage of machine language is that the ∑ High-level language (also known as third generation code can run very fast and efficiently, since it is directly language or 3GL) executed by the CPU. ∑ Very high-level language (also known as fourth However, on the downside, the machine language is generation language or 4GL) difficult to learn and is far more difficult to edit if errors occur. Moreover, if you want to add some instructions 1.4.1 First Generation: Machine Language into memory at some location, then all the instructions after the insertion point would have to be moved down Machine language was used to program the first stored to make room in memory to accommodate the new program on computer systems. This is the lowest level instructions. of programming language. The machine language is the Last but not the least, the code written in machine only language that the computer understands. All the language is not portable across systems and to transfer commands and data values are expressed using 1 and 0s, the code to a different computer it needs to be completely corresponding to the ‘on’ and ‘off’ electrical states in a rewritten since the machine language for one computer computer. could be significantly different from another computer.

© Oxford University Press. All rights reserved. Introduction to Programming 7 Architectural considerations made portability a tough The following instructions are a part of assembly issue to resolve. language code to illustrate addition of two numbers: MOV AX,4 Stores value 4 in the AX 1.4.2 Second Generation: Assembly Language register of CPU MOV BX,6 Stores value 6 in the BX The second generation of programming language includes register of CPU the assembly language. Assembly languages are symbolic ADD AX,BX Adds the contents of AX and BX programming languages that use symbolic notation to registers. Stores the result in represent machine-language instructions. These languages AX register are closely connected to machine language and the internal Although assembly languages are much better to architecture of the computer system on which they are program as compared to the machine language, they still used. Since they are close to the machine, assembly require the programmer to think on the machine’s level. language is also called low-level language. Nearly all Even today, some programmers still use assembly language computer systems have an assembly language available to write parts of applications where speed of execution is for use. critical, such as video games but most programmers today Assembly language developed in the mid 1950s have switched to third or fourth generation programming was a great leap forward. It used symbolic codes also languages. known as mnemonic codes that are easy-to-remember abbreviations, rather than numbers. Examples of these 1.4.3 Third GenerationPress Programming codes include ADD for add, CMP for compare, MUL for Languages multiply, etc. Assembly language programs consist of a series of A third generation programming language (3GL) is individual statements or instructions that instruct the a refinement of the second-generation programming computer what to do. Basically, an assembly language language. The 2GL languages brought logical structure to statement consists of a label, an operation code, and one software. The third generation was introduced to make the or more operands. languages more programmer friendly. Labels are used to identify and reference instructions in Third Generation Programming Languages spurred the the program. The operation code (opcode) is a mnemonicUniversity great increase in data processing that occurred in the 1960s that specifies the operation that has to be performed such and 1970s. In these languages, the program statements as move, add, subtract, or compare. The operand specifies are not closely related to the internal architecture of the computer and is therefore often referred to as high-level the register or the location in main memory where the data languages. to be processed is located. Generally, a statement written in a high-level program- However, like the machine language, the statement ming language will expand into several machine language or instruction in the assembly language will vary from Oxford instructions. This is in contrast to assembly languages, machine to another because the language is directly where one statement would generate one machine lan- related to the internal architecture of the computer and is guage instruction. Third Generation Programming Lan- not designed to be machine independent. This makes the guages made programming easier, efficient, and less prone code written in assembly language less portable as the to errors. code written for one machine will not run on machines High-level languages fall somewhere between natu- from a different or sometimes even the same manufacturer. ral languages and machine languages. Third Generation No doubt, the code written in assembly language will be Programming Languages include languages such as FOR- very efficient in terms of execution time and main memory TRAN (FORmula TRANslator) and COBOL (COmmon usage as the language is also close to the computer. Business Oriented Language) that made it possible for Programs written in assembly language need a scientists and business people to write programs using fa- translator often known as assembler to convert them miliar terms instead of obscure machine instructions. into machine language. This is because the computer will The first widespread use of high-level languages in the understand only the language of 1s and 0s and will not early 1960s changed programming into something quite understand mnemonics like ADD and SUB. different from what it had been. Programs were written in

© Oxford University Press. All rights reserved. 8 Programming in C statements like English language statements, making them only what they want the computer to do, without supplying more convenient to use and giving the programmer more all the details of how it has to be done. time to address a client’s problems. There is no standard rule that defines what a 4GL is but Although 3GLs relieve the programmer of demanding certain characteristics of such languages include: details, they do not provide the flexibility available in low- ∑ the code comprising instructions are written in English- level languages. However, a few high-level languages like sentences; like C and FORTRAN combine some of the flexibility ∑ they are non-procedural, so users concentrate on ‘what’ of assembly language with the power of high-level instead of the ‘how’ aspect of the task; languages, but these languages are not well suited to an amateur programmer. ∑ the code is easier to maintain; While some high-level languages were designed to serve ∑ the code enhances the productivity of the programmers a specific purpose (such as controlling industrial robots as they have to type fewer lines of code to get something or creating graphics), other languages were flexible and done. It is said that a programmer becomes 10 times considered to be general-purpose languages. Most of the more productive when he writes the code using a 4GL programmers preferred to use general-purpose high-level than using a 3GL. languages like BASIC (Beginners’ All-purpose Symbolic A typical example of a 4GL is the Instruction Code), FORTRAN, PASCAL, COBOL, C++, or that allows a user to request information from a database Java to write the code for their applications. with precisely worded English-like sentences. A query Again, a translator is needed to translate the instructions language is used asPress a database user interface and hides the written in high-level language into computer-executable specific details of the database from the user. For example, machine language. Such translators are commonly known when working with structured query language (SQL), as interpreters and compilers. Each high-level language the programmer just needs to remember a few rules of has many compilers. syntax and logic, and it is easier to learn than COBOL For example, the machine language generated by one or C. computer’s C compiler is not the same as the machine Let us take an example in which a report has to be language of some other computer. Therefore, it is necessary generated that displays the total number of students to have a C compiler for each type of computer on which enrolled in each class and in each semester. Using a 4GL, the C program has to be executed. Universitythe request would look similar to one that follows: Third generation programming languages have made TABLE FILE ENROLLMENT it easier to write and debug programs, which gives programmers more time to think about its overall logic. SUM STUDENTS BY SEMESTER BY CLASS The programs written in such languages are portable So we see that a 4GL is much simpler to learn and work between machines. For example, a program written in with. The same code if written in C language or any other standard C can be compiled and executed on any computer 3GL would require multiple lines of code to do the same that has a standard C compiler.Oxford task. Fourth generation programming languages are still 1.4.4 Fourth Generation: Very High-Level evolving, which makes it difficult to define or standardize Languages them. The only downside of a 4GL is that it does not make efficient use of the machine’s resources. However, With each generation, programming languages started the benefit of executing a program fast and easily, far becoming easier to use and more like natural languages. outweighs the extra costs of running it. However, fourth generation programming languages (4GLs) are a little different from their its prior generation because they are basically non-procedural. When writing 1.4.5 Fifth Generation Programming Languages code using a procedural language, the programmer has to Fifth generation programming languages (5GLs) are cen- tell the computer how a task is done—add this, compare tred on solving problems using constraints given to the that, do this if the condition is true, and so on, in a very program, rather than using an algorithm written by a pro- specific step-by-step manner. In striking contrast, while grammer. Most constraint-based and using a non-procedural language the programmers define languages and some declarative languages form a part of

© Oxford University Press. All rights reserved. Introduction to Programming 9 the fifth-generation languages. Fifth generation program- ∑ Monolithic programming—emphasizes on finding a ming languages are widely used in artificial intelligence solution research. Typical examples of 5GLs include , ∑ Procedural programming—lays stress on algorithms OPS5, and Mercury. ∑ Structured programming—focuses on modules Another aspect of a 5GL is that it contains visual tools ∑ Object-oriented programming—emphasizes on classes to help develop a program. A good example of a fifth and objects generation language is . So taking a forward leap than the 4GLs, 5GLs are ∑ Logic-oriented programming—focuses on goals usually designed to make the computer solve a given problem expressed in predicate calculus without the programmer. While working with a 4GL, the ∑ Rule-oriented programming—makes use of ‘if-then- programmer had to write specific code to do a work but else’ rules for computation with 5GL, the programmer only needs to worry about ∑ Constraint-oriented programming—utilizes invariant what problems need to be solved and what conditions need relationships to solve a problem to be met, without worrying about how to implement a routine or algorithm to solve them. Each of these paradigms has its own strengths and Generally, 5GLs were built upon Lisp, many originating weaknesses and no single paradigm can suit all on the Lisp machine, such as ICAD. Then, there are many applications. For example, for designing computation- frame languages such as KL-ONE. intensive problems, procedure-oriented programming In the 1990s, 5GLs were considered to be the wave of is preferred; for designing a knowledge base, rule- the future, and some predicted that they would replace all based programmingPress would be the best option; and for other languages for system development (except the low- hypothesis derivation, logic-oriented programming is level languages). In 1982 to 1993 Japan had put much used. In this book, we will discuss only the first four research and money into their fifth generation computer paradigms. systems project, hoping to design a massive computer network of machines using these tools. But when larger 1.5.1 Monolithic Programming programs were built, the flaws of the approach became more apparent. Researchers began to observe that starting Programs written using monolithic programming languages from a set of constraints for defining a particular problem, such as assembly language and BASIC consist of global data then deriving an efficient algorithm to solve the Universityproblem and sequential code. The global data can be accessed and is a very difficult task. All these things could not be modified (knowingly or mistakenly) from any part ofthe automated and still requires the insight of a programmer. program, thereby posing a serious threat to its integrity. A However, today the fifth-generation languages are back sequential code is one in which all instructions are executed as a possible level of computer language. Software vendors in the specified sequence. In order to change the sequence of across the globe currently claim that their software meets instructions, jump statements or ‘goto’ statements are used. the visual ‘programming’ requirements of the 5GL concept. Figure 1.5 shows the structure of a monolithic program. Oxford As the name suggests, monolithic programs have just one program module as 1.5 PROGRAMMING PARADIGMS such programming ADB 10 Global data A is a fundamental style of languages do not BDB 20 programming that defines how the structure and basic support the concept of SUM DB? elements of a computer program will be built. The subroutines. Therefore, all the actions required MOV AX, A style of writing programs and the set of capabilities Sequential ADD AX, B and limitations that a particular programming language to complete a particular code with has depends on the programming paradigm it supports. task are embedded MOV SUM, AX JMP While some programming languages strictly follow a within the same JMP STOP instruction single paradigm, others may draw concepts from more application itself. This ...... than one. The sweeping trend in the evolution of high- not only makes the size STOP: EXIT level programming languages has resulted in a shift in of the program large but programming paradigm. These paradigms, in sequence of also makes it difficult Figure 1.5 Structure of a their application, can be classified as follows: to debug and maintain. monolithic program

© Oxford University Press. All rights reserved. 10 Programming in C For all these reasons, monolithic programming language down into separate modules. This allows the code to be is used only for very small and simple applications where loaded into memory more efficiently and also be reused reusability is not a concern. in other programs. Modules are coded separately and once a module is written and tested individually, it is then 1.5.2 Procedural Programming integrated with other modules to form the overall program structure (refer to Fig. 1.7). Structured programming is, In procedural lan- therefore, based on modularization which groups related Global data guages, a program is statements together into modules. Modularization makes it divided into subrou- easier to write, debug, and understand the program. Ideally, tines that can access modules should not be longer than a page. It is always easy global data. To avoid to understand a series of 10 single-page modules than a repetition of code, single 10-page program. For large and complex programs, each subroutine per- Program the overall program structure may further require the forms a well-defined need to break the modules into subsidiary pieces. This Figure 1.6 Structure of a task. A subroutine process continues until an individual piece of code can procedural program that needs the ser- be written easily. Almost every modern programming vice provided by an- language similar to C, Pascal, etc., supports the concepts other subroutine can call that subroutine. Therefore, with of structured programming. In addition to the techniques ‘jump’, ‘goto’, and ‘call’ instructions, the sequence of ex- of structured programmingPress for writing modules, it also ecution of instructions can be altered. Figure 1.6 shows the focuses on structuring its data. In structured programming, structure of a procedural language. FORTRAN and CO- the program flow follows a simple sequence and usually BOL are two popular procedural programming languages. avoids the use of ‘goto’ statements. Besides sequential flow, structured programming also supports selection and Advantages repetition as mentioned here. ∑ The only goal is to write correct programs. ∑ Selection allows for choosing any one of a number of ∑ Programs are easier to write as compared to monolithic statements to execute, based on the current status of the programming. program. Selection statements contain keywords such Universityas ‘if’, ‘then’, ‘end if’, or ‘switch’ that help to identify Disadvantages the order as a logical executable. ∑ In repetition, a selected statement remains active until ∑ No concept of reusability the program reaches a point where there is a need for ∑ Requires more time and effort to write programs some other action to take place. It includes keywords ∑ Programs are difficult to maintain such as ‘repeat’, ‘for’, or ‘do… until’. Essentially, ∑ Global data is shared andOxford therefore may get altered repetition instructs the program as to how long it needs (mistakenly) to continue the function before requesting further instructions.

1.5.3 Structured Programming Modules that have Global data local data and Structured programming, also referred to as modular code programming, was first suggested by mathematicians, Corrado Bohm and Guiseppe Jacopini in 1966. It was specifically designed to enforce a logical structure on the program to make it more efficient and easier to understand and modify. Structured programming was basically defined to be used in large programs that require large Program development team to develop different parts of the same program. Structured programming employs a top-down Figure 1.7 Structured program approach in which the overall program structure is broken

© Oxford University Press. All rights reserved. Introduction to Programming 11 Advantages programming paradigms are task-based as they focus on the actions the program should accomplish. However, ∑ The goal of structured programming is to write correct the object-oriented paradigm is task-based and data- programs that are easy to understand and change. based. In this paradigm, all the relevant data and tasks ∑ Modules enhance programmers’ productivity by are grouped together in entities known as objects (refer allowing them to look at the big picture first and focus to Fig. 1.8). For example, consider a list of numbers. The on details later. procedural or structured programming paradigm ∑ With modules, many programmers can work on a considers this list as single, large program, with each working on a different merely a collection of Object 1 module. data. Any program that ∑ A structured program takes less time to be written than accesses this list must Object 2 other programs. Modules or procedures written for one have some procedures or program can be reused in other programs as well. functions to process this ∑ Each module performs a specific task. list. For example, to find Object 3 the largest number or to ∑ Each module has its own local data. sort the numbers in the ∑ A structured program is easy to debug because each list, we need specific procedure is specialized to perform just one task and Object 4 procedures or functions to every procedure can be checked individually for the do the task. Therefore, the presence of any error. In striking contrast, unstructured Press Objects of a program list is a passive entity as it programs consist of a sequence of instructions that are interact by sending is maintained by a messages to each other not grouped for specific tasks. Their logic is cluttered controlling program rather with details and, therefore, difficult to follow. than having the Figure 1.8 Object-oriented paradigm ∑ Individual procedures are easy to change as well as responsibility of understand. In a structured program, every procedure maintaining itself. However, in the object-oriented has meaningful names and has clear documentation paradigm, the list and the associated operations are to identify the task performed by it. Moreover, treated as one entity known as an object. In this approach, a correctly written structured program isUniversity self- the list is considered an object consisting of the list, documenting and can be easily understood by another along with a collection of routines for manipulating the programmer. list. In the list object, there may be routines for adding a ∑ More emphasis is given on the code and the least number to the list, deleting a number from the list, sorting importance is given to the data. the list, etc. The major difference between OOP and traditional approaches is that the program accessing this Disadvantages list need not contain procedures for performing tasks; ∑ Not data-centred Oxford rather, it uses the routines provided in the object. In other ∑ Global data is shared and therefore may get inadvertently words, instead of sorting the list as in the procedural modified paradigm, the program asks the list to sort itself. Therefore, we can conclude that the object-oriented ∑ Main focus is on functions paradigm is task-based (as it considers operations) as 1.5.4 Object-oriented Programming (OOP) well as data-based (as these operations are grouped with the relevant data). With the increase in size and complexity of programs, The striking features of OOP include the following: there was a need for a new programming paradigm that ∑ Programs are data centred. could help to develop maintainable programs. To implement this, the flaws in previous paradigms had to ∑ Programs are divided in terms of objects and not be corrected. Consequently, OOP was developed. It treats procedures. data as a critical element in the program development ∑ Functions that operate on data are tied together with the and restricts its flow freely around the system. We have data. seen that monolithic, procedural, and structured ∑ Data is hidden and not accessible by external functions.

© Oxford University Press. All rights reserved. 12 Programming in C

∑ New data and functions can be easily added as and when In the forthcoming chapters, we are going to study C required. programming language which supports both procedural as ∑ Follows a bottom-up approach for problem solving. well as structured programming.

POINTS TO REMEMBER

∑ A computer has two parts—computer hardware which from a storage device to main memory, where they can be does all the physical work and computer software which executed. tells the hardware what to do and how to do it. ∑ The fourth generations of programming languages ∑ A program is a set of instructions that are arranged in are: machine language, assembly language, high-level a sequence to guide a computer to find a solution for a language, and very high-level language. given problem. The process of writing a program is called ∑ Machine language is the lowest level of programming programming. language that a computer understands. All the instructions ∑ Computer software is written by computer programmers and data values are expressed using 1s and 0s. using a programming language. ∑ Assembly language is a low-level language that uses ∑ Application software is designed to solve a particular symbolic notation to represent machine language problem for users. instructions. Press ∑ System software represents programs that allow the ∑ Third-generation languages are high-level languages in hardware to run properly. It acts as an interface between which instructions are written in statements like English the hardware of the computer and the application language statements. Each instruction in this language software that users need to run on the computer. expands into several machine language instructions. ∑ The key role of BIOS is to load and start the operating ∑ Fourth-generation languages are non-procedural system. The code in the BIOS chip runs a series of tests languages in which programmers define only what they called POST (Power On Self Test) to ensure that the system want the computer to do, without supplying all the details devices are working correctly. BIOS is stored on a ROM of how it has to be done. chip built into the system. ∑ Programs written using monolithic programming ∑ Utility software is used to analyse, configure,University optimize, languages such as assembly language and BASIC consist and maintain the computer system. of global data and sequential code. ∑ A compiler is a special type of program that transforms ∑ In procedural languages, a program is divided into source code written in a programming language (the subroutines that can access global data. source language) into machine language comprising of ∑ Structured programming employs a top-down approach just two digits—1s and 0s (the target language). The in which the overall program is broken down into separate resultant code in 1s and 0s is known as the object code. modules. ∑ Linker is a program that combinesOxford object modules to form ∑ Object-oriented programming treats data as a critical an executable program. element in the program development and restricts its ∑ A loader is a special type of program that copies programs flow freely around the system.

EXERCISES

Fill in the Blanks 5. ______transforms the source code into binary 1. ______tells the hardware what to do and how to do language. it. 6. ______allows a computer to interact with additional 2. The hardware needs a ______to instruct what has to hardware devices such as printers, scanners, and video be done. cards. 3. The process of writing a program is called ______. 7. ______helps in coordinating system resources and 4. ______is used to write computer software. allows other programs to execute.

© Oxford University Press. All rights reserved. Introduction to Programming 13

8. ______provides a platform for running application 11. Which programming paradigm utilizes invariant software. relationships to solve a problem? 9. ______can be used to encrypt and decrypt files. (a) Rule-based (b) Constraint-based 10. An assembly language statement consists of a ______, (c) Structured (d) Object-oriented an ______, and ______. 12. Which is the preferred paradigm for designing a 11. ______and ______statements are used to change knowledge base? the sequence of execution of instructions. (a) Rule-based (b) Constraint-based 12. ______paradigm supports bottom-up approach of (c) Structured (d) Object-oriented problem-solving. 13. Which type of programming does not support 13. FORTRAN and COBOL are two popular ______subroutines? programming languages. (a) Monolithic (b) Structured Multiple Choice Questions (c) Rule-based (d) Object-oriented 1. BIOS is stored in 14. C and Pascal belong to which type of programming language? (a) RAM (b) ROM (a) Monolithic (b) Structured (c) Hard disk (d) None of these (c) Logic-oriented (d) Object-oriented 2. Which language should not be used for organizing large programs? 15. Which paradigm holds data as a priority? (a) C (b) C++ (a) MonolithicPress (b) Structured (c) COBOL (d) FORTRAN (c) Logic-oriented (d) Object-oriented 3. Which language is a symbolic language? State True or False (a) Machine language (b) C (c) Assembly language (d) All of these 1. Computer hardware does all the physical work. 2. The computer hardware cannot think and make 4. Which language is a 3GL? decisions on its own. (a) C (b) COBOL 3. A software is a set of instructions that are arranged in a (c) FORTRAN (d) All of these sequence to guide a computer to find a solution for the 5. Which language does not need any translator? Universitygiven problem. (a) Machine language (b) 3GL 4. Word processor is an example of educational software. (c) Assembly language (d) 4GL 5. Desktop publishing system is a system software. 6. Choose the odd one out. 6. BIOS defines firmware interface. (a) Compiler (b) Interpreter 7. Pascal cannot be used for writing well-structured programs. (c) Assembler (d) Linker 8. Assembly language is a low-level programming language. 7. Which one is a utility software? Oxford 9. Operation code is used to identify and reference (a) Word processor instructions in the program. (b) Antivirus 10. 3GLs are procedural languages. (c) Desktop publishing tool 11. In monolithic paradigm, global data can be accessed and (d) Compiler modified from any part of the program. 8. POST is performed by 12. Monolithic programs have two modules. (a) Operating ystems (b) Assembler 13. Monolithic programs are easy to debug and maintain. (c) BIOS (d) Linker 14. Structured programming is based on modularization. 9. Printer, monitor, keyboard, and mouse are examples of 15. Object-oriented programming supports modularization. (a) Operating ystems (b) Computer hardware 16. Structured programming heavily uses goto statements. (c) Firmware (d) Device drivers 17. Modules enhance programmers’ productivity. 10. Windows VISTA, Linux, Unix are examples of 18. A structured program takes more time to be written than other programs. (a) Operating ystems (b) Computer hardware (c) Firmware (d) Device drivers

© Oxford University Press. All rights reserved. 14 Programming in C Review Questions 13. What is BIOS? 1. Broadly classify the computer system into two parts. 14. What do you understand by utility software? Is it a must Also make a comparison between a human body and to have it? the computer system thereby explaining what each part 15. Differentiate between syntax errors and logical errors. does. 16. Can a program written in a high-level language be 2. Differentiate between computer hardware and software. executed without a linker? 3. Define programming. 17. Give a brief description of generation of programming 4. Define source code. languages. Highlight the advantages and disadvantages of languages in each generation. 5. What is booting? 18. What do you understand by the term ‘programming 6. What criteria are used to select the language in which paradigm’? the program will be written? 19. Discuss any three programming paradigms in detail. 7. Explain the role of operating system. 20. How is structured programming better than monolithic 8. Give some examples of computer software. programming? 9. Differentiate between the source code and the object 21. Describe the special characteristics of monolithic pro- code. gramming. 10. Why are compilers and interpreters used? 22. Explain how functional abstraction is achieved in struc- 11. Is there any difference between a compiler and an tured programming. interpreter? Press 23. Which programming paradigm is data-based and why? 12. What is application software? Give examples. 24. What are the advantages of modularization?

University

Oxford

© Oxford University Press. All rights reserved.