100% found this document useful (2 votes)
464 views42 pages

C Programming Sisir Kumar Jena CRC

C language book

Uploaded by

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

C Programming Sisir Kumar Jena CRC

C language book

Uploaded by

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

C Programming

C Programming
Learn to Code

Sisir Kumar Jena


First edition published 2022
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742

and by CRC Press


2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

CRC Press is an imprint of Taylor & Francis Group, LLC

© 2022 Sisir Kumar Jena

Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot
assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize to
copyright holders if permission to publish in this form has not been obtained. If any copyright material has not
been acknowledged please write and let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted,
or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, includ-
ing photocopying, microfilming, and recording, or in any information storage or retrieval system, without writ-
ten permission from the publishers.

For permission to photocopy or use material electronically from this work, access www.copyright.com or contact
the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works
that are not available on CCC please contact [email protected]

Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for
identification and explanation without intent to infringe.

Library of Congress Cataloging‑in‑Publication Data


Names: Jena, Sisir Kumar, author.
Title: C programming : learn to code / Sisr Kumar Jena.
Description: First edition. | Boca Raton, FL : Chapman & Hall/CRC Press, [2022] | Includes bibliographical
references and index. | Summary: "The C programming language is a popular language in industries as well as
academics. Since its invention and standardized as ANSI C, several other standards known as C99, C11, and
C17 were published with new features in subsequent years. This book covers all the traits of ANSI C and
includes new features present in other standards. The content of this book helps a beginner to learn the
fundamental concept of the C language. The book contains a step-by-step explanation of every program that
allows a learner to understand the syntax and builds a foundation to write similar programs.Besides, exercises
and illustrations present in this book make it a complete textbook in all aspects"-- Provided by publisher.
Identifiers: LCCN 2021027981 (print) | LCCN 2021027982 (ebook) | ISBN 9781032036250 (hbk)
| ISBN 9781032036274 (pbk) | ISBN 9781003188254 (ebk)
Subjects: LCSH: C (Computer program language) | Computer programming.
Classification: LCC QA76.73.C15 J46 2022 (print) | LCC QA76.73.C15
(ebook) | DDC 005.13/3--dc23
LC record available at https://lccn.loc.gov/2021027981
LC ebook record available at https://lccn.loc.gov/2021027982

ISBN: 978-1-032-03625-0 (hbk)


ISBN: 978-1-032-03627-4 (pbk)
ISBN: 978-1-003-18825-4 (ebk)

DOI: 10.1201/9781003188254

Typeset in Palatino
by SPi Technologies India Pvt Ltd (Straive)
In memory of my father, my guide, Baikuntha Nath Jena
Contents

Preface........................................................................................................................................... xvii
Acknowledgments........................................................................................................................xix
Organization of this Book............................................................................................................xxi
Author Biography...................................................................................................................... xxiii

1. Introduction to the Computer............................................................................................... 1


1.1 Introduction.................................................................................................................... 1
1.2 Definition and Characteristics of a Computer System............................................. 1
1.3 History of the Computer............................................................................................... 2
1.4 Basic Computer Organization...................................................................................... 4
1.4.1 Input Devices..................................................................................................... 5
1.4.2 Memory.............................................................................................................. 6
1.4.3 Central Processing Unit................................................................................... 6
1.4.4 Output Devices.................................................................................................7
1.5 Computer Memory........................................................................................................ 7
1.5.1 Registers............................................................................................................. 8
1.5.2 Cache Memory.................................................................................................. 8
1.5.3 Primary Memory............................................................................................... 8
1.5.4 Random Access Memory............................................................................... 10
1.5.5 Read Only Memory........................................................................................ 10
1.5.6 Secondary Memory......................................................................................... 10
1.5.7 Hard Disk Drive.............................................................................................. 10
1.5.8 Solid State Drive.............................................................................................. 11
1.6 Introduction to the Operating System...................................................................... 12
1.6.1 Hardware and Software................................................................................. 12
1.6.2 Operating System...........................................................................................12
1.6.3 Functions of an Operating System............................................................... 13
1.7 Review Questions........................................................................................................ 14
1.7.1 Long Answers.................................................................................................. 14
1.7.2 Short Answers................................................................................................. 14
1.7.3 Practical Exercises........................................................................................... 15
References................................................................................................................................ 16

2. Number Systems.................................................................................................................... 17
2.1 Introduction.................................................................................................................. 17
2.1.1 Non-positional Number System................................................................... 17
2.1.2 Positional Number System............................................................................ 17
2.2 Positional Number Systems....................................................................................... 18
2.2.1 Decimal Number System............................................................................... 18
2.2.2 Binary Number System.................................................................................. 20
2.2.3 Hexadecimal Number System...................................................................... 21
2.2.4 Octal Number System.................................................................................... 22

vii
viii Contents

2.3 Number Conversion.................................................................................................... 23


2.3.1 Binary to Decimal........................................................................................... 23
2.3.1.1 Approach 1....................................................................................... 24
2.3.1.2 Approach 2....................................................................................... 24
2.3.2 Binary Fraction to Decimal Conversion...................................................... 25
2.3.3 Binary to Decimal Conversion...................................................................... 26
2.3.4 Decimal Fraction to Binary Fraction............................................................ 27
2.3.5 Decimal to Octal Conversion........................................................................ 28
2.3.6 Octal to Decimal Conversion........................................................................ 29
2.3.7 Octal to Binary Conversion........................................................................... 29
2.3.7.1 Procedure 1....................................................................................... 29
2.3.7.2 Procedure 2....................................................................................... 30
2.3.8 Binary to Octal Conversion........................................................................... 30
2.3.8.1 Procedure 1....................................................................................... 30
2.3.8.2 Procedure 2....................................................................................... 31
2.3.9 Decimal to Hexadecimal Conversion.......................................................... 32
2.3.10 Hexadecimal to Decimal Conversion.......................................................... 33
2.3.11 Hexadecimal to Binary Conversion............................................................. 33
2.3.11.1 Procedure 1....................................................................................... 33
2.3.11.2 Procedure 2....................................................................................... 34
2.3.12 Binary to Hexadecimal Conversion............................................................. 34
2.3.12.1 Procedure 1....................................................................................... 34
2.3.12.2 Procedure 2....................................................................................... 35
2.4 Review Questions........................................................................................................ 36
2.4.1 Conversion Questions.................................................................................... 36

3. Problem Solving through Flowcharts and Algorithms.................................................. 39


3.1 Introduction.................................................................................................................. 39
3.2 Problem-solving Approach......................................................................................... 40
3.3 Algorithm Design........................................................................................................41
3.3.1 Characteristics of an Algorithm.................................................................... 42
3.4 Basics of an Algorithm................................................................................................ 43
3.4.1 Advantages of Using an Algorithm............................................................. 44
3.4.2 Example: Write an Algorithm to Add Two Numbers and
Produce the Sum............................................................................................. 44
3.4.3 Algorithm 3.1................................................................................................... 45
3.5 Flowcharts..................................................................................................................... 45
3.5.1 Advantages of Using a Flowchart................................................................ 45
3.5.2 Flowchart Symbols......................................................................................... 46
3.5.3 Flowchart Drawing Guidelines.................................................................... 46
3.6 Example Problems....................................................................................................... 48
3.7 Basics of a Programming Language.......................................................................... 53
3.7.1 Low-level Languages..................................................................................... 53
3.7.1.1 Machine-level Languages.............................................................. 54
3.7.1.2 Assembly-level Languages............................................................ 54
3.7.2 High-level Languages.................................................................................... 55
3.7.2.1 Compiler vs. Interpreter................................................................. 57
3.7.2.2 Advantages...................................................................................... 57
Contents ix

3.8 Review Questions........................................................................................................ 57


3.8.1 Objective Type Questions.............................................................................. 57
3.8.2 Practice Problems............................................................................................ 57
3.8.3 Subjective Questions......................................................................................58
Reference.................................................................................................................................. 59

4. Introduction to C Programming.......................................................................................... 61
4.1 Introduction.................................................................................................................. 61
4.2 History of C................................................................................................................... 62
4.3 Executing a C Program................................................................................................ 64
4.3.1 Editing.............................................................................................................. 64
4.3.2 Compiling........................................................................................................ 64
4.3.3 Linking............................................................................................................. 65
4.3.4 Executing.......................................................................................................... 65
4.4 Structure of a C Program............................................................................................ 65
4.4.1 Documentation................................................................................................ 65
4.4.2 Header Files..................................................................................................... 65
4.4.3 Global Variables.............................................................................................. 66
4.4.4 main() Function............................................................................................66
4.4.5 Subprograms................................................................................................... 67
4.4.6 Your First C Program...................................................................................... 67
4.5 Compilers and Editors for Executing C Programs.................................................. 69
4.5.1 Editors..............................................................................................................69
4.5.2 Compilers......................................................................................................... 69
4.5.3 Executing Your First C Program................................................................... 71
4.5.3.1 Mac.................................................................................................... 71
4.5.3.2 Windows........................................................................................... 72
4.5.3.3 Linux................................................................................................. 72
4.6 Review Questions........................................................................................................ 73
4.6.1 Objective Questions........................................................................................ 73
4.6.2 Short Answer Questions................................................................................ 73
4.6.3 Programming Questions................................................................................ 73
4.6.4 Long Questions............................................................................................... 75
References................................................................................................................................ 75

5. Constants, Variables, and Data Types................................................................................ 77


5.1 Introduction.................................................................................................................. 77
5.2 C Character Sets........................................................................................................... 77
5.3 Keywords...................................................................................................................... 78
5.4 Variables and Identifiers............................................................................................. 79
5.5 Data Types..................................................................................................................... 80
5.5.1 Primary Data Types........................................................................................ 81
5.5.2 Integer Data Types.......................................................................................... 81
5.5.3 Floating Point Types....................................................................................... 82
5.5.4 Character Data Types..................................................................................... 83
5.5.5 Void Types........................................................................................................ 83
5.6 Declaration of Variables.............................................................................................. 84
5.7 Constants....................................................................................................................... 86
5.7.1 Integer Constants............................................................................................ 86
x Contents

5.7.2 Real Constants................................................................................................. 87


5.7.3 Fractional Form............................................................................................... 87
5.7.4 Exponential Form...........................................................................................87
5.7.5 Character Constants....................................................................................... 87
5.7.6 String Constants.............................................................................................. 87
5.8 Learn to Code Examples............................................................................................. 88
5.9 Escape Sequences......................................................................................................... 91
5.10 Review Questions........................................................................................................ 92
5.10.1 Objective Questions........................................................................................ 92
5.10.2 Programming Questions................................................................................ 92
5.10.3 Subjective Questions......................................................................................94

6. Operators and Expressions.................................................................................................. 95


6.1 Introduction.................................................................................................................. 95
6.2 Arithmetic Operators................................................................................................... 96
6.3 Relational Operators.................................................................................................... 97
6.4 Assignment Operators................................................................................................ 98
6.5 Logical Operators......................................................................................................... 99
6.6 Increment and Decrement Operators...................................................................... 100
6.7 Conditional Operators............................................................................................... 103
6.7.1 Nested Conditional Operators.................................................................... 105
6.8 Bitwise Operators....................................................................................................... 105
6.8.1 Bitwise AND, OR, XOR................................................................................ 106
6.8.2 One’s Complement (~) Operator................................................................ 107
6.8.3 Two’s Complement Representation........................................................... 107
6.8.4 Left Shift Operator (≪) and Right Shift Operator (≫)............................ 109
6.9 Special Operators....................................................................................................... 112
6.9.1 The Comma Operator.................................................................................. 112
6.9.2 The sizeof Operator...................................................................................... 113
6.10 Expressions................................................................................................................. 113
6.10.1 Evaluation of Expressions........................................................................... 114
6.10.2 Rules for Evaluation of Expressions.......................................................... 114
6.11 Type Conversion........................................................................................................ 115
6.11.1 Implicit Type Casting................................................................................... 115
6.11.2 Explicit Type Conversion............................................................................. 116
6.12 Operator Precedence and Associativity.................................................................. 116
6.13 Review Questions...................................................................................................... 118
6.13.1 Objective Type Questions............................................................................ 118
6.13.2 Programming Questions.............................................................................. 119
6.13.3 Subjective Type Questions........................................................................... 120

7. Basic Input/Output.............................................................................................................. 123


7.1 Introduction................................................................................................................ 123
7.2 Unformatted Functions............................................................................................. 124
7.2.1 getchar() and putchar()..................................................................... 124
7.2.2 gets() and puts().................................................................................... 125
7.2.3 getch() and getche()............................................................................. 126
7.2.4 putch()......................................................................................................... 127
Contents xi

7.3 Formatted Functions.................................................................................................. 128


7.3.1 printf() Function.................................................................................... 128
7.3.2 Formatting with printf()........................................................................ 129
7.3.3 scanf() Function...................................................................................... 134
7.3.4 Formatting with scanf.................................................................................. 134
7.4 Review Questions...................................................................................................... 137
7.4.1 Short Answer Questions.............................................................................. 137
7.4.2 Programming Questions.............................................................................. 138
7.4.3 Subjective Questions....................................................................................139

8. Control Structures................................................................................................................ 141


8.1 Introduction................................................................................................................ 141
8.2 Selection with if Statements...................................................................................... 143
8.2.1 Some Points to Remember........................................................................... 145
8.3 if-else Statement......................................................................................................... 146
8.3.1 Write a Program to Check Whether a Number Entered by
the User is Zero or Nonzero........................................................................ 148
8.3.2 Write a Program to Calculate the Travel Fare of a Person...................... 149
8.4 Nested if-else Statements.......................................................................................... 150
8.4.1 Write a Program to Find the Biggest Among Three Numbers............... 151
8.5 if-else-if Ladders......................................................................................................... 151
8.5.1 Write a Program to Perform as a Four-Function Calculator................... 152
8.6 Compound Statements.............................................................................................. 154
8.7 Multiway Selection with Switch Statements.......................................................... 155
8.7.1 Some Points to Remember........................................................................... 157
8.8 goto Statement............................................................................................................ 159
8.8.1 Notes on goto................................................................................................159
8.9 Introduction to Loops................................................................................................ 160
8.10 while Loops................................................................................................................. 161
8.11 do-while Loops........................................................................................................... 164
8.11.1 Difference Between while and do-while Loops.......................................166
8.12 for Loops.....................................................................................................................167
8.12.1 Some Solved Problems (Printing Patterns)............................................... 171
8.13 Unconditional Branching: Break and Continue..................................................... 173
8.13.1 break Statements........................................................................................... 173
8.13.2 continue Statements.....................................................................................174
8.14 Review Questions...................................................................................................... 176
8.14.1 Short Questions............................................................................................. 176
8.14.2 Long Questions............................................................................................. 176

9. Functions............................................................................................................................... 179
9.1 Introduction................................................................................................................ 179
9.2 The Need for Functions............................................................................................. 181
9.3 Types of Function....................................................................................................... 182
9.4 User-defined Functions............................................................................................. 182
9.5 Components and Working of a Function............................................................... 186
9.5.1 Calling Function............................................................................................ 186
9.5.2 Called Function............................................................................................. 186
9.5.3 Function Prototype....................................................................................... 187
xii Contents

9.5.4 Function Definition....................................................................................... 187


9.5.5 Function Call................................................................................................. 188
9.5.6 Actual Arguments......................................................................................... 188
9.5.7 Formal Arguments........................................................................................ 188
9.5.8 Return Type................................................................................................... 188
9.6 Categories of a Function........................................................................................... 191
9.6.1 A Function Without Arguments and Without Return Types.................. 191
9.6.2 A Function Without Arguments and With Return Types....................... 191
9.6.3 A Function With Arguments and Without Return Types....................... 193
9.6.4 A Function With Arguments and With Return Types............................. 193
9.7 Recursion..................................................................................................................... 195
9.7.1 Example: Find the Value of xy..................................................................... 198
9.7.2 Programming Examples.............................................................................. 201
9.8 Storage Classes........................................................................................................... 204
9.8.1 Automatic Storage Class.............................................................................. 205
9.8.2 Register Storage Class.................................................................................. 206
9.8.3 Static Storage Class....................................................................................... 206
9.8.4 External Storage Class.................................................................................. 207
9.9 Review Question........................................................................................................ 209
9.9.1 Objective Questions...................................................................................... 209
9.9.2 Subjective Questions....................................................................................210
9.9.3 Programming Questions.............................................................................. 210

10. Arrays and Strings............................................................................................................... 213


10.1 Introduction................................................................................................................ 213
10.2 Need for Arrays.......................................................................................................... 214
10.3 Types of Arrays........................................................................................................... 214
10.4 1D Arrays.................................................................................................................... 215
10.4.1 Declaration of 1D Arrays............................................................................. 215
10.4.2 Initialization of Arrays................................................................................. 216
10.4.3 Accessing Array Elements........................................................................... 217
10.4.4 Characteristics of an Array.......................................................................... 218
10.4.5 Entering Data in an Array........................................................................... 219
10.4.6 Displaying the Content of an Array........................................................... 220
10.4.7 Programming Examples.............................................................................. 221
10.4.7.1 Write a Program to Create an Array of N Elements and
Write the Code to Find the Biggest Number and
the Smallest Number Present in the Array................................ 221
10.4.7.2 Write a Program to Search for an Element Present
in the Array, the Number of Times the Element is
Present, and Print the Element’s Positions................................ 222
10.4.7.3 Write a Program to Print the Binary Equivalent of
a Decimal Number Using an Array............................................ 223
10.4.8 Points to Note................................................................................................ 224
10.5 2D Arrays.................................................................................................................... 225
10.5.1 Introducing Matrices.................................................................................... 225
10.5.2 Declaration of a 2D Array............................................................................ 226
10.5.3 Representation of a 2D Array in Memory................................................. 226
10.5.3.1 Row Major Order.......................................................................... 227
Contents xiii

10.5.3.2 Column Major Order.................................................................... 227


10.5.4 Initialization of 2D Array............................................................................. 228
10.5.5 Accessing the Elements of a 2D Array....................................................... 229
10.5.6 Entering Data in a 2D Array........................................................................ 231
10.5.7 Exploration of a 2D Matrix.......................................................................... 234
10.5.8 Programming Examples.............................................................................. 235
10.5.8.1 Write a Program to Add All the Elements Present
in the Main Diagonal of a 2D Matrix.......................................... 235
10.5.8.2 Write a Program to Add the Elements of
Each Column and Print it in the Following Format................. 236
10.5.8.3 Write a Program to Add Two Matrices...................................... 238
10.5.8.4 Write a Program to Multiply Two Matrices............................... 240
10.6 Multidimensional Arrays.......................................................................................... 242
10.6.1 Declaration and Representation of 3D Arrays.......................................... 242
10.6.1.1 Write a Program to Declare a 3D Array,
Input Some Numbers, and Display the 3D Array.................... 244
10.7 Character Arrays: Strings.......................................................................................... 245
10.7.1 Declaration of a String.................................................................................. 245
10.7.2 Initialization of a String...............................................................................245
10.7.3 Reading a String............................................................................................ 246
10.7.3.1 Disadvantages of the scanf() Function................................. 246
10.7.3.2 Reading Strings with the gets() Function............................ 247
10.7.4 Displaying the String.................................................................................... 247
10.7.5 Programming Examples.............................................................................. 249
10.7.5.1 Find the Length of a String.......................................................... 249
10.7.5.2 Count the Number of Words Present in a String...................... 249
10.7.5.3 Reverse the String.........................................................................250
10.7.5.4 Check Whether the String is a Palindrome or Not................... 251
10.8 String Functions......................................................................................................... 252
10.8.1 strcpy (Destination, Source)........................................................................ 253
10.8.2 strcat (Destination, Source).......................................................................... 253
10.8.3 strcmp (First, Second)................................................................................... 253
10.8.4 Programming Examples Using String Functions..................................... 254
10.9 Review Questions...................................................................................................... 255
10.9.1 Objective Questions...................................................................................... 255
10.9.2 Subjective Questions....................................................................................255
10.9.3 Programming Exercises............................................................................... 256

11. Pointers.................................................................................................................................. 259


11.1 Introduction................................................................................................................ 259
11.2 Basic Knowledge........................................................................................................ 260
11.3 Pointer Variables........................................................................................................ 261
11.3.1 Declaration of Pointer Variables................................................................. 261
11.3.2 Working with Pointers................................................................................. 261
11.3.3 Workout.......................................................................................................... 263
11.4 Pointer to Pointer (Double Pointer)......................................................................... 265
11.5 Void Pointers............................................................................................................... 266
11.6 Null Pointers............................................................................................................... 268
11.6.1 What is the Meaning of NULL?.................................................................. 268
xiv Contents

11.7 Constant Pointers....................................................................................................... 268


11.7.1 Pointers to Constants.................................................................................... 272
11.8 Pointer Arithmetic...................................................................................................... 272
11.9 Pointers and Functions.............................................................................................. 276
11.9.1 Pass by Value................................................................................................. 276
11.9.2 Pass by Reference or Address..................................................................... 277
11.9.2.1 Problem: Write a Program to
Swap Two Numbers Using Functions........................................ 280
11.10 Pointers and Arrays................................................................................................... 282
11.11 Passing Arrays to Functions..................................................................................... 285
11.11.1 Write a Program to Pass an Array to a Function and Find the
Largest and Smallest Numbers Present in that Array............................. 290
11.12 Pointers and 2D Arrays............................................................................................. 291
11.13 Pointers and Strings................................................................................................... 293
11.13.1 Passing a String to a Function..................................................................... 294
11.13.2 Write a Program to Reverse a String Using a Function........................... 294
11.14 An Array of Pointers.................................................................................................. 295
11.15 Pointers to Functions................................................................................................. 297
11.16 Review Questions...................................................................................................... 300
11.16.1 Objective Questions...................................................................................... 300
11.16.2 Subjective Questions....................................................................................302
11.16.3 Programming Exercises............................................................................... 302

12. Structures and Unions........................................................................................................ 305


12.1 Introduction................................................................................................................ 305
12.2 Declaring a Structure................................................................................................. 307
12.2.1 Tagged Structure Declaration...................................................................... 307
12.2.2 Structure Declaration Using typedef......................................................... 308
12.2.3 Declaring Structure Variables...................................................................... 308
12.2.3.1 Declaring Structure Variables Using the Structure Name....... 308
12.2.3.2 Declaring Structure Variables after the Closing Braces........... 309
12.3 Initializing a Structure............................................................................................... 311
12.4 Accessing Structure Members.................................................................................. 312
12.4.1 Accessing Members Using the dot (.) Operator....................................... 313
12.5 Learn to Code Examples........................................................................................... 315
12.6 Arrays of Structures................................................................................................... 316
12.7 Structures within Structures (Nested Structures).................................................. 318
12.7.1 Declaration of Nested Structures................................................................ 318
12.7.1.1 Declare the Structure with One Declaration.............................319
12.7.1.2 Declare the Structure Separately................................................. 319
12.7.2 Accessing the Members of a Nested Structure......................................... 319
12.7.3 Nested Structure Initialization.................................................................... 320
12.8 User-defined Data Type: typedef............................................................................... 321
12.8.1 Uses of typedef.............................................................................................. 322
12.9 Pointers and Structures............................................................................................. 323
12.9.1 Accessing Structure Members Using a Pointer........................................ 323
12.9.2 A Pointer as a Member of a Structure........................................................ 324
12.9.3 Self-referential Structures............................................................................ 324
12.10 Structures and Functions.......................................................................................... 328
Contents xv

12.10.1 Passing Individual Members of a Structure.............................................. 328


12.10.2 Passing the Whole Structure Using the Pass by Value Concept............ 330
12.10.3 Passing the Whole Structure Using the Pass by Address Concept........ 332
12.11 Unions.......................................................................................................................... 333
12.11.1 Declaration of a Union................................................................................. 333
12.11.2 Member Accessing........................................................................................ 336
12.12 Structures vs. Unions................................................................................................. 336
12.12.1 Size of Unions and Structures..................................................................... 337
12.12.2 Sharing Memory and Member Accessing................................................. 337
12.13 Bitfields........................................................................................................................ 338
12.13.1 Declaration of a Bitfield............................................................................... 340
12.13.2 Uses of Bitfields............................................................................................. 342
12.14 Enumeration............................................................................................................... 343
12.15 Review Questions...................................................................................................... 346
12.15.1 Objective Questions...................................................................................... 346
12.15.2 Subjective Questions....................................................................................346
12.15.3 Programming Exercises............................................................................... 346

13. Dynamic Memory Allocation............................................................................................ 349


13.1 Introduction................................................................................................................ 349
13.1.1 Process of Memory Allocation.................................................................... 350
13.1.1.1 Text Segments................................................................................ 351
13.1.1.2 Data Segments............................................................................... 351
13.1.1.3 Stack Segments.............................................................................. 351
13.1.1.4 Heap Segments.............................................................................. 351
13.2 Types of Memory Allocation.................................................................................... 351
13.2.1 Static Memory Allocation............................................................................ 351
13.2.2 Dynamic Memory Allocation...................................................................... 351
13.3 Dynamic Memory Allocation Process..................................................................... 352
13.3.1 The malloc() Function.............................................................................. 353
13.3.2 The calloc() Function.............................................................................. 356
13.3.3 The realloc() Function........................................................................... 356
13.3.4 The free() Function..................................................................................360
13.4 Review Questions...................................................................................................... 361

14. File Handling........................................................................................................................ 365


14.1 Introduction................................................................................................................ 365
14.1.1 Difference between Console I/O and File I/O......................................... 366
14.2 Basics of File I/O........................................................................................................ 367
14.2.1 What is a File?................................................................................................ 367
14.2.2 File Handling Process Flow......................................................................... 367
14.3 Opening a File............................................................................................................. 368
14.4 Closing a File.............................................................................................................. 370
14.5 File Functions with Examples.................................................................................. 371
14.5.1 The fprintf() and fscanf() Functions.............................................. 371
14.5.1.1 Writing and Reading an Integer Using fprintf()
and fscanf()............................................................................... 372
14.5.2 The putw() and getw() Functions..........................................................374
xvi Contents

14.5.2.1 Writing and Reading More than One Integer


Using the putw() and getw() Functions................................ 374
14.5.2.2 Reading Numbers from a File and Checking
Them for Even or Odd.................................................................. 375
14.5.3 The fputc() and fgetc() Functions.....................................................377
14.5.3.1 Writing and Reading a Character Using fputc()
and fgetc()................................................................................. 378
14.5.3.2 Writing and Reading Multiple Characters Using
fputc() and fgetc()...............................................................379
14.5.3.3 Count Number of Characters, Lines, Tabs, and
Blank Spaces Present in a File...................................................... 380
14.5.4 The fputs() and fgets() Functions.....................................................381
14.5.4.1 Writing and Reading a String Using fputs() and
fgets().................................................................................................382
14.6 Other Programming Examples................................................................................ 383
14.7 Review Questions...................................................................................................... 386

15. The Preprocessor.................................................................................................................. 389


15.1 Introduction................................................................................................................ 389
15.2 Preprocessor Directives............................................................................................. 389
15.3 Macro-substitutions................................................................................................... 390
15.3.1 Writing Macros with Arguments................................................................ 392
15.3.2 Removing a Macro........................................................................................ 392
15.4 The #include Preprocessor........................................................................................ 392
15.5 Conditional Preprocessors........................................................................................ 395
15.5.1 The #ifdef and #endif Preprocessor Directives......................................... 395
15.5.2 The #ifndef and #endif Directives.............................................................. 396
15.5.3 The #if and #endif Directives...................................................................... 396
15.6 Other Preprocessor Directives.................................................................................. 396
15.6.1 #line Directives.............................................................................................. 397
15.6.2 #error Directives............................................................................................ 398
15.6.3 #pragma Directives....................................................................................... 400
15.7 Review Questions...................................................................................................... 400

16. Command Line Arguments................................................................................................ 403


16.1 Introduction................................................................................................................ 403
16.1.1 The Code::Block IDE..................................................................................... 404
16.2 Executing a Program Using a Command Prompt................................................. 405
16.2.1 Installing the minGW Compiler................................................................. 405
16.2.2 Compiling and Executing a Program........................................................ 407
16.3 Fundamentals of the Command Line Argument.................................................. 410
16.4 Using Command Line Arguments.......................................................................... 411
16.5 Review Questions...................................................................................................... 413

Appendix A:  ASCII Character Table........................................................................................ 415


Appendix B:  Integer Representation........................................................................................ 417
Index.............................................................................................................................................. 423
Preface

The C programming language is a general-­purpose language of great importance to stu-


dents, researchers, and software professionals. The TIOBE programming community index
is an indicator of the popularity of programming languages. C was at the top of the list in
March 2021. Experts believe that the C language serves as a preparatory step for individu-
als who aspires to learn other high-­level languages like Java and Python. Since its inven-
tion and standardization in 1989, it is most popular among embedded systems and
operating system developers. Several new standards of this language are currently in use
by developers and are known as C99 and C11. This book is written for those who have no
or only some basic prior knowledge about programming languages.

xvii
Acknowledgments

The idea of writing a book on C programming is quite an old thought of mine. I have been
writing the draft while teaching this subject. Having made some handouts for my stu-
dents, which they appreciated, I was motivated to write a book. I want to thank my stu-
dents for continuously suggesting that I write it. Some other people also motivated me and
supported me in completing it.
A heartful thanks to my wife, Priya Arundhati, and my son, Kritansh, for their encour-
agement, care, and love. Without them, my life would not be joyful. My parents and my
family members are my strength and excellent motivators for me, always.
A sincere thanks to Aastha Sharma, Senior Editor, CRC Press – Taylor & Francis Group,
for understanding my thoughts when writing this book and suggesting to me the neces-
sary additions for the final proposal. I am also grateful to Shikha Garg, Senior Editorial
Assistant, CRC Press – Taylor & Francis Group, who helped me produce the final manu-
script. I am also thankful to all editorial members who assisted me during the production
process of this book.
Finally, I would sincerely like to thank my friends and colleagues who directly or indi-
rectly support me in doing this work.

xix
Organization of this Book

To learn any programming language, we require a basic knowledge of computer funda-


mentals and number systems – covered in Chapters 1 and 2. Overall, the book contains 16
chapters organized so that an individual (beginner, intermediate programmer, or expert)
will gain maximum benefit if they follow it sequentially.
As mentioned, Chapter 1 provides a brief overview of a computer system's fundamental
components: input, output, memory, and processing devices. It also introduces the overall
functions of an operating system that a programmer should know. Chapter 2 describes
number systems, their types, and their conversion. Anyone knowing computer fundamen-
tals and number systems can skip these first two chapters. A programmer should know
how to find a solution to a given problem. Two primary components involved in solving a
problem are algorithms and flowcharts. A detailed description of these is provided in
Chapter 3. Chapter 4 introduces the C language, starting with its history and standards
(e.g., C89, C99, C11). A detailed description of a C program structure and how to execute it
in different environments is explained in this chapter.
Chapter 5 introduces language tokens such as constants, variables, and data types. The
C language has a rich set of operators which are described in Chapter 6. The chapter also
explains expressions and how to execute them according to the operator’s precedence and
associativity. Chapter 7 introduces input/output functions that a programmer uses to read
inputs from the user and produces output on the screen. Chapter 8 describes control state-
ments that include all decision-­making and looping constructs. The concept of modular
programming through functions is introduced in Chapter 9. The power of a function allows
a programmer to divide a more significant problem into smaller subtasks and execute
them by calling them when necessary. In Chapter 10, arrays and strings are explored to
provide insight into storing and sequentially retrieving information. Chapter 11 explores
pointers. The pointer concept is a vital part of the language and provides a mechanism to
access memory content dynamically. It also enhances the language’s features to support
data structure. Chapter 12 discusses several concepts such as structure, union, bit fields,
and enumerations. All these concepts are unique to the C language and enhance its char-
acteristics. Chapter 13 addresses the dynamic memory allocation concept used to allocate
memory dynamically and optimize memory allocation. Permanently storing information
on a file and manipulating its content is a required feature for any programming language.
Hence, in Chapter 14, we explore the concept of file handling in C. Other miscellaneous
concepts such as the preprocessor and command-­line arguments are described in Chapters
15 and 16.
This book includes more than 270 illustrations to explain the features of the C language.
Every chapter begins with a discussion of a real-­life scenario to explain the importance of
that chapter, before describing the mechanisms supported by C to tackle that issue. All the
fundamental concepts of C are covered with pleasing and feature-­rich examples.
Suggestions to improve the content are always welcome. We request all our readers to
send their findings, errors, comments, views, and feedback to make it a better book in this
field. Please send your suggestions to: [email protected].

xxi
Author Biography

Sisir Kumar Jena is presently working as an assistant professor in the Department of CSE,
DIT University, Dehradun. He was the HOD and an assistant professor in the Department
of CSE at Nalanda Institute of Technology, Bhubaneswar, India, during 2007–15. He has
more than ten years of teaching experience and five years of experience as a research
scholar at IIT Guwahati. He has been pursuing his Ph.D. in Computer Science and
Engineering at IIT, Guwahati, while writing this book. He has presented and published
many research papers and book chapters at refereed international conferences and in jour-
nals. His interest area includes digital VLSI design and testing, approximate computing,
IoT, and security in hardware.

xxiii
1
Introduction to the Computer

1.1 Introduction
Perhaps the most powerful and resourceful tool ever created by humanity is the computer.
The term “computer” could mean a device that calculates. But nowadays a computer can
do a variety of jobs. If you take any field, be it engineering, healthcare, automotive devices,
gaming, or entertainment, everywhere a computer is used to do the task. This chapter
introduces how computers came into existence and describes the different components
associated with a computing device. After completion of this chapter, the reader will have
learnt the following:

1. What a computer is, and how may we define it.


2. A brief history of the computer and how it came into existence.
3. What the different components of a computer system are, and how they are
organized.
4. Be able to define a memory subsystem, its categories, and its organization.
5. Understand the importance of an Operating System (OS) and its functionality.

This chapter’s content is purely elementary and not meant for those who know the basics
of computer systems. Those with a moderate knowledge of any computer language can
skip this chapter. We will start the chapter by introducing the definition of a computer
system and its characteristics.

1.2 Definition and Characteristics of a Computer System


The development of a computer system has a long history, which includes the work done
by several great minds. In this modern era, we can consider a computer as a system that
processes data and produces useful information. Though there is no formal definition that
defines a computer, we will try to propose a definition:

A computer is an electronic device that receives input through an input device, stores
it in the storage device (memory), and manipulates or processes the data to produce
information (output) through an output device.

DOI: 10.1201/9781003188254-1 1
2 C Programming

Speed

Memory Accuracy

Automac
Versality

Diligence

FIGURE 1.1
Characteristics of a computer.

Analyzing the definition, you may notice four crucial components of a computer sys-
tem: (1) input device, (2) output device, (3) storage device, and (4) the processing device.
The overall organization of all these components is discussed later in this chapter. The
above defines a computer system as a data processing machine. But it is not only a data
processing unit. Rather, it has several capabilities that need to be discussed here in the form
of its characteristics. We could not complete the definition without knowing the character-
istics of a computer system. Figure 1.1 shows the essential characteristics of a computer
system collected from [1].

• Speed: A computer is a high-speed electronic device which takes a negligible amount


of time to perform any task compared to the speed of any human being.
• Accuracy: Computers are very accurate in producing the correct output. A computer
produces the wrong result only when the user has made a mistake.
• Automatic: Computers execute the task assigned to them without any intervention
until the job gets finished.
• Diligence: Computers never tire. They can work continuously and produce correct
and consistent results every time.
• Versatility: A computer is capable of doing different tasks. We all know that nowadays
computers are used everywhere.
• Memory: A computer is potent at remembering things and never forgets them.
Whatever we store in computer memory will be there throughout its lifetime.

1.3 History of the Computer


The computer has a long history of development. The objective of this book is something
different. So in this section, we only provide an overview of how the computer came into
existence by highlighting some inventions. The origin of the entire development is not
Introduction to the Computer 3

(a) (b)

FIGURE 1.2
(a) Charles Babbage; (b) John von Neumann.

essential to us, but I would like to start with Charles Babbage’s (see Figure 1.2a) contribu-
tion. He is known as the father of the digital programmable computer.
The work of Babbage describing a “difference engine” was used by many researchers
as inspiration for further development [2], leading to several working models but with
the disadvantage that the programs were hardwired and challenging to change. A final
and major contribution was made during the 1940s by John von Neumann (see Figure
1.2b), known as the “stored program.” With a stored program, we can control a com-
puter system’s activity, and this program is usually stored inside the computer’s mem-
ory [2]. In today’s modern world, digital computers are all built based on this
stored-program concept. A brief contribution to computer development in chronologi-
cal order is [3]:

• The German philosopher and mathematician, Gottfried Leibniz (1646–1716), built the
first calculator to perform multiplication and division. It was not reliable due to the
inaccuracy of its parts.
• Charles Babbage (1792–1872) (Figure 1.1a) was a British inventor who designed his
difference engine in 1822 and, in 1842, came up with an “analytical engine” incorpo-
rating the ideas of a memory and card input/output for data and instructions. But he
was not able to build the system. Babbage is mostly remembered for and considered
as the father of digital computers.
• Howard Aiken (1900–73), a Harvard professor with IBM’s backing, built the Harvard
Mark I computer (51 ft long) in 1944. It required three seconds to perform
multiplication.
• John Vincent Atanasoff built a specialized computer in 1941 and was visited by
Willaim Mauchly before constructing the Electronic Numerical Integrator and
Calculator (ENIAC).
4 C Programming

• J. Presper Eckert and Mauchly designed and built the ENIAC in 1946 for military
computations. It used vacuum tubes (valves), which were totally electronic (and
operated in microseconds), instead of the electromechanical relay.
• Von Neumann was a scientific genius and a consultant on the ENIAC project. In 1950,
he formulated plans with Mauchly and Eckert for a new computer, the Electronic
Discrete Variable Automatic Computer (EDVAC), which was to store programs as
well as data.
• At the same time (1950), another computer named the Electronic Delay Storage
Automatic Calculator (EDSAC) was developed by Maurice Wilkes at Cambridge
University in England.
• After the above inventions, every computer built followed the von Neumann archi-
tecture. Several generations of computers have been developed, but the overall archi-
tecture remains the same.

The reader of this book is encouraged to find out more on computer generations and pres-
ent computer system scenarios.

1.4 Basic Computer Organization


Before we can understand basic computer organization, see Figure 1.3 of a desktop com-
puter system and its components. There are five components that we usually see: (1) the
keyboard; (2) the mouse (3); the monitor; (4) the cabinet; (5) the speaker. We also see some
other components, such as the Uninterrupted Power Supply (UPS) and the joystick. Every
component is not essential, but we connect them for ease of use.
Let us look inside the cabinet. Figure 1.4 shows what we can find inside, and we unveil
only those components that help us to explain the basic organization of a computer system:

• A Central Processing Unit (CPU);


• Two types of memory (primary and secondary);
• A Switched-Mode Power Supply (SMPS);
• A motherboard that provides ports for connecting all other components.

Cabinet
Monitor

Speaker Speaker

Keyboard
Mouse

FIGURE 1.3
A desktop computer system.
Introduction to the Computer 5

Hard Disk
AC 230V SMPS Drive

CPU Chip External Ports


PCI Slots
and Connectors

CPU
Heat Sink

M O T H E R B O A R D

Jumpers Memory Slots

Primary Baery
Memory

FIGURE 1.4
Major components inside the cabinet.

Readers are encouraged to explore more about these components and write an essay that
will enhance their knowledge of a computer system.
According to [4], a simple digital computer should have five essential parts: (1) mem-
ory, (2) Arithmetic Logic Unit (ALU), (3) Control Unit (CU), (4) input devices, and (5)
output devices. Among these components, the ALU and CU belong to the CPU. The CU
of the CPU plays a significant role in executing the user’s task. The CU controls the overall
activity of the computer system and manages communication among the other compo-
nents. To understand the overall execution of a task, look at Figure 1.5, which shows the
basic organization of these components. The description of each component is given
below.

1.4.1 Input Devices
This unit helps in supplying data and instruction to the computer system. For example, if
we wish to instruct the computer to play a song, then we search for a particular song and
click the play button using the mouse. In this scenario, the mouse acts as the input unit.
Similarly, if we wish to write a computer program, we use the keyboard as our input
device. There are several input devices connected to our computer through which we give
commands: mouse, keyboard, joysticks, and others.

An input device reads data or instructions from the user and sends it to the computer
system for further processing.
6 C Programming

CPU
Keyboard Mouse

Microphone Speakers Printer


Joysck
ALU
User Touch Input User Display Device

Input Output
Control Unit
Devices Devices

Primary
Memory

Secondary
Memory

Memory
FIGURE 1.5
Basic organization of a computer system.

1.4.2 Memory
Every computer has a memory unit primarily categorized into two types: primary memory
and secondary memory. We will further discuss the classification and description of these
memory units in Section 1.5. The primary job of this unit is to store everything, and that
includes the data or instructions read by the input unit, the intermediate result produced
by the processor, and the final result.

Memory is used to store input data or instructions, intermediate results yielded dur-
ing processing, and the final result produced by the processor.

1.4.3 Central Processing Unit


The CPU is called the brain of the computer system. It has two main components: the ALU
and the CU. It reads the data from the storage unit, performs calculations as per the user
instructions, stores the final result in the storage device, and displays the result to the user.
The ALU is used to execute all the logical and arithmetic operations. The CU is used to
control the overall activity of the computer system and manage the interaction among the
different components.
Introduction to the Computer 7

The CPU is called the brain of the computer system. It controls and coordinates the
interaction among different components and handles all the arithmetic and logical
operations.

1.4.4 Output Devices
These help in displaying the results of a computation. For example, when we execute a
program, the output is shown on the monitor screen. So, in this case, the monitor acts as
the output device. Similarly, a speaker is also an output device.

An output device obtains the result produced by the CPU, converts it into a human-
readable form, and displays it to the user of the computer system.

A programmer needs to understand how the instructions are executed inside the CPU.
This requires a detailed exploration of the memory unit. The following section introduces
the idea of memory-processor integration and its communication technique.

1.5 Computer Memory
A modern digital computer has several memory subsystems organized in a hierarchy,
starting from the smallest high-speed registers to a high-capacity hard disk drive. A com-
puter has the following main memory subsystems:

1. Registers;
2. Cache memory;
3. Primary memory;
4. Secondary memory.

Figure 1.6 shows how these memories are arranged with the CPU for easy communica-
tion and program execution. The main reason behind so many categories of memory
lies in the two requirements: speed and capacity. The CPU needs high-speed memory
because the execution speed of a CPU is relatively high compared to the data supplying
capability (reading the content from memory and submitting it to the CPU for process-
ing) of any memory. On the other hand, a user always needs a high-volume memory to
permanently keep all their data and programs. The capacity of the secondary memory
is relatively high compared to the main memory, cache, and registers. In contrast, fetch-
ing data from the register is faster compared to any other memory subsystem. It is evi-
dent that building high-speed memory incurs more cost as compared to low-speed
memory.
A programmer needs to understand memory organization to write efficient programs.
Let us describe a few points about each category of all memory types.
8 C Programming

Central Processing Unit Primary Memory

ALU

Control Unit
Secondary Memory
Program General Purpose
Counter Registers
R0
R1
Instrucon R2
Register
Rn

Cache Memory

FIGURE 1.6
Memory organization.

1.5.1 Registers
These are the smallest, high-speed, volatile memories available inside the CPU for easy
access while processing or executing a task. The total number of registers present inside a
CPU varies from architecture to architecture. The most common ones are general purpose
registers, program counters, and instruction registers. A general purpose register stores cur-
rent and intermediate data of an executed instruction. There may be several general pur-
pose registers available inside the CPU. A program counter keeps the information regarding
the instruction about to run next. It is like a counter and holds an address that keeps
increasing after the execution of the current instruction. The instruction register contains the
instruction that is currently executing. The CPU fetches the instruction from the primary
memory, places it inside the instruction register, decodes it, and finally executes it.

1.5.2 Cache Memory
Cache memory is a volatile memory present in between the main memory and the CPU
register. The speed of this memory is higher than main memory and slower than the CPU
registers. Every time the CPU requests the next instruction, the control unit first searches
for it inside the cache. If it is not there, then the control brings a set of instructions (along
with the required one) from the main memory and keep it inside the cache. The benefits of
bringing the whole group lie in the principle of locality of reference: the CPU always fetches
the instructions that are adjacent to each other, location wise.

1.5.3 Primary Memory
Primary memory, commonly referred to as the main memory, is a significant component of
any computing device. It is an intermediate memory between the secondary memory and
the CPU of the computer system. On request, the CPU needs to load an application in the
main memory for execution. When a programmer finishes writing a program, he or she
stores it in secondary memory. To execute that program, the CPU loads it from secondary
memory to the primary memory. The processor is now directly interacting with the main
memory and runs the program. At this point, it is necessary to understand the internal
architecture of the main memory subsystem.
Introduction to the Computer 9

TABLE 1.1
Units of Storage in Computer
Serial No. Units Description
1 bit Refers to either 0 or 1
2 1 Nibble 4 bits
3 1 Byte 8 bits
4 1 Kilobyte (KB) 1024 Bytes (210 Bytes)
5 1 Megabyte (MB) 1024 Kilobyte (210 KB)
6 1 Gigabyte (GB) 1024 Megabyte (210 MB)
7 1 Terabyte (TB) 1024 Gigabyte (210 GB)
8 1 Petabyte (PB) 1024 Terabyte (210 TB)
9 1 Exabyte (EB) 1024 Petabyte (210 PB)
10 1 Zettabyte (ZB) 1024 Exabyte (210 EB)

The main memory consists of several locations, and we can identify each location with
an address. A location holds data or an instruction in the form of binary bits. A bit is the
smallest unit of storage, refers to either 0 or 1, though it is not much use as a single unit. To
be useful, a collection of bits is required: a group of four bits forms a nibble, a group of eight
bits forms a byte; Table 1.1 shows the other units made from collections of bits.
Data stored in memory is in the form of a word, and the word size (word length) depends
on the computer architecture. A modern computer system can have 16-bit (2-byte word),
32-bit (4-byte word), or 64-bit (8-byte word) word sizes. An example of a simple main
memory is shown in Figure 1.7. The word length is 2 bytes, and there are 64 locations. Hence
to identify each location uniquely, we need 6 bits (26 = 64) starting from the address 000000
to 111111.
Two types of primary memory exist in a computer system: Random Access Memory
(RAM) and Read Only Memory (ROM). ROM has several variations: Programmable ROM
(PROM), Erasable Programmable ROM (EPROM), Electrically Erasable Programmable

Address 2-byte
Word Length
000000 1st Word
000001 2nd Word
000010
000011
000100

111111 64th Word

FIGURE 1.7
An example of a main memory subsystem.
10 C Programming

ROM (EEPROM), and so on; and the description of each type is not included in the scope
of this book. Similarly, RAM is also of two types: static RAM and dynamic RAM.

1.5.4 Random Access Memory


RAM is also known as the main memory of a computer system. In RAM, we can retrieve
and store information randomly from any location:

1. RAM is the read–write memory of the computer;


2. RAM is volatile memory: the content of the RAM is erased when we switch off the
computer system;
3. In RAM, it is possible to select any memory location randomly to store and retrieve
information.

1.5.5 Read Only Memory


The information present in this memory is permanent, and we cannot modify the content.
Hence it is a read only memory:

1. Information can be read only.


2. It is a non-volatile memory: the data present in this memory are permanent.
3. Such memories are also called permanent stores or dead stores.
4. It is generally used to store bootable information.
5. Generally, the computer manufacturer provides a ROM chip.

1.5.6 Secondary Memory
Before executing a program, you should write it and store it somewhere inside your com-
puter memory. Primary memory will not store your program permanently; it can help
your CPU execute the program by providing memory space. When your program finishes
running, the allocated memory will be taken back – that’s why you need permanent stor-
age to store your programs. Secondary memory does that job for you.
There are two types of secondary memory in today’s computers: a Hard Disk Drive
(HDD) and a Solid-State Drive (SSD). SSDs are much faster compared to HDDs. SDDs have
no mechanical moving parts, but HDDs have built-in platters called magnetic disks and a
movable head that travels back and forth between the disks to access the data. On the other
hand, SSDs are quite expensive compared to HDDs and have limited storage capacity.

1.5.7 Hard Disk Drive


Figure 1.8 shows the internal architecture of the currently available HDDs. As you can see,
an HDD has a mechanical moving read–write head that moves back and forth through the
platters. The figure shows the organization of the read–write head and its direction of
movement. The platters are coated with a thin magnetic material and are used to record
data. Each platter is divided into several tracks and sectors to store data, as shown in
Figure 1.8. While accessing the data recorded on each platter’s surface, read–write heads
move forward and backward, and, the platters rotate to bring the desired sector under the
read–write head.
Introduction to the Computer 11

Direcon of Movement

Spindle Pla er
Pla ers Track
Pla er
Read–Write Head
Pla er
Read–Write
Head Sector
Spindle

(a) (b) (c)

FIGURE 1.8
Internal architecture of an HDD.

1.5.8 Solid State Drive


Figure 1.9 shows a typical SSD and its block diagram [5–7]. An SSD uses solid-state memo-
ries to store data. The main component of an SSD is the NAND flash memory, a controller,
a RAM, and a host interface. Figure 19.9b shows the organization of these components and
their communication path. The NAND flash memory, sometimes called flash memory, is a
non-volatile semiconductor device used to store data. There are several so-called flash
blocks, consisting of 64 to 128 pages, to record user data. These pages are further subdi-
vided into subpages, which is equal to the typical size of a sector. Each subpage also has
two areas: a data area and a spare area. The data area stores the user’s data, and the spare
area stores management information, such as bad sectors and error correction codes. Flash
memories are arranged in the form of a package sharing an eight-bit-wide common input/
output (I/O) bus. The host interface provides the connection to the host through interfaces
such as a serial advanced technology attachment (SATA), a parallel advanced technology
attachment (PATA), or a universal serial bus (USB). The SSD controller handles the read/
write request coming from the user with the help of a RAM – as a temporary buffer. The
RAM buffers the data through a read/write request before actually reading/writing from/
to the flash memory.

NAND NAND
NAND flash Memories RAM Flash Flash
Cache Memories Memories

Host SSD
Interface Controller

NAND NAND
Flash Flash
Memories Memories
Controller

(a) (b)

FIGURE 1.9
(a) A typical SSD; (b) Block diagram of an SSD.
12 C Programming

1.6 Introduction to the Operating System


1.6.1 Hardware and Software
Before I introduce what an operating system is, I would like to discuss the concept of soft-
ware (s/w) and hardware (h/w). The h/w is a physical device connected to your com-
puter. S/w is a collection of programs, and we install them on a computer system to instruct
the h/w to do something. That means, to interact with the h/w, we need the help of s/w.
Buying a computer from the market and connecting it to a power supply does not help you
interact with the computer. The only way you can instruct the computer to do anything is
to install s/w and give commands through it. Hence, the s/w will act as an interface
between the user and the computer system. Figure 1.10 shows the user and h/w interac-
tion through s/w. The figure shows a three-layer communication: the h/w layer, s/w layer,
and user layer. The user layer provides instruction to the s/w layer, which in turn instructs
the h/w to execute the instruction.
S/w is mainly of two types: application s/w and system s/w (Figure 1.10). Application
s/w is built for a specific task or specific application. For instance, Microsoft word, VLC
media player, or any browser s/w like Google chrome is application s/w. On the other
hand, the system s/w allows access to the h/w. It acts as the interface between the user and
the h/w as well as application s/w and h/w. The relationship can be seen in Figure 1.11.

1.6.2 Operating System
An Operating System (OS) is system s/w that handles all the instructions coming from the
user or application s/w and instructs the h/w to perform accordingly (Figure 1.11). Several
OSs are available on the market, like Microsoft Windows 10, Ubuntu, Linux, Unix, and
iOS. After buying a new computer, the first task is to install an OS on it; only then will the
computer be usable. Later, we can install application s/w above the OS to do other specific
tasks. If we want to listen to music, we can install s/w like Windows Media Player or VLC
media player. Similarly, for word processing, we can install Microsoft Word or LibreOffice.
Figure 1.12 shows the position of an OS in a layering architecture.

Hardware Layer Soware Layer User

Cabinet Soware
Monitor

1.
Speaker Speaker Applicaon
Soware

2.
System
Soware
Keyboard
Mouse

FIGURE 1.10
Hardware interaction through software.
Introduction to the Computer 13

Cabinet
Monitor
Applicaon
Soware

System
Speaker Soware

Keyboard
Mouse

FIGURE 1.11
System software providing access to hardware.

User

Applicaon
A Soware

Microso
Operang System Window

Cabinet
Monitor

Speaker Speaker
COMPUTER
HARDWARE
Keyboard Mouse Printer Modem

FIGURE 1.12
Operating System layer.

1.6.3 Functions of an Operating System


An OS manages several resources and handles all the requests that are coming from users
and the application s/w. The broad classification of the OS functions includes:

1. Resource management;
2. Memory management;
3. Process management;
4. File management.

A detailed description of these functions is beyond the scope of this book. Readers are
encouraged to explore more about these functions in any standard OS book.
14 C Programming

1.7 Review Questions
1.7.1 Long Answers

1. What is a computer system, and what are its characteristics?


2. What are the basic components of a computer system? Explain its organization with a
proper diagram.
3. What is a central processing unit (CPU)? Explain all the components of a CPU with an
appropriate diagram.
4. What is computer memory? Explain the categories of several memory subsystems and
their organization found in a computer system.
5. What are CPU registers? Explain the standard registers found inside a CPU irrespec-
tive of any architecture.
6. What is cache memory? Explain the need for cache memory and how it works.
7. Elaborate the working principle of cache memory to reduce the speed mismatch
between the main memory and the CPU.
8. Explain the categories of the memory subsystem and state the difference between pri-
mary memory and secondary memory.
9. Draw the block diagram of the main memory subsystem and explain the detail of
address space and word size.
10. What is the difference between RAM and ROM?
11. Explain the internal architecture of a hard disk drive (HDD) with its working
principle.
12. Explain the internal architecture of a solid-state drive (SSD) with its working
principle.
13. What are hardware and software? Explain the difference between them.
14. How does a user access/instruct hardware to execute an instruction? Explain the
hardware–software communication required to accomplish a task.
15. What is the difference between application software and system software? Explain
using an appropriate example.
16. What is an operating system (OS)? Explain the layered architecture of a system show-
ing the OS layer.
17. Explain the various functions of an operating system.
18. Explore your computer and list all the application software and system software
installed in your system.
19. Explore 32-bit and 64-bit operating systems. Which OS is installed in your computer
system and why?
20. Explain the booting process of a computer system.

1.7.2 Short Answers

1. Who is known as the father of computer systems and why?


2. Who introduced the concept of the “stored program”? Explain it.
Introduction to the Computer 15

3. What is the full form of ENIAC, EDSAC, and EDVAC? Which one was developed
first?
4. What are SMPS and UPS? Why are they necessary?
5. What is a control unit, where is it present, and what does it do?
6. What is the role of an ALU, and what operations does it perform?
7. Give some examples of input devices and output devices.
8. What is the meaning of locality-of-reference?
9. Explain the memory hierarchy, with respect to size, cost, and speed, of several mem-
ory subsystems.
10. What is a bit? How many bits form one byte?
11. List out the different variations of read only memory (ROM).
12. What is the difference between volatile and non-volatile memory?
13. What is NAND-flash memory, and where is it used?
14. What is word size or word length?
15. What is a program counter?
16. What is an instruction register?
17. What is a general purpose register?
18. What is the full form of SATA and PATA? What is the difference between them?
19. What is a bootstrap loader program?
20. What is the typical rotational speed of a hard drive in a modern computer system?

1.7.3 Practical Exercises

1. What should you know before purchasing a computer (whether a desktop or a laptop)
from the market?
2. Do you think a bigger RAM capacity increases the speed of your computer system?
Explore and explain.
3. What are x64 and x86 based operating systems? What is the difference between both
of them? Try to find out which type of operating system is installed on your
computer.
4. Explore your system and try to find out the following information about your
computer:
a. What is the RAM size?
b. Which OS are you using?
c. What is the size of your secondary memory?
d. Is the secondary memory connected to your computer an HDD or SSD?
e. How can you find out how many processes are running on your system at any
instant of time?
f. What is the speed of your processor?
g. How many cores does your processor have?
h. What is the size of your CPU register?
5. Study different operating systems, their types, and consider which one is best, and
why.
16 C Programming

6. Three major players in operating system design are Microsoft Windows, Linux, and
Apple ios. Prepare a report on these OSs and learn how they are different from each
other.
7. What is a pen drive? To which category of memory system, primary or secondary,
does it belong?
8. Explore several keyboard shortcuts for your computer, create a new file, save a file,
minimize the opened windows, toggle through windows, and other shortcuts that
ease your operating capability.
9. When you shut down your computer, three options are shown in a Windows machine:
shut down, restart, and sleep. What is the use of sleep?
10. Go to your computer settings and explore the detail of several components, such as
system, personalize, account, and network & Internet.

References
1. Sinha, Pradeep K., and Priti Sinha. Computer Fundamentals. BPB Publications, 2010.
2. Randell, Brian, ed. The Origins of Digital Computers: Selected Papers. Springer, 2013.
3. Forouzan, Behrouz A., and Firouz Mosharraf. Foundations of Computer Science. Thomson, 2008.
4. Van Der Poel, W.L. A Simple Electronic Digital Computer. Appl. Sci. Res. 2, 367–400 (1952).
5. Kim, J., S. Seo, D. Jung, J. Kim, and J. Huh, “Parameter-Aware I/O Management for Solid State
Disks (SSDs),” IEEE Trans. Comp., vol. 61, no. 5, pp. 636–649, May 2012, doi: 10.1109/TC.2011.76.
6. Chen, F., R. Lee, and X. Zhang, “Essential Roles of Exploiting Internal Parallelism of Flash
Memory Based Solid State Drives in High-speed Data Processing,” 2011 IEEE 17th International
Symposium on High Performance Computer Architecture, San Antonio, TX, 2011, pp. 266–277, doi:
10.1109/HPCA.2011.5749735.
7. Hu, Y., H. Jiang, D. Feng, L. Tian, H. Luo, and C. Ren, “Exploring and Exploiting the Multilevel
Parallelism Inside SSDs for Improved Performance and Endurance,” IEEE Trans. Comp., vol. 62,
no. 6, pp. 1141–1155, June 2013, doi: 10.1109/TC.2012.60.
Introduction to the Computer
Sinha, Pradeep K. , and Priti Sinha . Computer Fundamentals. BPB Publications, 2010.
Randell, Brian , ed. The Origins of Digital Computers: Selected Papers. Springer, 2013.
Forouzan, Behrouz A. , and Firouz Mosharraf . Foundations of Computer Science. Thomson, 2008.
Van Der Poel, W.L. A Simple Electronic Digital Computer. Appl. Sci. Res. 2, 367–400 (1952).
Kim, J. , S. Seo , D. Jung , J. Kim , and J. Huh , “Parameter-Aware I/O Management for Solid State Disks
(SSDs),” IEEE Trans. Comp., vol. 61, no. 5, pp. 636–649, May 2012, doi: 10.1109/TC.2011.76.
Chen, F. , R. Lee , and X. Zhang , “Essential Roles of Exploiting Internal Parallelism of Flash Memory Based
Solid State Drives in High-speed Data Processing,” 2011 IEEE 17th International Symposium on High
Performance Computer Architecture, San Antonio, TX, 2011, pp. 266–277, doi: 10.1109/HPCA.2011.5749735.
Hu, Y. , H. Jiang , D. Feng , L. Tian , H. Luo , and C. Ren , “Exploring and Exploiting the Multilevel Parallelism
Inside SSDs for Improved Performance and Endurance,” IEEE Trans. Comp., vol. 62, no. 6, pp. 1141–1155,
June 2013, doi: 10.1109/TC.2012.60.

Problem Solving through Flowcharts and Algorithms


Schneider, G. Michael , and Judith Gersting . Invitation to computer science. Cengage Learning, 2018.

Introduction to C Programming
Ritchie, Dennis M. , “The development of the C language,” ACM Sigplan Notices, vol. 28, no. 3, pp. 201–208,
1993.
Ritchie, Dennis M. , Brian W. Kernighan , and Michael E. Lesk , The C programming language. Prentice Hall,
1988.
Stroustrup, Bjarne , “Sibling Rivalry: C and C++,” (2002).
ISO, LA0 , “ISO/IEC 9899: 2018-information technology–programming languages–C,” (2018).
ISO, ISO , “ISO/IEC 9899: 2011 Information technology—Programming languages— C,” (2011).
Organisation, I. S. , “ISO/IEC 9899: 1999 Programming Languages-C,” (1999).
https://code.visualstudio.com/learn

You might also like