introduction to c programming - jnujprdistance.comjnujprdistance.com/assets/lms/lms...

120
Introduction to C Programming

Upload: others

Post on 15-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

Page 2: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

This book is a part of the course by Jaipur National University, Jaipur.This book contains the course content for Introduction to C Programming.

JNU, JaipurFirst Edition 2013

The content in the book is copyright of JNU. All rights reserved.No part of the content may in any form or by any electronic, mechanical, photocopying, recording, or any other means be reproduced, stored in a retrieval system or be broadcast or transmitted without the prior permission of the publisher.

JNU makes reasonable endeavours to ensure content is current and accurate. JNU reserves the right to alter the content whenever the need arises, and to vary it at any time without prior notice.

Page 3: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

I/JNU OLE

Index

ContentI. ...................................................................... II

List of FiguresII. ..........................................................VI

List of TablesIII. ......................................................... VII

ApplicationIV. ............................................................. 99

BibliographyV. .......................................................... 106

Self Assessment VI. Answers ..................................... 109

Book at a Glance

Page 4: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

II/JNU OLE

Contents

Chapter I ....................................................................................................................................................... 1‘C’ Fundamentals ......................................................................................................................................... 1Aim ................................................................................................................................................................ 1Objectives ...................................................................................................................................................... 1Learning outcome .......................................................................................................................................... 11.1 Introduction .............................................................................................................................................. 2 1.1.1 Operating system ..................................................................................................................... 2 1.1.2 Application software ................................................................................................................ 2 1.1.3 Programming languages .......................................................................................................... 2 1.1.4 Advanced development tools ................................................................................................... 2 1.1.5 Web based tools ....................................................................................................................... 21.2 Introduction to ‘C’ .................................................................................................................................... 2 1.2.1 Low Level Languages .............................................................................................................. 3 1.2.2 High Level Languages ............................................................................................................. 31.3 Identifier and Keywords .......................................................................................................................... 31.4 Data Types and Constants ........................................................................................................................ 4 1.4.1 Basic Data Types ...................................................................................................................... 4 1.4.2 Type Qualifiers ......................................................................................................................... 5 1.4.2.1 Short .......................................................................................................................... 5 1.4.2.2 Long .......................................................................................................................... 5 1.4.2.3 Unsigned ................................................................................................................... 5 1.4.2.4 Unsigned long ........................................................................................................... 51.5 Variables ................................................................................................................................................... 5 1.5.1 Variable Declaration................................................................................................................. 5 1.5.2 Variable Initialisation ............................................................................................................... 6 1.5.3 Declaring Variables as Constants ............................................................................................. 61.6 Operators and Expressions ....................................................................................................................... 6 1.6.1 Arithmetic Operators ................................................................................................................ 6 1.6.2 Rational Operators ................................................................................................................... 7 1.6.3 Logical Operators .................................................................................................................... 7 1.6.4 Comma Operator ...................................................................................................................... 8 1.6.5 Conditional Operators .............................................................................................................. 8 1.6.6 Bitwise Operators .................................................................................................................... 8 1.6.7 Assignment Operators .............................................................................................................. 9 1.6.8 Increment and Decrement Operators ....................................................................................... 91.7 Preprocessor Directives ........................................................................................................................... 9 1.7.1 Macro Expansion ................................................................................................................... 10 1.7.2 File Inclusion ..........................................................................................................................11Summary ..................................................................................................................................................... 12References ................................................................................................................................................... 12Recommended Reading ............................................................................................................................. 12Self Assessment ........................................................................................................................................... 13

Chapter II ................................................................................................................................................... 15Data Input and Output .............................................................................................................................. 15Aim .............................................................................................................................................................. 15Objectives .................................................................................................................................................... 15Learning outcome ........................................................................................................................................ 152.1 Introduction ............................................................................................................................................ 162.2 Getchar Functions .................................................................................................................................. 162.3 Putchar Function .................................................................................................................................... 162.4 Scanf( ) Function .................................................................................................................................... 172.5 Printf( ) Function .................................................................................................................................... 172.6 Gets ( ) and Puts ( ) Functions ............................................................................................................... 18

Page 5: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

III/JNU OLE

Summary ..................................................................................................................................................... 19References ................................................................................................................................................... 19Recommended Reading ............................................................................................................................. 19Self Assessment ........................................................................................................................................... 20

Chapter III .................................................................................................................................................. 22Control Statements .................................................................................................................................... 22Aim .............................................................................................................................................................. 22Objectives .................................................................................................................................................... 22Learning outcome ........................................................................................................................................ 223.1 Introduction ............................................................................................................................................ 233.2 Loops...................................................................................................................................................... 23 3.2.1 For Loop Statement ............................................................................................................... 23 3.2.1.1 Execution of ‘For’ Statement .................................................................................. 23 3.2.2 While Loop ............................................................................................................................ 24 3.2.3 Do – While Statement ............................................................................................................ 253.3 The Break Statement .............................................................................................................................. 263.4 Continue Statement ................................................................................................................................ 263.5 ‘If’ Statement ......................................................................................................................................... 273.6 ‘If Else’ Statement .................................................................................................................................. 273.7 Switch Statement ................................................................................................................................... 273.8 ‘If Else If Ladder’ .................................................................................................................................. 283.9 Nested If ................................................................................................................................................. 283.10 Iteration Statement ............................................................................................................................... 293.11 Nested For ............................................................................................................................................ 293.12 Goto Statement ..................................................................................................................................... 29 3.12.1 Conditional Goto .................................................................................................................. 29 3.12.2 Unconditional Goto .............................................................................................................. 29Summary ..................................................................................................................................................... 30References ................................................................................................................................................... 30Recommended Reading ............................................................................................................................. 30Self Assessment ........................................................................................................................................... 31

Chapter IV .................................................................................................................................................. 33Arrays and Strings ..................................................................................................................................... 33Aim .............................................................................................................................................................. 33Objectives .................................................................................................................................................... 33Learning outcome ........................................................................................................................................ 334.1 Introduction ............................................................................................................................................ 344.2 Declaration of An Array ......................................................................................................................... 344.3 Initialisation of Array ............................................................................................................................. 34 4.3.1 Drawbacks of Initialising An Array ....................................................................................... 344.4 Dimensions of An Array ........................................................................................................................ 34 4.4.1 Single Dimensional Arrays .................................................................................................... 35 4.4.1.1 Declaration of Single Dimensional Arrays ............................................................. 35 4.4.1.2 Initialisation of One Dimensional Array ................................................................. 35 4.4.2 Two Dimensional Arrays ....................................................................................................... 35 4.4.2.1 Elements of Multidimensional Array ...................................................................... 36 4.4.2.2 Initialisation of Multidimensional Array ................................................................. 364.5 Strings .................................................................................................................................................... 36 4.5.1 String Functions ..................................................................................................................... 374.6 Passing Array to Functions .................................................................................................................... 38Summary ..................................................................................................................................................... 39References ................................................................................................................................................... 39Recommended Reading ............................................................................................................................. 39Self Assessment ........................................................................................................................................... 40

Page 6: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

IV/JNU OLE

Chapter V .................................................................................................................................................... 42Functions and Structures .......................................................................................................................... 42Aim .............................................................................................................................................................. 42Objectives .................................................................................................................................................... 42Learning outcome ........................................................................................................................................ 425.1 Introduction to Functions ....................................................................................................................... 435.2 Uses of Functions ................................................................................................................................... 435.3 Elements of User Defined Functions ..................................................................................................... 43 5.3.1 Function Declaration .............................................................................................................. 43 5.3.2 Function Call .......................................................................................................................... 45 5.3.2.1 Call by Value ........................................................................................................... 45 5.3.2.2 Call by Reference .................................................................................................... 45 5.3.3 Function Definition ................................................................................................................ 465.4 Scope and Lifetime of Variables ............................................................................................................ 46 5.4.1 Automatic Variables ............................................................................................................... 46 5.4.2 External Variables .................................................................................................................. 46 5.4.3 External Declaration .............................................................................................................. 46 5.4.4 Static Variables....................................................................................................................... 47 5.4.5 Register Variables .................................................................................................................. 475.5 Return Values ......................................................................................................................................... 475.6 Function Categories ............................................................................................................................... 47 5.6.1 Functions with No Arguments and No Return Values ........................................................... 47 5.6.2 Functions with Arguments and No Return Values ................................................................. 48 5.6.3 Functions with No Arguments and Return Values ................................................................. 48 5.6.4 Functions with Arguments and Returning Values .................................................................. 485.7 Recursion ............................................................................................................................................... 485.8 Introduction to Structure ........................................................................................................................ 48 5.8.1 Declaring of a Structure ......................................................................................................... 49 5.8.2 Accessing Structure Elements ................................................................................................ 49 5.8.3 Process of Storing Structure Elements ................................................................................... 505.9 Array of Structures ................................................................................................................................. 505.10 Additional Features of Structures ......................................................................................................... 515.11 Uses of Structures ................................................................................................................................ 525.12 Unions .................................................................................................................................................. 52Summary ..................................................................................................................................................... 53References ................................................................................................................................................... 53Recommended Reading ............................................................................................................................. 53Self Assessment ........................................................................................................................................... 54

Chapter VI .................................................................................................................................................. 56Pointers ....................................................................................................................................................... 56Aim .............................................................................................................................................................. 56Objectives .................................................................................................................................................... 56Learning outcome ........................................................................................................................................ 566.1 Introduction ............................................................................................................................................ 576.2 Pointer Declaration ................................................................................................................................ 576.3 Reference Operator ................................................................................................................................ 576.4 Dereference Operator ............................................................................................................................. 586.5 Pointer Arithmetic .................................................................................................................................. 58 6.5.1 Increment (++) ....................................................................................................................... 59 6.5.2 Decrement (--) ........................................................................................................................ 59 6.5.3 Addition (+) and Subtraction (-) ............................................................................................ 59 6.5.4 Differencing ........................................................................................................................... 596.6 Pointers with Function ........................................................................................................................... 59 6.6.1 Call by Value .......................................................................................................................... 60

Page 7: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

V/JNU OLE

6.6.2 Call by Reference ................................................................................................................... 60 6.6.3 Callback Functions ................................................................................................................ 606.7 Function Pointer Syntax ......................................................................................................................... 606.8 Initialising Function Pointer .................................................................................................................. 606.9 Using Function Pointer .......................................................................................................................... 616.10 Arrays and Pointer ................................................................................................................................ 616.11 Array of Pointers .................................................................................................................................. 626.12 Pointers with Structures ....................................................................................................................... 626.13 Pointers on Pointer ............................................................................................................................... 62Summary ..................................................................................................................................................... 64References ................................................................................................................................................... 64Recommended Reading ............................................................................................................................. 64Self Assessment ........................................................................................................................................... 65

Chapter VII ................................................................................................................................................ 67Dynamic Memory Allocation .................................................................................................................... 67Aim .............................................................................................................................................................. 67Objectives .................................................................................................................................................... 67Learning outcome ........................................................................................................................................ 677.1 Introduction ............................................................................................................................................ 687.2 Stack and Heap ...................................................................................................................................... 687.3 Sizeof ..................................................................................................................................................... 687.4 Malloc() .................................................................................................................................................. 70 7.4.1 Managing Strings with Malloc( ) ........................................................................................... 717.5 Freeing Memory ..................................................................................................................................... 72 7.5.1 Working with Memory Segments .......................................................................................... 727.6 Calloc() and Realloc() ............................................................................................................................ 737.7 Chapter Program-Math Quiz .................................................................................................................. 75Summary ..................................................................................................................................................... 78References ................................................................................................................................................... 78Recommended Reading ............................................................................................................................. 79Self Assessment ........................................................................................................................................... 80

Chapter VIII .............................................................................................................................................. 82File Input and Output ................................................................................................................................ 82Aim .............................................................................................................................................................. 82Objectives .................................................................................................................................................... 82Learning outcome ........................................................................................................................................ 828.1 Introduction ........................................................................................................................................... 838.2 Bits and Bytes ........................................................................................................................................ 838.3 Fields, Records and Files ....................................................................................................................... 838.4 File Streams ........................................................................................................................................... 84 8.4.1 Opening and Closing Files ..................................................................................................... 84 8.4.2 Reading Data .......................................................................................................................... 86 8.4.3 Writing Data ........................................................................................................................... 88 8.4.4 Appending Data ..................................................................................................................... 898.5 Goto andError Handling ........................................................................................................................ 91 8.5.1 A Brief History of Goto ......................................................................................................... 91 8.5.2 Usage of Goto ........................................................................................................................ 918.6 Chapter Program-The Phone Book Program ......................................................................................... 93Summary ..................................................................................................................................................... 95References ................................................................................................................................................... 95Recommended Reading ............................................................................................................................. 96Self Assessment ........................................................................................................................................... 97

Page 8: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

VI/JNU OLE

List of Figures

Fig. 7.1 Using the sizeof operator to determine storage requirements ........................................................ 69Fig. 7.2 Using the sizeof operator and simple arithmetic to determine the number of elements

in an array ....................................................................................................................................... 69Fig. 7.3 Using dynamic memory to read character strings from standard input .......................................... 72Fig. 7.4 Using realloc () to expand contiguous memory segments .............................................................. 75Fig. 7.5 Using chapter based concepts to build the Math Quiz ................................................................... 76

Page 9: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

VII/JNU OLE

List of Tables

Table 1.1 Keywords ....................................................................................................................................... 3Table 1.2 Character set of ‘C’ language ......................................................................................................... 3Table 1.3 Basic data types .............................................................................................................................. 4Table 1.4 Data type – range of values ............................................................................................................ 4Table 1.5 Arithmetic operators ....................................................................................................................... 6Table 1.6 Rational operators .......................................................................................................................... 7Table 1.7 Logical operators ............................................................................................................................ 7Table 1.8 Operator precedence....................................................................................................................... 8Table 1.9 Bitwise operators ............................................................................................................................ 9Table 2.1 Scanf function - character conversion .......................................................................................... 17Table 4.1 Elements of multidimensional array ............................................................................................ 36Table 4.2 Backslash escape .......................................................................................................................... 36Table 4.3 String functions ............................................................................................................................ 37Table 7.1 Possible realloc () Outcomes ........................................................................................................ 74Table 8.1 Data file hierarchy ........................................................................................................................ 83Table 8.2 Common Text File Open Modes .................................................................................................. 85Table 8.3 Fscanf ( ) Type Specifiers............................................................................................................. 87

Page 10: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the
Page 11: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

1/JNU OLE

Chapter I

‘C’ Fundamentals

Aim

The aim of the chapter is to:

explain various programming language•

explicateidentifiersandkeywords•

elucidate datatypes•

Objectives

The objectives of this chapter are to:

explain various types of variables•

explicate advanced programming tools•

explain the basics of ‘C’ programming language•

Learning outcome

At the end of the chapter, you will be able to:

defineoperations•

distinguishidentifiersandkeywords•

understanddifferentdatatypes,datatypequalifiersandvariables•

Page 12: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

2/JNU OLE

1.1 IntroductionComputer is a system, made up of two major components; hardware and software. The set of physical components i.e., mouse, keyboards, monitor, CPU, etc. are the forms of the hardware. Software is the secondary component which acts as an interface between a user and hardware.

Without software it is not possible to use hardware. Software is the set of programs, while a program is a set of instruction given to the hardware. Software helps the user to run the programs. Computer system cannot be used without it. In other words, software can be called the bridge between the user and the computer hardware.

Thecomputersystemisclassified intofivemaincategoriesbasedon therequirementof theuser.Theseareasdiscussed below.

1.1.1 Operating systemIt is the platform of the computer and is a necessary application for all computer systems, which helps the user to boot the machine. Windows XP, Linux, Windows NT, MAC, OS/2, etc. are some examples of the operating systems.

1.1.2 Application softwareAccountingsoftwarelikeTally;officeautomationsoftwarelikeMicrosoftOfficeordesigningtoolslikeCoralDraw,Page Maker or Photoshop are available software which are developed according to the user's need.

1.1.3 Programming languagesBASIC, C++, C#, Java, etc. are the examples of the computer languages. These are the programming languages which are used to develop system and application software.

1.1.4 Advanced development toolsThese are basically used in combinations. The major categories of this software include;

Front endDesigns screen and reports of the software. Visual Basic, Developer 2000, Visual C++ are some popular front ends.

Back endDBMS or RDBMS are used to store the data entered by the user. Oracle, Sybase, Informix etc are some popular back ends.

1.1.5 Web based toolsHTML, DHTML, VB Script, Java Script, ASP, PHP, PERL etc. are some software used to develop internet websites.

1.2 Introduction to ‘C’Information technology is the subject which deals with programming. Programming or coding is the process of testing, writing, debugging/troubleshooting and maintaining the source code of computer programs. This source code is written in a programming language.

‘C’ is the programming language which is used to write the program and execute it. It was developed at AT & T’s Bell Laboratories in USA in1972 and was written by Dennis Ritchie. It is popular because of its reliability, simplicity and user friendly facility. COBOL was the language which was used for commercial purpose. BASIC was used as beginner’s language and FORTRAN was used for engineering applications.

There are mainly two types of languages, known as low level and high level languages.

Page 13: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

3/JNU OLE

1.2.1 Low Level LanguagesThese languages interact with machine hardware e.g., memory.

1.2.2 High Level Languages

These are human understandable languages, like English.•Example - ‘C’ language.•

Code written in ‘C’ language is portable, i.e., software written on one type of computer can be adapted to �work on another type.This language shows both low level and high level feature as it interacts with the hardware as well as �English in words.As ‘C’ language is written in blocks, it is also called a block structured language. �It is a very powerful language, as most part of UNIX (multi-user operating system) is written in ‘C’. �‘C’hasfivebuilt-indatatypesandpermitsalmostalldatatypeconversion. �‘C’ languages are widely used in the electronic devices like cellular phones, laptops, microwaves, etc. �It is majorly used in 3D applications like video games, where we need powerful graphical interface and �fast speed.It enables the user to write virus as well as antivirus programs in ‘C’. �

1.3 Identifier and KeywordsIn‘C’language,everywordhasakeywordoranidentifier.Thenamesgiventothevariablesbythecompilerarereferredtobeidentifiers.Theyrefertothenameofuserdefinedvariable,arraysandfunctions.Theyshouldessentiallybe sequence of letters or digits. The variable name should begin with characters and are permitted to be written in upper case and lower case both or even with underscore. The keyword set of ‘C’ language is given below.

auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsigned

continue for signed voiddefault goto size of volatile

do if static while

Table 1.1 Keywords

The following table is the character set of ‘C’ language.

letter A B C D E F G H I J K L M N O P Q R S T U V W X Y Zdigit 0 1 2 3 4 5 6 7 8 9 underscore _punctuation ! " # % & ' ( ) * + , - . / ; < = > ? [ \ ] ^ { | } ~

Table 1.2 Character set of ‘C’ language

Page 14: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

4/JNU OLE

1.4 Data Types and ConstantsFor any computer programming language, it is very essential to have a data type, which makes it easier to maintain information within a computer program. Data type plays a very important and large part, since the basic principle behind the computer programming is to take the information, process it and deliver the information to the user in a different form. The programmer has to declare as to which data type has to be used for each data object for most of theprogramminglanguagesandmostdatabasesystemsrequiretheusertodeclarethetypeofeachdatafield.Thedata types differ from one programming language to another and from one data base application to another. The constant value is the entity that does not change when the program is executed. It refers to a value. ‘C’ supports various types of constants.

1.4.1 Basic Data Types

Integer intFloating point floatDoublefloatingpoint doubleCharacter charVoid void

Table 1.3 Basic data types

Data Type Range of valuesint - 32768 to +32767float 3.4e-38 to 3.4e+e38double 1.7e+308char -128 to 127

Table 1.4 Data type – range of values

int•usedtodefineinternumbers �no decimal points are used �takes 16 bytes of memory to store the value on 16 bit machine �an integer can be positive or negative �

float•usedtodefinefloatingpointnumbers �storesonlyfloatingpointvalues �the values should be in decimal places and it takes 32 bytes of memory to store the value on 16 bit �machine

double•usedtodefinebigfloatingpoints �used to get the store on 16 bit machine, it requires 64 bytes of memory �

char•usedtodefinecharacters �used to store single character or number at a time �used a 16 bit machine, 8 byte memory is required for character type of data �

void•using void data type, we can specify a function �

Page 15: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

5/JNU OLE

1.4.2 Type QualifiersTypequalifiersdeclarethevariablesalongwiththedatatypes.

Short•Long•Unsigned•Unsigned long•

1.4.2.1 Short

Short int is an integer of lower range.•Short int may require less memory than an ordinary int or require same amount of memory, but will never •exceed an ordinary int in word length.The short int will have half the memory requirements, if long int and int have the same requirements.•

1.4.2.2 Long

Long int is an integer of increased range. Long int may require more memory than ordinary int or may require •the same amount of memory but will never be less than an ordinary int. Long int will have double the requirements, if short int and an ordinary int both have the same requirements.•

1.4.2.3 Unsigned

An unsigned int is the integer with no negative range, the space capacity is used to increase positive range•Unsigned int and int have similar memory requirements.•The unsigned int can be twice as large as an ordinary int.•

1.4.2.4 Unsigned long

Like unsigned, int might possibly be of increased range.•

1.5 VariablesAvariableisanidentifierwhichisusedtorepresentaspecifictypeofinformationwithinadesignatedportionofa program. It represents a single data item, i.e., numerical quantity or a character constant. A variable is the entity that changes when the program is executed. They can be changed at different times. A variable is a name which stores a value in the memory. It stores only one value at a time. If the variable is of the real type it can be stored usingfloatordoubledatatype.

1.5.1 Variable DeclarationThe variables are declared along with the data types so that the compiler understands which type of variable it is.General syntax used is,

<data type> <variable name>;

Example,int num �floatpercent �char grade �

You can use extended data types as mentioned below:Long int amount �Signed int temp �

Page 16: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

6/JNU OLE

1.5.2 Variable InitialisationValues are assigned for the variables through the variable initialisation.Example,int num; //variable declarationnum = 1; //variable initialisation

1.5.3 Declaring Variables as ConstantsConstant variable values once assigned cannot be changed throughout the program. These types of variables can be declared using the keyword ‘const’.

Example,constafloatpi=3.14

1.6 Operators and ExpressionsIndividual constants, variables array elements and function can be joined together by the various operators to form expressions. An operator is a symbol which enables the user to command the computer and perform certain manipulations and calculations. The data items that operators act upon are called operands. Some operators require two operands, while other act upon only one operand. It is used in ‘C’ language program to operate on data and variables.‘C’hassetofoperatorswhichcanbeclassifiedasthefollowing:

1.6.1 Arithmetic Operators

Basic operations such as addition, subtraction, multiplication and division are performed using arithmetic •operations.%istheoperatorcalledasmodulusoperatorandisusedtofindoutdivisionfromtheremainder.•The operand acted upon by the arithmetic operators must represent numeric values.•Division of one integer quantity by another is referred to be integer division.•Floatingpointquotientistheresultifadivisionoperationiscarriedoutwithtwofloatingpointnumbersorwith•onefloatingpointnumberandoneinteger.

Sr. No. Operator Meaning1. + Addition or unary plus2. - Subtraction or unary minus3. * Multiplication4. / Division5. % Modulus

Table 1.5 Arithmetic operators

Examples of arithmetic operators are,x + y �x – y �-x + y �a * b + c �-a * b �

where,a, b, c, x, y are Operands.

Page 17: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

7/JNU OLE

1.6.2 Rational Operators

Rational operators are required to compare the relationship between operands.•They are popularly known as comparison operators. ‘C’ supports the following rational table.•

Sr. No. Operator Meaning1. < Less than2. > Greater than3. ≤ Less than or equal to4. ≥ Greater than or equal to5. = Equal to6. ! = Not equal to

Table 1.6 Rational operators

The operands fall within the same precedence group, and are lower than the arithmetic and unary operators.•The equal to (=) and not equal to (! =) operators fall within different precedence group, beneath the rational •operators.

1.6.3 Logical Operators

The six rational operators are used to form logical operators, which help represent the conditions either true or •false.True condition is represented by value 1.•False condition is represented by value 2.•Logical operators are used to compare or evaluate logical and rational expressions. AND, OR and NOT are the •logical operators.The result of AND operation will be true if the both the operand are true.•The result of OR operation will be true if either operand is true or both the operands are true. Thus, the result •of operation OR will be false only if both the operands are false.OR operation is of higher precedence than operation AND.•

Sr. No. Operator Meaning1. && Logical AND – True if all conditions are true2. || Logical OR – True if any one or all conditions are true3. ! Logical NOT – Negation

Table 1.7 Logical operators

Expression is the set of operators and operands.Consider,c = a + bHere, c will store addition of a and b.

Page 18: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

8/JNU OLE

Sr. no. Operator category Operators Associativity1. Arithmetic – multiple, divide and remainder ×, ÷, % L→R2. Arithmetic – add and subtract +, - L→R3. Rational operators <,≤,>,≥ L→R4. Equality operators =, != L→R5. AND && L→R6. OR || L→R

Table 1.8 Operator precedence

1.6.4 Comma Operator

Comma operator is used to separate two or more expressions when only one expression is expected.•a=(b=3, b=2)

Comma operator is also used in an expression for forming a loop.•

1.6.5 Conditional Operators

An expression that makes use of conditional operator is called as conditional expression.• Conditional operator is in combination of ‘? :’. This is called as tertiary operator. Its general form is, •expression 1? expression 2 : expression 3Expression1isevaluatedfirstwhenconditionalexpressionisevaluated.•Expression 2 is evaluated if expression 1 is true and it becomes the value of conditional expression.•If expression 1 is false, expression 3 is evaluated and it becomes the value of conditional expression.•Conditional expression often appears on the right hand side of an assignment statement.•Above the assignment operator, the conditional operator has its own precedence.•

It checks the condition and evaluates the result depending upon the status of the condition.i.e., true or false.Example, max = a > b ? a : bHere, if a>b, then the condition becomes true and max variable will store the value of a if a>b is false, then max variable will store the value of bThus, the conditional operator evaluates true or false and returns the result.

1.6.6 Bitwise Operators

Basically, the computer does not understand any language so the bitwise operators are used to manipulate the data. •Considering the bit pattern of the values stored by a computer, the bitwise operators modify the variables.It understands the machine code which is in the form of 0’s and 1’s. But this program is written in a high level •language. A program, called compiler, is used to convert the high level language into low level language. ‘0’ and ‘1’ are called as bits. Bitwise operation is thus, required to perform multiple operations on bits.

Page 19: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

9/JNU OLE

Sr. No. Operators Meaning1 & Bitwise AND2 | Bitwise OR3 ^ Bitwise exclusive OR4 << Shift Lift5 >> Shift Right

Table 1.9 Bitwise operators1.6.7 Assignment Operators

In ‘C’ language, there are several different operators that are used to form assignment expressions which assign •thevalueofanexpressiontoanidentifier.The most commonly used assignment operator is '='. This is used to assign some value to the variable. •The arithmetic operations precede assignment operation.•

Example, b = 10Here, value 10 is assigned to the variable b.

1.6.8 Increment and Decrement OperatorsIncrement and decrement operators are the shortcuts used to increment the values. The operator '+ +' is used to increase the value by 1 and the operator '- -' is the decrement operator, used to reduce value by 1.Example,+ + x is similar to x = x = 1If, x is 5, Then, after + + x or x + + , x will become 6Or,x + + is similar to x = x + 1-- y is similar to y = y – 1If, x is 5,then after + + x or x + +,x will become 6Or,y - - is similar to y = y – 1Withinvariablename,incrementanddecrementoperatorscanbeusedasprefixorpostfixposition.

1.7 Preprocessor DirectivesThe ‘C’ preprocessor is exactly what its name implies. It is a program that processes our program before it is passed to the compiler. Preprocessor directives form what can almost be considered a language within ‘C’ language. In the code of any program, preprocessor directives are the lines included which are not program statements but, directivesforthepreprocessor.Theselinesaregenerallydefinedbyahashsymbol(#).Thepreprocessordigestsallthese directives before any code is generated by the statement since the preprocessor is executed before the actual compilation of the code begins. The preprocessor directives extent only across single line code and the preprocessor directive is considered to end as soon as a new line character is found. By preceding the new line character at the end of the line by a backslash (\), the preprocessor directive can be extended through more than one line.

The following are the types of preprocessor directives:Macro expansion �File inclusion �

Page 20: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

10/JNU OLE

1.7.1 Macro ExpansionConsider the following program,

#defineUPPER25main ( ){ int I ; for(i=1;i≤UPPER;i++) printf ( “\n%d”, i ) ;}In this program, instead of writing 25 in the ‘for’ loop, we are writing it in the form of UPPER, which has already beendefinedbefore‘main()’throughthestatement,

#defineUPPER25

Thisstatementiscalled‘macrodefinition’ormorecommonly,justa‘macro’.Duringpreprocessing,thepreprocessorreplaces every occurrence of UPPER in the program with 25.

Exampleofmacrodefinition,

#definePI3.1415main ( ){ floatr=6.25; floatarea; area = PI* r*r ; printf ( “\nArea of circle = %f”, area ) ;}

UPPER and PI in the above programs are often called ‘macro templates’, whereas, 25 and 3.1415 are their corresponding ‘macro expansions’.

A‘#define’directiveismanyatimesusedtodefineoperatorsasshownbelow.

#defineAND&&#defineOR||main ( ){ int f = 1, x =4, y = 90 ;

if((f,5)AND(x≤20ORy≤45)) printf(“\nYourPCwillalwysworkfine…”); else print (“\nIn front of the maintenance man” ) ;}

A‘#define’directivecouldbeusedeventoreplaceacondition.

#defineAND&&#defineARRANGE(a>25ANDa<50)main ( ){

Page 21: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

11/JNU OLE

int a = 30 ;

if (ARRANGE) printf ( “within range” ) ; else printf ( “out of range” ) ;}

A#definedirectivecouldbeusedtoreplaceevenanentire‘C’statement.#defineFOUNDprintf(“Xvirus”);main ( ){ char signature ;

if ( signature = =’Y’ ) FOUND else printf(“Safe…asyet!”);}

1.7.2 File InclusionFeaturesoffileinclusionareasfollows:

Ifwehaveaverylargeprogram,thecodeisdividedintoseveraldifferentfiles,eachcontainingasetofrelated•functions.Itisagoodprogrammingpracticetokeepdifferentsectionsofalargeprogramseparate.Thesefilesare‘#included’atthebeginningofmainprogramfile.Therearesomefunctionsandsomemacrodefinitionsthatareneededalmostinallprogramsthatwewrite.These•commonlyusedfunctionsandmacrodefinitionscanbestoredinafileandthefilecanbeincludedineveryprogramwewrite.Thiswouldaddallthestatementsinthefiletoourprogramasifwehavetypedthemin.There are two ways to write ‘#include’ statement.•

#include“filename”–thiscommandwilllookforthefilenameinthecurrentdirectoryaswellasthespecific �list of directories as mentioned in the include search path that might have been set up.#include<filename>-thiscommandwilllookforthefilenameinthespecifiedlistofdirectoriesonly. �

Page 22: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

12/JNU OLE

SummaryOperating system is a platform to use the computer system. Windows XP, Linux, MAC, etc. are a few examples •of the operating systems that are used. Java, ‘C’, ‘C+ +’, etc. are computer programming languages.A low level programming language interacts with the machine hardware, while the high level programming •language interacts in human understandable language, like English.In‘C’language,everywordhasakeywordoranidentifieralongwithacharacterset.•The constant value is the entity that does not change when the program is executed and it refers to a value.•‘C’consistsofvariousdatatypes.-int,float,double,charandvoid.•Short,long,unsignedandunsignedlongarethedataqualifiers.•The variables are declared along with the data types so that the compiler understands which type of variable •it is.An operator is a symbol that enables the user to command the computer and perform certain manipulations and •calculations.Theseareclassifiedas-arithmeticoperators,rationaloperator,logicaloperator,commaoperator,conditional operation, bitwise operator, assignment operator and increment and decrement operators.In the code of any program, preprocessor directives are the lines included which are not program statements •but directives for the preprocessor.

ReferencesDixit, J. B., 2005. • Fundamentals of Computers and Programming in C, Firewall Media.Balagurusamy, 2008. • Programming In Ansi C, 4th ed., Tata McGraw-Hill Education.Lipari, G., 2012. • Fundamentals of Programming Introduction to the C language [Pdf] Available at: <http://retis.sssup.it/~lipari/courses/infbase2012/03.c_intro-handout.pdf> [Accessed 26 June 2013].Introduction to the C Programming Language • [Pdf] Available at: <http://163.25.99.51/Huang_Computer/Programming%20Language-website2.pdf> [Accessed 26 June 2013].Dr. Kumar, A. S., 2008.• Lecture - 1 Introduction to programming languages [Video online] Available at: <http://www.youtube.com/watch?v=EbNJ05EVXs0> [Accessed 26 June 2013].PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts• [Video online] Available at: <http://www.youtube.com/watch?v=c_sDgHgNR6w> [Accessed 26 June 2013].

Recommended ReadingDeitel, J. P. & Deitel, M. H., 2009. • C: How to Program, 6th ed., Prentice Hall.Kochan, G. S., 2012. • Programming in Objective-C, 4th ed., Addison-Wesley Professional.Kochan, 2005. • Programming In C, 3/E, Pearson Education India.

Page 23: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

13/JNU OLE

Self AssessmentLow level languages interacts with machine __________.1.

softwarea. hardwareb. operating systemc. programming languaged.

In‘C’language,every__________hasakeywordoranidentifieralongwithacharacterset.2. sentencea. lineb. wordc. segment d.

Increment and decrement operators are the shortcuts used to increment the values. The operator __________ 3. is used to increase the value by 1 and the operator __________ is the decrement operator, used to reduce value by 1.

' + + ' , ' - - 'a. ' - ' , ' + + 'b. ' +' , ' - -'c. ' - - ' , ' + +'d.

__________ is used to separate two or more expressions when only one expression is expected.4. Assignment operatora. Arithmetic operatorb. Comma operatorc. Conditional operatord.

Which of the following statements is true?5. Comma operator is in combination of ‘? :’a. Conditional operator is in combination of ‘? :’b. Conditional operator is in combination of ‘# :’c. Conditional operator is in combination of ‘? .’d.

Which of the following statements is true?6. Rational operators are required to compare the relationship between operands.a. Assignment operators are required to compare the relationship between operands.b. Rational operators are not required to compare the relationship between operands.c. Logical operators are required to compare the relationship between operands.d.

Which of the following statements is true?7. Greaterthanorequaltoisthemeaningoftheoperator≤a. Greater than or equal to is the meaning of the operator ±b. Greaterthanorequaltoisthemeaningoftheoperator≠c. Greaterthanorequaltoisthemeaningoftheoperator≥d.

Page 24: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

14/JNU OLE

Whichsymbolisgenerallyusedtodefinethelinesinthepreprocessordirectives?8. Percentage ( % ) signa. Hash ( # ) signb. Ampersand ( & ) signc. Underscores ( _ ) signd.

Identifydatatypequalifiers.9. Short and longa. Long and unsignedb. Long, unsigned and unsignedc. Short, long, unsigned and unsigned longd.

Which operators are required to compare the relationship between operands?10. Logical operatorsa. Rational operatorsb. Conditional operatorsc. Comma operatorsd.

Page 25: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

15/JNU OLE

Chapter II

Data Input and Output

Aim

The aim of the chapter is to:

explain data output and input functions•

explain getchar function•

defineputcharfunction•

Objectives

The objectives of this chapter are to:

explain in detail putchar function•

describe getchar function•

expliacte scanf function, printf function and gets and puts function•

Learning outcome

At the end of this chapter, you will be able to:

understand printf function•

identify scanf function•

describe gets and puts function•

Page 26: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

16/JNU OLE

2.1 IntroductionInput and output data is done by a collection of library functions like getchar, putchar, scanf( ), printf( ), gets and puts in ‘C’ language, which permit the transfer of information between the computer and the standard input and output devices.

Following a list of parameters enclosed in parentheses, simply by writing the function name an input or output function can be accessed from anywhere within a program. The empty parenthesis must appear though some input outputfunctionsdonotrequireparameters.‘C’includesacollectionofheaderfileswhichprovidestheinformationthatisnecessaryinsupportofvariouslibraryfunctions.Studio.histheheaderfilethatcontainstheinformationabout the input or output library function.

2.2 Getchar FunctionsGetchar function reads a single character from standard input. It does not take parameters and the input character is its returned value. It is a part of standard ‘C’ input and output library. It does not require any arguments.

In general, a reference to the getcher is written as, Character variable = getchar ( )

Example, char c; c = getchar ()

From the standard input device, the second line causes a single character to be entered and then assigned to c. By reading one character at a time within a multipass loop, this function can also be used to read multicharacter strings. Thevalueofthesymbolicconstant‘end-of-file’willautomaticallybereturnedifitisencounteredwhilereadingacharacter with the getchar function.

2.3 Putchar FunctionThe standard ‘C’ function that prints or displays a single character by sending it to standard output is called putchar. It considers one argument, which is the character to be sent and also returns this character as its result. An error value is returned if any error occurs. Therefore, it should be declared as a function if the returned value of putchar is used returning an int.

Example,putchar (‘N’) �putchar (‘a’) �putchar (‘t’) �putchar (‘i’) �putchar (‘o’) �putchar (‘n’) �putchar (‘a’) �putchar (‘l’) �

However, each character must be output separately, when putchar is used. In the given statements, the parameters to the function calls are character constants, represented between apostrophes as usual. The arguments could be character variable instead. getc and putc are the two functions those require FILE pointers which are similar to getcharandputcharexceptthattheycanoperateonfilesotherthanthestandardinputandoutput.Thegetcfunctionis called with one argument. The expression getc(stdin) is similar to getchar( ) and the expression putc(c, stdout) is same as putchar(c).

Page 27: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

17/JNU OLE

2.4 Scanf( ) FunctionScanf( ) is a C library function. By means of this function, input data can be entered from a standard input device into the computer memory. This function is generally used to enter any combination of numerical values, single character and strings. The function returns the number of data items that have been entered successfully.The general form to write scanf( ) function is:

scanf (string, parameter 1, parameter 2..., parameter n)

where,String - string containing required formatting informationParameter 1 and parameter 2 - parameters that represent the individual input data item.Each character group must start with percent sign (%).

Sr. No. Conversion character

Meaning

1 c type of data item is single character2 d type of data item is decimal integer3 e typeofdataitemisfloating–pointvalue4 f typeofdataitemisfloatingpointvalue5 h type of data item is short – integer6 i type of data item is decimal, hexadecimal or octal integer 7 o type of data item is octal integer8 s type of data item is string9 u type of data item is unsigned decimal integer10 [. . .] type of data item is string which may include whitespace characters.

Table 2.1 Scanf function - character conversion

The parameters whose types match the corresponding characters groups in the control string are written as variables or arrays. Each variable must be preceded by ampersand (&) sign. If two or more characters are entered, they must be separated by white space characters. Since the newline character is considered to be white space character, data items may continue onto two or more lines. All the arguments must be pointed to the variables used as arguments.

2.5 Printf( ) FunctionThis function is used to print out a message, either on screen or on paper. The letter ‘f’ in printf( ) either stands for “formatted” or “function”. It is equivalent to WRITE a statement in Pascal but is more powerful. It is very much similar to the input function scanf( ). Its purpose is to display data rather than to enter data into the computer. The main function of printf ( ) function is to move data from the computer’s memory to the standard output device.

The general form to write printf( ) function is:printf(string, parameter 1, parameter 2,......, parameter n)

where, String - refers to a string that contains formatting information. Parameter 1, parameter 2,........, parameter n - these are the arguments that represent the individual output data items.

Parameters can be written as constants, single variables or array names or more complex expressions. Parameters in printf( ) function do not represent memory addresses, unlike scanf( ) function and thus they are not preceded by ampersand (&) sign. The control string is composed of individual groups of characters, with one character group for

Page 28: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

18/JNU OLE

each output data item. Each character group must start with a percent sign (%) followed by a conversion character indicating the type of the corresponding data item. Multiple characters can be separated by whitespace characters.Therearetwomodifiersofprintf()function.Longintegerisusedtodisplaylongdatatypeandshortintegerisusedto display short data type.

2.6 Gets ( ) and Puts ( ) FunctionsGets and puts functions facilitate the transfer of strings between the computer and the standard input or output devices. Each of these functions accepts a single argument or parameter. The parameter must be data item representing a string and the string may include whitespace characters. For reading and displaying strings, gets and puts functions are the alternatives for scanf and printf.

Example, Char school [40] gets(school) puts(school)

These lines use gets and puts to transfer the line of text in and out of the computer. It will give the same result as the scanf and printf function for input and output of given variable or array, when this program is executed.

Page 29: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

19/JNU OLE

SummaryInput and output data is done by a collection of library functions like getchar, putchar, scanf, printf, gets and •puts in ‘C’ language, which permit the transfer of information between the computer and the standard input and output devices.Getchar function reads a single character from standard input. It does not take parameters and the input character •is its returned value.The standard ‘C’ function that prints or displays a single character by sending it to standard output is called •putchar.Scanf is the function where input data can be entered from a standard input device into the computer •memory.Printf function is used to print out a message, either on screen or on paper. The letter ‘f’ in printf either stands •for “formatted” or “function”.Gets and puts functions facilitate the transfer of strings between the computer and the standard input or output •devices.

ReferencesGoel, A.,• Computerprogramming-I:Asperthefirst-yearengineeringsyllabusofUniversityofMumbai, Pearson Education India.Veerana, V. K. & Jankidevi, S. J., 2007. • CforUIncludingCandCGraphics, Firewall Media.Kernighan, W. B. & Ritchie, M. D., 1988. • The C programming Language [Pdf] Available at: <http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf> [Accessed 26 June 2013].Input and Output in C• [Pdf] Available at: <http://www.prog2impress.com/downloads/Input%20and%20Output%20in%20C.pdf> [Accessed 26 June 2013].Introduction to C Programming I • [Video online] Available at: <http://www.youtube.com/watch?v=fUcSXbQnrLI&list=PL66D13A5B3585C213> [Accessed 26 June 2013].CProgrammingTutorial:InputOutput(printf,scanf,formatspecifiers)Lesson1• [Video online] Available at: <http://www.youtube.com/watch?v=5v7h4ZmgMvw> [Accessed 26 June 2013].

Recommended ReadingRajaraman, V., 1994. • COMPUTERPROGRAMMINGINC, PHI Learning Pvt. Ltd.Reddy, R. & Ziegler, C., 2009. • C Programming for Scientists and Engineers with Applications, Jones & Bartlett Learning.Dixit, J.B., 2006. • ComprehensiveProgramminginCandNumericalAnalysis, Laxmi Publications.

Page 30: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

20/JNU OLE

Self AssessmentParameters of the printf function can be written as constants, __________ variables or array names or more 1. complex expressions.

doublea. tripleb. singlec. externald.

The meaning of conversion character __________ is type of data item is decimal, hexadecimal or octal 2. integer.

Sa. Ub. Oc. Id.

By reading one character at a time within a multipass loop, __________ can also be used to read multicharacter 3. strings.

getchar functiona. putchar functionb. printf functionc. scanf functiond.

Which of the following statements is true?4. Parameters in printf function do not represent memory addresses, unlike scanf function and thus they are a. not preceded by ampersand (&) sign.Parameters in printf function do not represent memory addresses, unlike scanf function and thus they are b. not preceded by percentage (%) sign.Parameters in printf function do not represent memory addresses, unlike scanf function and thus they are c. not preceded by hash (#) sign.Parameters in scanf function do not represent memory addresses, unlike scanf function and thus they are d. not preceded by ampersand (&) sign.

Which of the following statements is true?5. In scanf function if two characters are entered, they must be separated by white space characters.a. In scanf function if two or more characters are entered, they must not be separated by white space b. characters.In printf function if two or more characters are entered, they must be separated by white space characters.c. In scanf function if two or more characters are entered, they must be separated by white space characters.d.

Which of the following statements is true?6. Type of data item is short – integer is the meaning of conversion character I.a. Type of data item is short – integer is the meaning of conversion character H.b. Type of data item is short – integer is the meaning of conversion character S.c. Type of data item is short – integer is the meaning of conversion character U.d.

Page 31: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

21/JNU OLE

Which function reads a single character from standard input?7. getchara. putcharb. printfc. scanfd.

Parameter of which function must be data item that represents a string and the string may include whitespace 8. characters.

printfa. scanfb. putcharc. gets and putsd.

Type of data item is string which may include whitespace characters is the meaning of which conversion 9. character?

Sa. [. . .]b. Uc. Id.

The expression getc(stdin) and putc(c, stdout) are similar to which functions? 10. getchar(c) and putchar(c)a. scanf() and printf()b. scanf ( )c. printf ( )d.

Page 32: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

22/JNU OLE

Chapter III

Control Statements

Aim

The aim of the chapter is to:

explain the concept of decision making and branching in ‘C’ language•

explain different control statements•

explicate 'for loop' statements•

Objectives

The objectives of this chapter are to:

explain the control statements in ‘C’ language•

enlist various control statements•

explicate break, switch and continue statements•

Learning outcome

At the end of this chapter, you will be able to:

defineifstatement•

defineifelseconstruct•

understand iteration loop, do while loop, for loop•

Page 33: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

23/JNU OLE

3.1 IntroductionControlstatementsarethestatementsin‘C’languagethatcanaltertheflowofasequenceofinstruction.Itisusedto carry out some actions. These statements enable the user to jump from one program to another. The program transfer may be conditional or unconditional. All control statements involve the use of logical expressions.Example: a < b

3.2 LoopsThe versatility of the computer lies in its ability to perform a set of instruction repeatedly. This involves some portion oftheprogram,eitheraspecifiednumberoftimesoruntilaparticularconditionisbeingsatisfied.Thisrepetitiveoperation is done through a loop control instructions.

There are three methods by which we can repeat a part of a program. They are as follow:using a ‘for’ statement•using a ‘while’ statement•using a ‘do-while’ statements•

3.2.1 For Loop Statement

The ‘for’ loop provides a more concise loop control structure.•It is used to repeat the actions given within the limit. ‘for’ statement has three conditions as follows:•

initial condition – from where the loop execution starts �finalcondition–itisatestcondition �increment or decrement - directs loop how to proceed �

As long as the test condition is being a newline or a carriage return, the for loop is used to read a character from •the keyboard.The ‘for’ loop allows us to specify two things about a loop in a single line. These are:•

setting a loop counter to an initial value testing the loop counter to determine whether its value has reached �the number of repetitions desired.

General form of ‘for’ statement is:•

for (initialise counter ; test counter ; increment counter){ do this ; and this ; and this ;}

3.2.1.1 Execution of ‘For’ Statement

Whenthe‘for’statementisexecutedforthefirsttime,thevalueof‘count’issettoaninitialvalue1.•Nowthecondition‘count≤3’istested.Since‘count’s1,theconditionissatisfiedandthebodyoftheloopis•executedforthefirsttime.Upon reaching the closing brace of ‘for’, control is sent back to the ‘for’ statement, where the value of ‘count’ •gets incremented by 1.Again the test is performed to check whether the new value of ‘count’ exceeds 3.•If the value of ‘count’ is still within the range 1 -3, the statements within the braces of ‘for’ are executed •again.Thebodyofthe‘for’loopcontinuestogetexecutedtill‘count’doesn’texceedthefinalvalue3.•When ‘count’ reaches the value 4, the control exits from the loop and is transferred to the statement (if any) •immediately after the body of ‘for’.

Page 34: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

24/JNU OLE

3.2.2 While Loop

‘While’ loop is the simplest of all looping structures.•It is used when we are not certain that the loop will be executed.•‘C’ is almost identical to Pascal. The ‘while’ loop can also terminate when ‘break’, ‘goto’ or ‘return’ like •statement body is executed.It is used for repetition purpose.•The loop gets iterated till the condition is true.•The loop gets break once the condition becomes false.•The 'while' loopwillenter intotheoperationsonlyafterfindingoutwhether theinitialconditionis trueor•false.Simple while statement syntax can be written as:•

While ( test condition ){Body of the loop}

The following points are to be noted about ‘while’ loop:•The statements within the ‘while’ loop would keep on getting executed till the condition under testing �remainstrue.Whentheconditionbecomesfalse,thecontrolpassestothefirststatementthatfollowsthebody of the ‘while’ loop.Any other valid expression can be used in place of the condition. So as long as the expression evaluates to �a non-zero value, the statements within the loop would get executed.The condition being tested may use logical operators.The following example may be considered: �

while(i≤10)while(i≥10&&j≤15)

while ( j > 10 && (b < 15 || c < 20 ) )

Thestatementwithintheloopmaybeasinglelineorablockofstatements.inthefirstcasetheparentheses �are optional.

Example:

while(i≤10) i = i +1 ;

Is same as

while(i≤10){ i = i + 1 ;} As a rule, the ‘while’ must test a condition that will eventually become false.

main ( ){ int i = 1 ; while(i≤10) printf ( “%d\/”, i) ;}

Page 35: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

25/JNU OLE

Thisisanindefiniteloop,since‘i’remainsequalto1forever.The correct form would be,

main ( ){ int i = 1 ; while(i≤10) { printf ( “%d\n”, i ) ; }}

Instead of incrementing loop counter, we can even decrement it and still manage to get the body of the loop executed repeatedly. The following format may be referred.

main ( ){ int i = 5 ; while(i≥1) { printf ( “\nmake the computer literate!” ) ; i = i – 1 ; }}

Itisnotnecessarythataloopcountermustonlybean‘int’.Itcanevenbe‘float’.Example:

main ( ){ floata=10.0; while(a≤10.5){ printf ( “\nRaindrops on roses.....” ) ; printf ( “....and whiskers on kittens” ) ; a = a + 0.1 ; }}

Evenfloatingpointloopcounterscanbedecremented.Onceagaintheincrementanddecrementcouldbebyanyvalue, not necessarily 1.

3.2.3 Do – While Statement

‘Do - while’ loop is also a kind of a loop similar to while loop.•The ‘do while’ loop tests at the bottom of the loop after executing the body of the loop.•We can assure that the body of the loop is executed at least once. This is because the body of the loop is executed •firstandthentheloopconditionischecked.The loop operations or statements will be repeated again and again as long as the condition is true.•Three expressions are used to construct this loop.•Simple syntax of do while loop is given below:•

Page 36: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

26/JNU OLE

do{statement}while (expression) ;

Here, the expression is evaluated after the statement is executed. If the condition expression is true then the body is executed again and this process continues till the expression becomes false. The loop terminated when the expression becomes false.

3.3 The Break StatementIn ‘C’ language, sometimes it becomes very necessary to skip a part of the loop or quit the loop as soon as certain condition occurs during the execution of a loop. Within a loop, ‘C’ language permits a jump from one statement to another as well as jump out of the loop. The break statement allows us to accomplish this task. It provides the programmer an early exit from for, while, do and switch constructs. It is used to break the control in the loops. In other words, it is used to break the sequence. Break passes control to the next statement immediately after the innermost loop. Break statements are generally used with switch statements. A simple break statement syntax is given below:

while ( /* . . */ ) {while (/* . . */ ) { /* . . */ Break;}/* when the break executes the program, the program continues to execute from here */}

3.4 Continue StatementIn ‘do - while’ and ‘for’ loops, 'continue' is used to transfer execution to the bottom of the body of the loop. The next thing to happen in the case of ‘do’ and ‘while’, is the testing of the continuation condition whereas the continuation condition is tested with a ‘for’ statement and execution continues with the increment statement. It is a keyword and is followed by a semicolon (;). It is used for inverse operations of break statement. A ‘continue’ is usually associated with an ‘if’.

Example:

main ( ){ int i, j ; for(i=1;i≤2;j++) { for(j=1;j≤2;j++) { if ( i = = j ) continue ; printf ( “\n%d %d\n”, i, j ) ; } }}

Page 37: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

27/JNU OLE

The output of the above program would be,1 22 1

3.5 ‘If’ Statement‘If’ statement is the simplest form of the control statement and is often used in making a decision and allowing the flowofexecutionofaprogram.Itisoftenusedtocheckwhethertheconditionistruetonot.In‘if’statement,onlytruepartsareincluded.Itisthefirstloopusedformakinganydecision.Iftheexpressionisevaluatedandifitistrue, then the statement following the ‘if’ is executed. If the expression is false, then the statement is skipped and execution is continued to the next statement.

A simple 'if' statement syntax can be written as:

if (condition)statement;

3.6 ‘If Else’ Statement‘If else’ statement is used to express decision regarding selection of particular condition. It is a general form of if statement.

‘if else’ statements include two parts: •true part �false part �

A simple if else statement syntax is written below:•

if ( expression ) statement 1else statement 2

In the above syntax, else part is optional.•The expression is evaluated, i.e.,•

if expression has a non-zero value, statement 1 is executed �if expression is considered false when the expression is zero �if there is else part, statement 2 is executed instead �

3.7 Switch StatementTo control complex conditional and branching operations, the switch statements are used. This statement transfers control to a statement within a switch body depending on the value of switch expression. The switch expression must evaluate an integral or enumeration value. Different conditions in the switch are called cases. The user can write the statement within those cases to get execute. These cases are broken or completed by the break keyword.The switch statement body contains case clauses which consists of:

a case label �an optional default label �a case expression �a list of statements �

The general form of writing a switch statement is as follows:

Switch (expression){ case value -1:

Page 38: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

28/JNU OLE

_ _ _ _ block of statements break; Case value -2: _ _ _ _ block of statements break; _ _ _ _ default: _ _ default block statements break;}

3.8 ‘If Else If Ladder’When there are multiple conditions to be checked, the ‘if else if ladder’ is used. For the condition to be in sequence, the user can put multiple if’s with else. The general form of ‘if else if ladder’ is:

if (condition1){ _ _ _ _} Else if (condition 2){ _ _ _ _}Else _ _ _ _}

3.9 Nested If‘Nested if’ statements are used when multiple conditions are introduced in a particular sequence.

The general form if nested if is:if (condition1) outer if loop{ if (condition 2) inner if loop { _ _ _ _ } else else of inner else { _ _ _ _ } inner else loop closing} closing of outer if else else of outer loop

Page 39: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

29/JNU OLE

{ _ _ _ _}

3.10 Iteration StatementDepending on the value of an integer expression, iterative statements repeat the execution of the list of the statements. These can be represented in the manner written below.

While ( <integer expression> ) { <statement list>}

The representation above is a simple iteration statement syntax.

The statement list is executed repeatedly, as long as the integer expression is true, i.e. non zero. Whenever the integer expression is false, i.e. zero, the execution continues with the statement following the while statement and the statement list is skipped.

3.11 Nested For‘Nested for’ is used to put ‘for loop’ within ‘for loop’. Generally this form is used for complicated applications.

3.12 Goto StatementGoto transfers the control of the program from one statement to another.•Goto statement makes the program jump to a given label.•The goto statement is marked by a label statement.•It transfers control to a label.•Label is the name given to the particular section of given name.•

A simple goto statement syntax can be written as:

{ goto here /* . . */

Here: /*definethelabel‘here’*/ /* . . */}

Conditional and unconditional goto are the two types of goto statements used in a computer program.

3.12.1 Conditional GotoUnder certain conditional cases, the conditional goto is used to transfer the control of execution from one part of the program to the other part.

3.12.2 Unconditional GotoTo transfer the control from one part of the program to the other part without checking any conditions, unconditional goto is used.

Page 40: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

30/JNU OLE

SummaryControlstatementsarethestatementsin‘C’languagethatcanaltertheflowofasequenceofinstruction.These•statements enable the user to jump from one program to another.‘If’statementisusedinmakingadecisionandallowingtheflowofexecutionofaprogram.•‘If else’ statement is used to express decision.•The ‘while’ statement can terminate when ‘break’, ‘goto’ or ‘return’ like statement body is executed.•The ‘do while’ loop tests at the bottom of the loop after executing the body of the loop.•The ‘for’ loop provides a more concise loop control structure.•Goto statement makes the program jump to a given label.•

ReferencesAshok, K., 2010. • C Programming: Test Your Skills, Pearson Education India.Ackermann, C. E., 1989. • The Essentials of C Programming Language, Research & Education Assoc.Control Statements • [Pdf] Available at: <http://download.nos.org/srsec330/330L9.pdf> [Accessed 26 June 2013].Program Control Statements• [Pdf] Available at: <http://www.uotechnology.edu.iq/dep-eee/lectures/1st/Computer%20science/2.pdf> [Accessed 26 June 2013].ControlStatementsinProgrammingLanguages(final)part1• [Video online] Available at: <http://www.youtube.com/watch?v=hX0Rrq8ouxY> [Accessed 26 June 2013].Control statements in programming languages-part 1-pldc• [Video online] Available at: <http://www.youtube.com/watch?v=ageuh_4_J9E> [Accessed 26 June 2013].

Recommended ReadingBalagurusamy, E., • Programming In Ansi C, 5E, Tata McGraw-Hill Education.Krishnamoorthy, 2010. • DATASTRUCTURESUSINGC, Tata McGraw-Hill Education.Hanly, 2009. • ProgrammingInCAndDataStructures(ForJntu), Pearson Education India.

Page 41: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

31/JNU OLE

Self Assessment__________ statement is often used in making a decision and allowing the execution of a program.1.

if else a. do whileb. do c. ifd.

The __________ loop tests at the bottom of the loop after executing the body of the loop.2. switcha. gotob. do while c. continued.

‘While’ statement is the simplest of all __________ structures.3. loopinga. controlb. programmingc. data typed.

Which of the following statements is true?4. do while statements enable the user to jump from one program to another.a. control statements enable the user to jump from one program to another.b. while statements enable the user to jump from one program to another.c. goto statements enable the user to jump from one program to another.d.

Which of the following statements is true? 5. The goto statement is marked by a control statement.a. The control statement is marked by a goto statement.b. The do while statement is marked by a label statement.c. The goto statement is marked by a label statement.d.

Which of the following statements is true? 6. if else statement is not used to express decision.a. if else statement is used to express decision.b. goto statement is used to express decision.c. control statement is used to express decision.d.

Which of the following statements is true?7. break statements are not used with switch statements.a. control statements are generally used with switch statements.b. break statements are generally used with switch statements.c. break statements are generally used with goto statements.d.

Page 42: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

32/JNU OLE

Which statement is the simplest of all looping structures?8. while statementa. do while statementb. switch statementc. goto statementd.

What provides a more concise loop control structure? 9. switch statementa. beak statementb. goto statementc. for loopd.

On what do the iterative statements depend to repeat the execution of the list of the statements?10. Case labela. Default case labelb. Integer expressionc. Case expressiond.

Page 43: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

33/JNU OLE

Chapter IV

Arrays and Strings

Aim

The aim of this chapter is to:

explain the data type array and strings•

explicate function of arrays and strings•

enlist elements of multidimensional array•

Objectives

The objectives of this chapter are to:

explain array and string functions•

definearrayandstrings•

explicate elements of multidimensional array•

Learning outcome

At the end of this chapter, you will be able to:

defineanddescribearray•

definearrayfunctions•

understand strings•

Page 44: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

34/JNU OLE

4.1 IntroductionArray type is a data type. It is a variable that holds multiple elements which has the same data type.•Itisthecapabilitythatenablestheusertodefineasetofordereddataitems.•In ‘C’ language, collection of the variables or values are selected by one or more indices those can be computed •by the computer by its run time. Such collection is called an array variable, array value or array.Variables are called grades in ‘C’ language. These grades represent the entire set of grades and not a single •value of grade.Each element of the set is referred by the index number or subscript.•

4.2 Declaration of An ArrayAn array must be declared before they are used like any other variable.•Anarraycanbespecifiedbyitsname,datatypesuchasint,float,char,andthesizeindicatesthenumberof•element that can be stored inside the array.A simple array syntax is mentioned below:•

data_type array_name[size]

4.3 Initialisation of ArrayThe elements can be initialised in an array in the same way as in any other ordinary variables when they are •declared.While initialising an array, the user has to provide initialising values which are enclosed by the curly brackets •in the declaration followed by an equal sign after the array name.General form of initialising an array is given below:•

type array_name [size] = (list of values)

The values in the list can be separated by commas. (Refer to the representation given below:)

int number [3] = {0, 0, 0};

The digit 3 denotes the array size whereas, 0 denotes the number of the values of each element in the list which •are less than the number of elements. Only in such a case, many elements can be initialised and the remaining elements will be set to 0 automatically.The compiler allocates enough space for all initialised elements when the size is omitted.•

Example:

Int counter [] = {1, 1, 1, 1};

4.3.1 Drawbacks of Initialising An Array

There is no convenient way by which the user can initialise only selected elements.•There is no shortcut method by which the user can initialise large number of elements.•

4.4 Dimensions of An ArrayArraysareclassifiedintothreetypesasfollows:

single dimensional array �two dimensional array �multidimensional array �

Page 45: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

35/JNU OLE

4.4.1 Single Dimensional Arrays

It is the collection of multiple elements of the same data type.•A number of location gets created where we get access to all the elements one by one.•

4.4.1.1 Declaration of Single Dimensional Arrays

Declaration of a single dimensional array in the program is in declaration section i.e., the section where we •declare the variables.Specifyingthedatatypeoftheelementswhicharegoingtobestoredinanarrayisthefirstrequirementwhile•declaring single dimensional array.Another important thing while declaring an array is to specify the name of the array.•Declaring its size is equally important. Size is the number of locations which we would like to reserve for the •array.Thesizevalueiscalledthesubscriptnumberwhichdefinesthemaximumnumberofelementsallowedtobe•stored in an array.General syntax for declaring one dimensional array is:•

Data type array_name [subscript number]

4.4.1.2 Initialisation of One Dimensional Array

Array location gets stored with garbage memory when array is declared in the memory.•In the locations of array, the garbage value gets stored automatically.•When the arrays are declared it is very important to initialise them.•The general form in which array elements are initialised is given as:•

type array-name[size] = {list of values}

4.4.2 Two Dimensional Arrays

Two dimensional arrays are also called multidimensional arrays.•To store the tabular data, two dimensional arrays are used.•We need more powerful array to store the data when the data is in the form of rows as well as columns.•Thenumberofrowsandcolumnsarespecifiedintwodimensionalarrays.•Usually, there is a need to store and manipulate two dimensional data structure matrices and tables.•These are stored in row major order.•Multidimensional arrays are the single dimensional arrays whose elements itself are arrays.•The general form of two dimensional arrays is given below:•

data type array_name [rows] [columns]

Theabovesyntaxdefinestwodimensionalarrayswhererowsandcolumnareconstants.•'Array2d' is an array of length denoting the ROWS and ‘int’ denoting COLUMNS.•

Page 46: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

36/JNU OLE

4.4.2.1 Elements of Multidimensional Array

Marks [0][0]35.5

Marks [0][1]40.5

Marks [0][2]45.5

Marks [1][0]50.5

Marks [1][1]55.5

Marks [1][2]50.5

Marks [2][0] Marks[2][1] Marks [2][2]Marks [3][0] Marks[3][1] Marks [3][2]

Table 4.1 Elements of multidimensional array

4.4.2.2 Initialisation of Multidimensional ArrayThe two dimensional arrays may be initialised by following their declaration with the list of initial values in the braces like the one dimension arrays.Example:

int table [2] [3] = { 0, 0, 0, 1, 1, 1 }

Intheaboveexample,thearrayinitialisestheelementsofthefirstrowtozeroandthoseinthesecondrowto1.The initialisation is done row by row.The above statement can also be written in the form of:

int table [2] [3] = { {0, 0, 0 } , {1, 1, 1} }

4.5 StringsIn ‘C’ language, strings are the arrays of ‘char’ object. In otherwords, these are defined as the arrays of•characters.An array of string can be declared like a two dimensional array.•Thestringcharactersarecompiledtoanarrayofspecificcharactervaluewithanadditionalnullterminating•character code, which has a value 0 to mark the end of the string. These string constants are surrounded by double quotes (“).Backslash escape [\ n] may be used to include a newline in strings.•

Escape Meaning\ \ Literal backslash\ “ Double quote\ ‘ Single quote\ n Newline\ r Carriage return\ b Backspace\ t Horizontal tab\ f Form feed\ a Alert\ v Vertical tab\ ? Question mark\ nnn Character with octal value nnn\ xhh Character with hexadecimal value hh

Table 4.2 Backslash escape

Page 47: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

37/JNU OLE

4.5.1 String Functions

strcat (dest, source) Appends the string ‘source’ to the end of the string ‘dest’

Strchr (s, c) Findsthefirstinstanceofcharacter‘c’instring‘s’andreturnsapointertoitoranull pointer if ‘c’ is not found

Strcmp (a, b) Compares string a and b, returns negative if a is less than b, 0 is equal, positive if greater

Strcpy (dest, source) Copies the string ‘source’ onto the string ‘dest’

Strlen (st) Return the length of string ‘st’

Strncat (dest, source, n)Appends a maximum of ‘n’ character from the string ‘source’ to the end of string ‘dest’ and null terminates the string at the end of the input or at index’ n+1 when the max length is reached

Strncmp (a, b, n) Compares maximum of ‘n’ characters from strings ‘a’ and ‘b’; returns negative if ‘a’ is less than ‘b’, 0 if equal and positive if greater.

Strrchr (s, c) Find the last instance of character ‘c’ in string ‘s’ and returns a point to it or a null pointer if ‘c’ is not found

Strcoll (s1, s2) Comparetwostringsaccordingtoalocale-specificcollatingsequence

Strcspn (s1, s2) Returnstheindexofthefirstcharacterin‘s1’thatmatchesanycharacterin‘s2’

Strerror (errno) Returns a string with an error message corresponding to the code in errno

Strncpy (dest, source, n) Copies ‘n’ character from the ‘source’ onto the string ‘dest’, substituting null byte once past the end of ‘source’; does not null terminate if max length is reached

Strpbrk (s1, s2) Returnsapointertothefirstcharacterin‘s1’thatmatchesanycharacterins2oranull pointer if not found

Strspn (s1. s2) Returnstheindexofthefirstcharacterin‘s1’thatmatchesnocharacterins2

Strstr (st, subst) Returnsapointertothefirstoccurrenceofthestring‘subst’inSt’ or a null pointer if no such substitute exists

Strtok(s1, s2) Returns a pointer to a token within ‘s1’ delimited by the character in ‘s2’

Strxfrm(s1, s2, n) Transforms ‘s2’ onto ‘s1’, such that ‘s1’ used with ‘strcmp’ gives the same results as ‘s2’ used with ‘strcoll’

Table 4.3 String functions

Page 48: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

38/JNU OLE

4.6 Passing Array to FunctionsArray elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function. These two calls are illustrated below:

/*Demonstration of call by value */main ( ){ int i : int marks {} = { 55, 65, 75, 56, 78, 78, 90 } ; for(i=0;i≤6;i++)}

display ( int m ){ print ( “%d”, m ) ;}

The output is,55 65 75 56 78 78 90

Page 49: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

39/JNU OLE

SummaryArray is a variable that holds multiple elements which has the same data type.•Array must be declared before they are used like any other variable.•While initialising an array the user has to provide initialising values which are enclosed by the curly brackets •in the declaration followed by an equal sign after the array name.Multidimensional array is the array with more than one index value.•Strings are the arrays of ‘char’ object.•

ReferencesHoover, 2009. • SystemProgrammingWithCAndUnix, Pearson Education India.Laitinen, K., 2004. • ANaturalIntroductiontoComputerProgrammingwithC#, Trafford Publishing.ArraysandStrings• [Pdf] Available at: <http://pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/10-ArraysAndStrings.pdf> [Accessed 26 June 2013].Lecture 7:Arrays, strings, and functions• [Pdf] Available at: <http://www.stanford.edu/~fringer/teaching/operating_systems_03/handouts/lecture7.pdf> [Accessed 26 June 2013].CProgrammingTutorial:Arrays(OneandTwoDimensionalArray):Lesson2• [Video online] Available at: <http://www.youtube.com/watch?v=NFJMjgXb0uA> [Accessed 26 June 2013].C Programming Tutorial 44 - Strings and Characters• [Video online] Available at: <http://www.youtube.com/watch?v=EJBb8nQD-4g> [Accessed 26 June 2013].

Recommended ReadingMalik, D. S., 2012. • C++Programming:FromProblemAnalysistoProgramDesign, 6th ed.: From Problem Analysis to Program Design, 6th ed., Cengage Learning.Lafore, 2002. • Object Oriented Programming In C++, 4/E, Pearson Education India.Malik, D. S., 2009. • C++ Programming: Program Design Including Data Structures: Program Design Including Data Structures, 4th ed., Cengage Learning.

Page 50: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

40/JNU OLE

Self AssessmentVariables are called __________ in ‘C’ language.1.

groupsa. gradesb. loopsc. arraysd.

data_type array_name[size] is an __________.2. initialisation array syntaxa. array syntaxb. declaration array syntaxc. multidimensional array syntaxd.

The multidimensional array is stored in __________.3. column major ordera. rowsb. columnsc. row major orderd.

Which of the following statements is true? 4. Type array_name [size] = (list of values) is a general form of initialisation of an array.a. Type array_name [size] = (list of variables) is a general form of initialisation of an array.b. Type array_name [ ] = (list of values) is a general form of initialisation of an array.c. Type array_name [ ] = (list of variables) is a general form of initialisation of an array.d.

Which of the following statements is true? 5. \ xhh is the meaning of the character with decimal value hh.a. \ xhh is the meaning of the character with hexadecimal value h.b. \ xhh is the meaning of the character with hexadecimal value hh.c. \ xhh is the meaning of the character with decimal value hhh.d.

Which of the following statements is true? 6. Stringsarethearraysof‘float’object.a. Strings are the arrays of ‘char’ object.b. Strings are the arrays of ‘int’ object.c. Strings are the arrays of ‘void’ object.d.

Which of the following statements is true? 7. While declaring an array the user has to provide initialising values which are enclosed by the curly brackets a. in the declaration followed by an equal sign after the array name.While initialising an array the user has to provide declaring values which are enclosed by the curly brackets b. in the declaration followed by an equal sign after the array name.While initialising an array the user has to provide initialising variable and values which are enclosed by the c. curly brackets in the declaration followed by an equal sign after the array name.While initialising an array the user has to provide initialising values which are enclosed by the curly brackets d. in the declaration followed by an equal sign after the array name.

Page 51: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

41/JNU OLE

What is the meaning of the escape \ n? 8. horizontal taba. vertical tabb. newlinec. double quoted.

Identify multidimensional array syntax.9. floatarray2d[ROWS][COLUMNS];a. int array2d [ ROWS ] [ COLUMNS ] ;b. void array2d [ ROWS ] [ COLUMNS ] ;c. int arrad [ ROWS ] [ COLUMNS ] ;d.

What is the meaning of the escape ( \ “ ) ?10. double quotea. single quoteb. backslashc. newlined.

Page 52: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

42/JNU OLE

Chapter V

Functions and Structures

Aim

Aim of this chapter is to:

explain functions•

explicate the uses of functions•

elucidate the function properties•

Objectives

The objectives of this chapter are to:

explain the concept of recursion•

explicate functions and structures•

enlist various function categories•

Learning outcome

At the end of this chapter, you will be able to:

understand function and function properties•

describe structures in detail•

understand how to declare functions•

Page 53: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

43/JNU OLE

5.1 Introduction to FunctionsIn ‘C’ language, ‘functions’ is one of the most useful features. It is a sub program or set of instructions, which •is used to write a particular task. The functions like printf( ), scanf( ), etc. are used in C program.Whenafunctionbodyiswritten,wecallitafunctiondefinition.Writingofinstructionswhichperformrequired•actionsintheprogramareincludedinfunctiondefinition.Whenaprogramislargeanddifficulttodebugortest,theprogramisdividedintosubprogramsandcompiled•separately to make the task easier.Programs become logical and user friendly due to functions.•We can call a function many times in the same program or in the external program which helps in avoiding the •repetitions of the code. But the procedure of writing a code is done only once.A function is a self contained block of statements that performs a coherent task of some kind.•Every ‘C’ program can be thought of as a collection of these functions.•

5.2 Uses of FunctionsWriting functions avoid rewriting the same code over and over. Consider if you have a section of code in your •program that calculates area of a triangle. If you want to calculate the area of a different triangle later in the program, it won’t require writing the same instructions all over again. Instead, you would prefer to jump to a ‘section of code’ that calculates area and then jump back to the place from where you left off. This section of code is nothing else but a function.With the use of functions it becomes easier to write programs and keep track of what they are doing. If the •operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separate the code into modular functions to make the program easier to design and understand.

5.3 Elements of User Defined FunctionsWeneedtowritesomestepsforwritingtheuserdefinedfunctions.Whileincludingthesefunctionsintheprogram,the following three sections are mainly used:

Function declaration•Function call•Functiondefinition•

5.3.1 Function Declaration

Function declaration is very similar to variable declaration.•Whentheuserisinneedofsomevariablesintheprogram,thefirststepistodeclarethem.Likewise,ifwe•need functions, we have to declare them.Generally function can be declared above main ( ) or in the main ( ). Global functions are the functions that are •declared above the main ( ) as they are accessible throughout the program and the functions those declared in the main ( ) are accessible only to main ( ).The general form in which the function is declared is given below,•

data type function-name (data types of arguments)

Any‘C’function,bydefaultitreturnsan‘int’value.Morespecifically,wheneveracallismadetoafunction,•the compiler assumes that this function would return a value of the type ‘int’. If we desire that a function should return a value other than an ‘int’, then it is necessary to explicitly mention so in the calling function as well as in the called function.

Page 54: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

44/JNU OLE

Supposewewanttofindoutsquareofanumberusingfunction,considerfollowingsimpleprogram.•

main ( ){ floata,b;

printf ( “\nEnter any number” ) ; scanf ( “%f”, &a ) ;

b = square ( a ) ; printf ( “\nSquare of %f is %f”, a, b ) ;}

square(floatx){ floaty;

y = x * x ; return ( y ) ;}

The sample runs of this program are mentioned below:Enter any number - 3Square of 3 is 9.000000

Enter any number 1.5Square of 1.5 is 2.000000

Enter any number 2.5Square of 2.5 is 6.000000

Thefirstansweramongthethreeiscorrect.Thesquareof1.5isdefinitelynot2,noris6asquareof2.5.Thishappened because any ‘C’ function, by default, which always returns an integer value. Therefore, even though the function ‘square ( )’ calculates the square of 1.5 as 2.25, the program crops up when this 2.25 is to be returned to ‘main()’.‘Square()’isnotcapableofreturninga‘float’valuetoovercomethis.Letusconsiderthefollowingprogramsegmenttoillustratehowtomake‘square()’capableofreturninga‘float’value.

main ( ){ floatsquare(float); floata,b printf ( “\nEnter any number” ) ; scanf ( “%f”, &a ) ;

b = square ( a) ; printf ( “\nSquare of %f is %f”, a, b ) ;}

floatsquare(floatx);{ floaty; y = x * x ;

Page 55: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

45/JNU OLE

return ( y ) ;}

The output is, Enter any number - 1.5 Square of 1.5 is 2.250000

Enter any number - 2.5 Square of 2.5 is 6.250000

Now the expected answers are, 2.25 and 6.25. Note that the function ‘square ( )’ must be declared in ‘main ( )’ as,floatsquare(float);

This statements is often called a prototype declaration of the ‘square ( )’ function. What it means is ‘square ( )’ is afunctionthatreceivesa‘float’andreturnsa‘float’.Wehavedonetheprototypedeclarationin‘main()’becausewe have called it from ‘main ( ). There is a possibility that we may call ‘square ( )’ from several other functions at the beginning of the program.

5.3.2 Function Call

Calling a function in the program by writing the function name and if necessary by passing the argument is •called function call.We can store the return value in the variable which is of the same data type compared to the return value only •if the function is returning any value.Printing the value directly is another option that can be used.•The arguments are called as actual arguments, when the user passes the variable to the function call.•General form for calling the function is given below:•

function-name (list of actual arguments)

Function call is of two types. These are:•call by value �call by reference �

5.3.2.1 Call by Value

When we call function by passing normal values or variables, the function call is called call by value.•Valuesmaygetconflictedorinterchangedincomplicatedandlargeprogramsmakingitisriskytocallfunction•by values.Memory is wasted in call by value.•

5.3.2.2 Call by Reference

If we pass the reference of variables or values at the time call instead of passing variables or values, then function •call is called call by reference.The reference is the address of the variables stored in the memory.•As the program is complicated, there is no risk when functions are called by passing the address of the •variables.As new variables are not created, call by reference does not waste memory.•Callbyreferenceworksmoreefficientlythancallbyvalue.•

Page 56: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

46/JNU OLE

5.3.3 Function Definition

Theactualstatementsthataretobeexecutedareincludedinthefunctiondefinition.•Afterthecompletionofmain()function,thefunctiondefinitionisdone.•

5.4 Scope and Lifetime of VariablesA period in which the variables hold the given value at the time of program execution is called lifetime of •variables.There are two types of variables, which include:•

global variables – available throughout the program �local variables – accessible by the functions in which they are declared �

5.4.1 Automatic Variables

Automatic variables are declared in the function in which they are utilised.•They are known as local variables.•When the function is called, they get created and when the function execution gets over, they get destroyed.•We can declare variables of same name in different functions in the same program.•As these variables are declared in the particular functions, the compiler never gets confused. So the scope is •within the function where they are declared.The lifetime of variables is similar to lifetime of their functions.•The values of these variables cannot be changed accidentally.•The local variables are automatic by default.•

5.4.2 External Variables

These are the global variables.•They are declared above the main ( ) and are accessible to all functions in the program.•The lifetime and scope is throughout the program.•This function can be used by any program and can be manipulated whenever required.•

5.4.3 External Declaration

The external declaration can be declared in both, the main ( ) as well as above main ( ).•It has a global storage class.•While declaring this variable, ‘extern’ is the keyword that is used.•The general form to declare this variable is given below:•

main ( ){ externfloatamt; _ _ _ _}fun1( ){ externfloaty://declarations _ _} floaty; //definition

Page 57: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

47/JNU OLE

5.4.4 Static Variables

Static variables are the one whose value persists till the end of the program.•Using the static keyword the declaration of the variable is used.•The general form of variable declaration is as follows:•

static int i;static float j;

Static variable can be either internal or external.•Internal static variable is same as variable type auto.•The static internal variable remains alive till the end of the program, is the only difference between the internal •static variable and the variable type auto.

5.4.5 Register Variables

Register is the temporary memory which is attached to the CPU.•If a keyword ‘register’ is given to declare the variables then it stores the variables in the machine’s register •instead of storing variables in the normal memory.The speed of the accessing variable becomes faster if we store the data in the register. It usually accepts ‘int’ or •‘char’ types of variables in the register type of values.These are generally used for loop to run the program or loop fast.•

5.5 Return ValuesThese are the values which are returned by the function to the calling function.•The function which calls a function is called calling function.•Just a simple return statement passes control of called function to the calling function.•The general form of return statement is as follows:•

returnor

return (expression)

5.6 Function CategoriesThe functions are categorised on the basis of return values and passing arguments.

functions with no arguments and no return values•functions with arguments and no return values•functions with no arguments but return values•functions with arguments and return value•

5.6.1 Functions with No Arguments and No Return ValuesThe function with no arguments and no return value is the function which does not return any value and to which we do not pass any arguments.

Page 58: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

48/JNU OLE

5.6.2 Functions with Arguments and No Return Values

Thecalledfunctionreceivestheactualargumentsthatwepassinitsdefinitionasformalparameters.Butnoout•put or return values are given to the calling function by the called function.The compiler omits or discards extra formal or actual parameters if the number of actual parameters should be •equal to formal parameters. The type of the data of both the parameters should be same.This concept can be implemented in programs. Arguments can be variables of any data type like ‘char’, ‘int’, •‘float’,‘double’oranarrayorpointer.

5.6.3 Functions with No Arguments and Return ValuesThe functions with no arguments and return value are the functions which do not accept arguments but returns the value.

5.6.4 Functions with Arguments and Returning ValuesThis function returns a value of required data type.

5.7 RecursionA function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circulardefinition’,recursionisthustheprocessofdefiningsomethingintermsofitself.Example,main ( ){ int a, fact ;

printf ( “\nEnter any number” ) ; scanf ( “%d”, &a ) ;

face = factorial ( a ) ; printf ( “Factorial value = %d”, fact ) ;}

factorial ( int x ){ int f = 1, i ;

for(i=x;i≥1;i--) f = f * i ;

return ( f ) ;}The output is,Enter any number - 3Factorial value = 6

5.8 Introduction to StructureStructure allows the user to club different data types together. It allows the user to declare different variables •of different types and use them with the same name of the structure.A structure contains a number of data types grouped together. These data types may or may not be of the same •type.

Page 59: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

49/JNU OLE

Consider the example,main ( ){ struct book { char name ; floatprice; int pages ;} ;struct book b1, b2, b3 ;

printf ( “\nEnter names, prices & no. Of pages of 3 books\n” ) ;scanf ( “%c %f %d”, &b1.name, &b1.price, &b1.pages ) ;scanf ( “%c %f %d”, &b2.name, &b2.price, &b2.pages ) ;scanf ( “%c %f %d”, &b3.name, &b3.price, &b3.pages ) ;

print ( “\nAnd this is what you entered” ) ;print ( “\n%c %f %d”, b1.name, b1.price, b1. Pages ) ;print ( “\n%c %f %d”, b2.name, b2.price, b2. Pages ) ;print ( “\n%c %f %d”, b3.name, b3.price, b3. Pages ) ;}

Here, the output is,Enter names, prices and no. of pages of 3 books A 100.00 354 C 256.50 682 F 233.70 512

And this is what you entered, A 100.000000 354 C 256.500000 682 F 233.700000 512

This program demonstrates two fundamental aspects of structures. These are:Declaring of a structure•Accessing of structure elements•

5.8.1 Declaring of a Structure

The closing brace in the structure type declaration must be followed by a semicolon.•It is important to understand that a structure type declaration does not tell the compiler to reserve any space in •memory.Allastructuredeclarationdoesis,itdefinesthe‘form’ofthestructure.Usuallythestructuretypedeclarationappearsatthetopofthesourcecodefile,beforeanyvariablesorfunctions•aredefined.Inverylargeprograms,theyareputinaseparateheaderfile,andthefileisincluded(usingthepre-processor directive #include) in whichever program we want to use this structure type.

5.8.2 Accessing Structure Elements

Having declared the structure type and the structure variables, let us discuss how the elements of the structure •can be accessed.In arrays, we can access individual elements of an array using a subscript. Structures use a different scheme. They •useadot(.)operator.Sotoreferto‘pages’ofthestructuredefinedinoursampleprogramwehavetouse,

b1.pagesSimilarly, to refer to ‘price’ we have to use,•

b1.price

Page 60: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

50/JNU OLE

5.8.3 Process of Storing Structure ElementsWhatever be the elements of a structure, they are always stored in contiguous memory location.Consider following illustration,

/* memory map of structure elements */main ( ){ struct book { char name ; floatprice; int pages ; } ; struct book b1 = { ‘B’, 130.00, 550 } ;

printf ( “\nAddress of name = %u”, &b1.name ) ; printf ( “\nAddress of price = %u”, &b1.price ) ;printf ( “\nAddress of pages = %u”, &b1.pages ) ;}

Output of the program is,Address of name = 65518Address of price = 65579Address of pages = 65523

5.9 Array of StructuresStructure is the collection of different data types of elements.•Array of structures is used to store more than one record. This array gets continuously stored in the memory. •Access to this array becomes easy due to continuous storage.For loop can be used to access the structure elements.•Structure receives values into various structure elements and output is provided to these values.•Consider following illustration to understand how to use arrays in structures.•

/* usage of an array of structure */main ( ){ struct book { char name ; floatprice; int pages ; } ; struct book b[100] ; int i ;

for(i=0;i≤99;i++) { printf ( “\nEnter name, price and pages” ) scanf ( “%c %d”, &b[i].name, &b[i].price, &b[i].pages ) ;

Page 61: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

51/JNU OLE

} for(i=0;i≤99,i++) printf ( “\n%c %f %d”, b[i].name, b[i].price, b[i].pages ) ;}

linkboat ( ){ floata=0,*b; b = &a ; /* cause emulator to be linked */ a = *b ; /* suppress the warning – variable not used */}

5.10 Additional Features of StructuresThe values of structure variables can be assigned to another structure variable of the same type using the assignment operator.

main ( ){struct employee{ char name [10] ; int age ; floatsalary;} ;struct employee e1 = { “Sanjay” , 30,5500.50 } ;struct employee e2, e3 ; /* peice-meal copying */strcpy ( e2.name, e1.name ) ;e2.age + e1.age ;e2.salary = e1.salary ;

/* copying all elements at one go */e3 = e2 ;

printf ( “\n%s %d %f”, e1.name, e1.age, e1.salary ) ;printf ( “\n%s %d %f”, e2.name, e2.age, e2.salary ) ;}

The output of the program would be,• Sanjay, 30, 5500.500000 Sanjay, 30, 5500.500000 Sanjay, 30,5500.500000

Ability to copy contents of all structure elements of one variable into the corresponding elements of another •structure variable is rather surprising, since ‘C’ does not allow assigning the contents of one array to another just by equating the two.This copying of the structure elements at one go has been possible only because the structure elements are •stored in contagious memory locations. Had this not been so, the compiler would have been required to copy structure variable elements by elements.

Page 62: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

52/JNU OLE

5.11 Uses of Structureschanging the size of the structure•clearing the contents of the screen•placing the cursor at an appropriate position an screen•drawing any graphics shape on the screen•receiving a key from the keyboard•checking the memory size of the computer•findingoutthelistofequipmentattachedtothecomputer•formattingafloppy•hidingafilefromthedirectory•displaying the directory of a disk•sending the output to printer•interacting with the mouse•

5.12 UnionsLike structures, unions too contain the members whose individual data types may differ from one another. The unions are used to conserve memory since all members share the same storage area within the computer memory. They are useful for application that involves multiple numbers. Unions can be declared using the keyword union.

Page 63: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

53/JNU OLE

SummaryFunction is a sub program or set of instructions which is used to write a particular task.•Function declaration is very similar to variable declaration.•Calling a function in the program by writing the function name and if necessary by passing the argument is •called function call.When we call function by passing normal values or variables, the function call is called as call by value.•If we pass the reference of variables or values at the time call, instead of passing variables or values, then •function call is called call by reference.Global and local are the two types of variables.•Automatic variables are declared in the function in which they are utilised. They are known as local •variables.External variables are the global variables. They are declared above the main ( ) and are accessible to all •functions in the program.Static variables are the one whose value persists till the end of the program.•Register is the temporary memory which is attached to the CPU.•Return values are the values which are returned by the function to the calling function.•The function with no arguments and no return value is the function which does not return any value and to •which we do not pass any arguments.Thecalledfunctionreceivestheactualargumentsthatwepassinitsdefinitionasformalparameters.•The functions with no arguments and return value are the functions which do not accept arguments but returns •the value.Recursion is a function recursion when the function calls itself in its own body.•Structure allows the user to club different data types together.•Array of structures is used to store more than one record.•

ReferencesDeshpande, P. S. & Kakde, O. G., 2004. • C and Data Structures, Cengage Learning.Kernighan, W. B. & Ritchie, D., 1988. • C Programming Language, 2nd ed., Prentice Hall.Functions in C• [Pdf] Available at: <http://www.nada.kth.se/kurser/master/intro/Course03-04/Handouts/Flecture05.pdf> [Accessed 26 June 2013].DataStructuresUsingC• [Pdf] Available at: <http://www.gatesit.org/gitdownloads/C&DS.pdf> [Accessed 26 June 2013].C Programming Classes - Structure in C language • [Video online] Available at: <http://www.youtube.com/watch?v=Y_2DcVnOxPQ> [Accessed 26 June 2013].Functions in C Programming• [Video online] Available at: <http://www.youtube.com/watch?v=s7ZY1E4smqU> [Accessed 26 June 2013].

Recommended ReadingNair, 2009. • Data Structures In C, PHI Learning Pvt. Ltd.Puntambekar, A. A., 2008.• DataStructuresWithC, Technical Publications.Reddy, R. & Ziegler, C., 2009. • C Programming for Scientists and Engineers with Applications, Jones & Bartlett Learning.

Page 64: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

54/JNU OLE

Self AssessmentWhen we call function by passing normal values or variables, the function call is called __________.1.

call by referencea. call by valueb. call by variablec. referenced.

Array of structures is used to store more than ________ record.2. onea. threeb. twoc. fourd.

Recursion is one of the _________ properties.3. arraya. pointerb. functionc. variabled.

The __________ remains alive till the end of the program.4. static external variablea. internal variableb. static internal variablec. external variabled.

Which of the following statements is true?5. The function which calls a value is called call by value function.a. The function which does not calls a function is called calling function.b. The function which calls a reference is called call by reference function.c. The function which calls a function is called calling function.d.

Which of the following statements is true?6. A period in which the values hold the given variable at the time of program execution is called lifetime of a. variables.A period in which the variables hold the given value is called lifetime of variables. b. A period in which the variables hold the given value at the time of program execution is called lifetime of c. variables.A period in which the variables hold the given value at the time of program execution is called lifetime of d. values.

Which of the following statements is true?7. If we pass the reference of variables or values at the time call, instead of passing variables or values, then a. function call is called call by reference.If we pass the values of variables at the time call, instead of passing variables or values, then function call b. is called call by reference.If we pass the reference of variables or values at the time call, instead of passing functions, then function c. call is called call by reference.If we pass the reference of variables or values at the time call, instead of passing variables or values, then d. function call is called call by value.

Page 65: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

55/JNU OLE

What can be declared in both the main ( ) as well as above main ( )?8. internal declarationa. external declarationb. external valuesc. static variablesd.

Whichfunctionreceivestheactualargumentsthatwepassinitsdefinitionasformalparameters?9. Called functiona. Call by referenceb. Call by valuec. Global functiond.

Which functions are declared above the main ( ) as they are accessible throughout the program?10. Local functiona. Static functionb. Static internal functionc. Global functiond.

Page 66: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

56/JNU OLE

Chapter VI

Pointers

Aim

Aim of this chapter is to:

explain the concept of pointers•

explicate pointer declaration•

iexplain reference operator•

Objectives

The objectives of this chapter are to:

explain derefernce operator•

explicate pointer arithmetic•

elucidate callback functions•

Learning outcome

At the end of this chapter, the student will be able to:

definepointers•

understand pointer arithmatic•

describe pointer with function•

Page 67: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

57/JNU OLE

6.1 IntroductionPointer is a variable that stores a reference to another variable. It points a memory location in which data is •stored. In the computer, each memory cell has an address which can be used to access that location. Thus, the pointer variable points a memory location so that the user can access and make required changes in the content of the memory location using pointers.Thepointersareoneofthepowerfultoolsof‘C’programming.Theyareveryefficient.Therearemanyadvantages•of pointers as they save memory space and process the data very fast.Instead of referring values, we can refer to the addresses at which they are stored.•We are aware that the memory consists of millions of cells. Each cell has got its own address. We can access •these locations by either using variables or memory addresses. These addresses are nothing but the pointers.

6.2 Pointer DeclarationA pointer is a variable that contains the memory location of another variable.•

General pointer declaration syntax is,

type * variable name

Asterisk (*) tells the compiler that you are creating pointer variable.•The declaration tell the compiler to perform the following jobs:•

reserve space in memory to hold the integer value �associate the name ‘i’ with this memory location, if ‘int i = 3’ is considered �store the value 3 at this location �

6.3 Reference OperatorReference is a value that enables a program to access a particular data item indirectly such as, a variable or a •record in the computer memory or in some other storage device.Theamountofmemoryneededforitisassignedataspecificlocationinmemory,assoonasthevariableis•declared. The task of deciding the location of the variable within the panel of cells is automatically performed by the operating system during runtime.A reference is distant from data itself. A reference is the physical address of where the data is stored in memory or •in the storage device. Thus, a reference is often called a ‘pointer’ or ‘address’ and is said to ‘point to’ the data.The address that locates a variable within memory is what we call a reference to that variable.•Thereferencetoavariablecanbeobtainedbyprecedingtheidentifierofavariablewithanampersand(&)sign,•known as reference operator and can be translated as ‘address of’.

Example, A = &BHere, we would assign A as the address of variable B, since when preceding the name of the variable B with the reference operator (&) we are no longer talking about the content of the variable itself, but about its reference i.e., its address in memory.

Theconceptofreferencemustnotbeconfusedwithothervaluesnamely;identifiersorkeysthatuniquelyidentify•the data item, but give access to it only through a non-trivial lookup operation in some table data structure.The references are widely used in ‘C’ programming; especially pass large or mutable data as ‘arguments’ to •‘procedures’ or to share data among various uses.A reference may point to a variable or record that contains references to other data.•This idea is the basis of indirect addressing and of many linked data structures such as, linked lists.•

Page 68: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

58/JNU OLE

Referencesincreaseflexibilitywheretheobjectsarestored,howtheyareallocatedandhowtheyarepassed•between areas of code.We can access the data as long as we can access a reference to the data and the data itself need not be moved. •It also makes sharing of different codes easier, each keeps a reference to it.

6.4 Dereference OperatorDereference operator is also known as indirect operator, denoted by asterisk (*) sign.•It is a unary operator found in ‘C’ language which includes pointer variables.•It operates on a pointer variable and returns a 1-value equivalent at the pointer address. This is called dereferencing •the pointer.

Example of dereferencing a pointer,

int x = 0;int *pointer_to_x = &x;(*pointer_to_x) =+ 1;//x is now equal to 1

The above code increments the value ‘x’ by using the indirection operator and a pointer to the variable ‘x’.In ‘C’ language, the dereferencing operator can be used in compositions where multiple acts of dereferencing •are used.Pointer can refer other pointers and in such cases multiple applications of the dereference operator are •needed.The dereference operator on a pointer only works if the pointer has a pointee. The pointee must be allocated •and the pointer must be set to point to it.The most common error in pointer code is forgetting to set up the pointee.•The common runtime crash because of the error in the code is a failed dereferences operation.•

6.5 Pointer ArithmeticPointer variables can be used in expressions just like any other variables.•It is different to conduct arithmetic operations on pointers than to conduct them on regular integer data types.•Only addition and subtraction operations are conducted with them to begin with.•Addition and subtraction both have different behaviour with pointers according to the size of the data type to •which they point.

Example,

y = *p1 ** p2;sum = sum + * p1;z = 5 * - * p2/p1;*p2 = *p2 + 10;

‘C’languagesupportsfivearithmeticoperatorsonpointers.Thosearegivenbelow:•Increment (++) �Decrement (++) �Addition(+) �Subtraction (-) �Differencing �

Page 69: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

59/JNU OLE

6.5.1 Increment (++)Incrementofpointerdependsonthedatatypelike2for‘int’,4for‘float’.

6.5.2 Decrement (--)Decrementofpointeralsodependsonthetypelike2for‘int’,4for‘float’.

6.5.3 Addition (+) and Subtraction (-)‘C’ supports to add and subtract integer from pointer.

6.5.4 DifferencingSubtraction of two pointers is called as differencing.

Example,

#include<srdio.h>#include<conio.h>

Void main ( ){ int i [ ] = {4,5,21,7}, *pointer, j;

clrscr( ); pointer = & i; for (j = 1;j<=4;j++) { printf (“%d elelment of array=%d/n”,j,*pointer); pointer++; } for(j=4,j≥1,j--) { pointer --; printf(“%d element of array=d/n”,j,*pointer);\ } getch( )}

6.6 Pointers with FunctionIn function declaration, pointers are widely used. A complex function can be easily represented only with a •pointer.A function pointer is a variable that stores the address of a function that can later be called through that function •pointer. This is useful because functions encapsulate behaviour.For instance, every time the user need a particular behaviour such as drawing a line, instead of writing out a •bunch of code, all the user need to do is call the function.The syntax for the declaration of pointers to the function is given below,•

Return_type (*pointer_name) (variable1_type variable1_name, variable2_type variable2_name, variable3_type variable3_name......................);

Page 70: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

60/JNU OLE

Theusageofpointersinafunctiondefinitionisclassifiedintotwotypes.Thoseare:•Call by value �Call by reference �

6.6.1 Call by ValueWhen a function supports, a link is established between the formal and actual parameters. The value of actual parameters is stored in the temporary storage that is created.

6.6.2 Call by ReferenceWhen the user passes the address to a function, the parameters receiving the address should be pointers. The process where a calling function passes the address of the variables using pointers is known as call by reference. The function which is called by the reference can change the values of the variables used in the call.

6.6.3 Callback Functions

Another use for function pointers is to set up ‘listener’ or’ callback’ functions that are invoked when a particular •eventhappens.Thefunctioniscalled,anditnotifiesyourcodethatsomethingofinteresthastakenplace.For instance, most of the time the user will interact with a loop that allows the pointer to move and when the •user is writing a code for a graphical user interface(GUI), that redraws the interface.These operations are ‘events’ that may require a response that user’s program needs to handle.•

6.7 Function Pointer Syntax

void (*foo) (int);

Here, ‘foo’ is a pointer to a function taking one argument and an integer that returns void.

6.8. Reading Function Pointer Declaration

Void * (*foo) (int*) ;

Here, the key is to read inside-out; notice that the innermost element of the expression is ‘*foo’, otherwise it looks like a normal function declaration.

6.8 Initialising Function PointerTo initialise a function pointer, the user must give it the address of a function in the program.The syntax is like any other variable.

#include <studio.h>void my_int_func (int x){ printf ( “%d\n”, x);}int main ( ){ void (*foo) (int); /* the ampersand is actually optional */ foo = &my_int_func;

return 0;}

Page 71: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

61/JNU OLE

6.9 Using Function PointerTo call the function pointed to by a function pointer, the user has to treat the function pointer as if it were the name of the function the user wish to call. The act of calling it performs the dereference.

#include <stdio.h>void my_int_func (int x){ printf (“%d\n”, x);}

int main ( ){ void (*foo) (int); foo = &my_int_func;

/* call my_int_func foo (2);/* but if you want to, you may */return 0;}

6.10 Arrays and Pointer

Arrays have a strong relationship to pointers in ‘C’ language. The concept of arrays is very much bound to the •pointers.Theidentifierofanarrayisequivalenttotheaddressofitsfirstelement,whereasapointerisequivalenttothe•addressofthefirstelementthatitpointsto.Anarrayisverymuchlikeapointer.Theusercandeclarethearraysfirstelementasa[0]oras‘int’*abecause•a [0] is an address and *a is also an address, thus, the form of declaration is equivalent. The difference is that the pointer is a variable and appears on the left of the assignment operator.Consider,•

main( ){int a[100];/* A program to display the contents of array using pointer*/int i,j,n;printf (“\nEnter the elements of the array\n”);scanf (“%d”, &n);printf (“Enter the array elements”);for (I =0; I < n; I++)scanf (“%d”, &a[I] );printf (“Array elements are”)for (ptr = a, ptr< (a+n) ; ptr ++)printf (“Value of a[%d] = %d stored at address %u’, j+=, ptr);}

Page 72: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

62/JNU OLE

6.11 Array of PointersArray of pointers is formed by declaring its capacity with it.Array of pointer can be declared as below,Data type *arr-name[size] ;Example,char name [3] = { “Nasik”, “Mumbai”, “Pune” }This declaration will create array of pointer of exact required size. We can access these elements to print.

6.12 Pointers with StructuresPointerscanbedeclaredbystructuretype.The‘≥’signisusedtopointthemembersofthestructure.The general form of declaring a pointer to the structure is,

struct struct-name{ variables - - -} ;struct *ptr ;

6.13 Pointers on PointerWhen the “pass by pointer” is used to pass a pointer to a function, only a copy of the pointer is passed to the function. In other words, “pass by pointer” is passing a pointer by value. In most cases, this does not present a problem. But problem comes when you modify the pointer inside the function. Instead of modifying the variable, the user has to modifyacopyofthepointerandtheoriginalpointerremainsunmodified.Thus,itstillpointstotheoldvariable.Consider,//global variableint g_One = 1; // function prototype

void func ( int* pInt);

int main ( ){ int nvar = 2; int* pvar = &nvar; func (pvar) std: : cout<<*pvar<<std: : end1; //will still show 2

return 0;}

void func (int* pInt){ pInt = &g_One;}

Page 73: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

63/JNU OLE

General syntax of pointer to pointer,

//function prototypevoid func (int++ ppInt);

int main ( ){ int nvar = 2 int* pvar = &nvar; func ( &pvar); . . . . . return 0;}

Page 74: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

64/JNU OLE

SummaryPointer is a variable that stores a reference to another variable.•Pointer points a memory location in which data is stored.•Reference is a value that enables a program to access a particular data item indirectly such as a variable or a •record in the computer memory or in some other storage device.Deference is a unary operator and is also known as indirect operator denoted by asterisk (*) sign.•Pointer variables can be used in expressions. These are known as pointer arithmetic.•Increment,decrement,addition,subtractionanddifferencingarethefivepointerarithmeticsupportedby‘C’.•A function pointer is a variable that stores the address of a function that can later be called through that function •pointer.When a function supports, a link is established between the formal and actual parameters which is known as •call by value.The process where a calling function passes the address of the variables using pointers is known as call by •reference.When the “pass by pointer” is used to pass a pointer to a function, only a copy of the pointer is passed to the •function.

ReferencesKenneth, R., 2007. • Pointers On C, Pearson Education India.Schultz, W. T., 2004. • C And The 8051, 3rd ed., PageFree Publishing, Inc.Jensen, T., 2003. • ATUTORIALONPOINTERSANDARRAYSINC [Pdf] Available at: <http://pdos.csail.mit.edu/6.828/2012/readings/pointers.pdf> [Accessed 26 June 2013].Lou, Y., 2011. • IntroductiontoCPointersandArrays [Pdf] Available at: <http://www.cs.cornell.edu/courses/CS2022/2011sp/lectures/lect04.pdf> [Accessed 26 June 2013].Pointers in c• [Video online] Available at: <http://www.youtube.com/watch?v=w2pbty8tLKU> [Accessed 26 June 2013].CProgrammingTutorial#21-ConceptofPointers-Part1[HD]• [Video online] Available at: <http://www.youtube.com/watch?v=rjo9rfRPQU4> [Accessed 26 June 2013].

Recommended ReadingPandey, M. H., 2009. • Trouble Free C, Laxmi Publications.Loudon, K., 2009. • MasteringAlgorithmswithC, O'Reilly Media, Inc.Parthasarthy, S., 2008. • Essentials Of Programming In C For Life Sciences, Ane Books Pvt Ltd.

Page 75: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

65/JNU OLE

Self Assessment________ is a variable that stores a reference to another variable.1.

Arraya. Pointerb. Functionc. Constantsd.

__________ tells the compiler that you are crating pointer variable.2. Asterisk (*)a. Ampersand (&)b. Backslash (\)c. Hash (#)d.

__________ is a value that enables a program to indirectly access a particular data item such as a variable or a 3. record in the computer memory or in some other storage device.

Call by referencea. Call by valueb. Referencec. Pointerd.

The__________isequivalenttotheaddressofitsfirstelement,whereasapointerisequivalenttotheaddress4. ofthefirstelementthatitpointsto.

identifierofapointera. identifierofanarrayb. identifierofaconstantc. arrayd.

Which of the following statements is true?5. Void (foo) (int); is function point syntax.a. Void (*foo) (*int); is function point syntax.b. Void (foo) (*int); is function point syntax.c. Void (*foo) (int); is function point syntax.d.

Which of the following statements is true?6. When the “pass by pointer” is used to pass a pointer to a function, only a copy of the pointer is passed to a. the function.When the “pointer” is used to pass a “pass by pointer” to a function, only a copy of the pointer is passed to b. the function.When the “pass by pointer” is used to pass a array to a function, only a copy of the pointer is passed to the c. function.When the “pass by array” is used to pass a array to a function, only a copy of the pointer is passed to the d. function.

Page 76: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

66/JNU OLE

Which of the following statements is true?7. Pointers are formed by declaring its capacity with it.a. Array and pointers is formed by declaring its capacity with it.b. Array of pointers is formed by declaring its capacity with it.c. Array is formed by declaring its capacity with it.d.

What is it called when a function supports and a link is established between the formal and actual 8. parameters?

Call by referencea. Pointerb. Call by valuec. Pass by pointerd.

Which sign is used to point the members of the structure?9. <a. ≥b. ≤c. >d.

What is the subtraction of two pointers is called?10. Differencinga. Incrementb. Decrementc. Addition and subtractiond.

Page 77: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

67/JNU OLE

Chapter VII

Dynamic Memory Allocation

Aim

The aim of this chapter is to:

introduce memory concepts•

explain stack and heap•

elucidate sizeof•

Objectives

The objectives of this chapter are to:

explain the purpose of managing strings with malloc ( )•

classify possible realloc ( ) outcomes•

defineworkingwithmemorysegments•

Learning outcome

At the end of this chapter, you will be able to:

distinguish between malloc ( ) and calloc ( )•

understand freeing memory•

explain random access memory•

Page 78: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

68/JNU OLE

7.1 IntroductionDynamic memory concepts, such as allocating, reallocating, and freeing memory using the functions like malloc (),calloc(),realloc(),andfree()arebasicconceptsinClibrary.Thechapterspecificallyreviewsessentialmemoryconcepts that directly relate to how these functions receive and use memory.

Software programs, including operating systems, use a variety of memory implementations, including virtual memory and RAM. Random access memory (RAM) provides a volatile solution for allocating, storing, and retrieving data. RAM is considered volatile because of its inability to store data after the computer loses power (shuts down). Another volatile memory storage area is called virtual memory. Essentially, virtual memory is a reserved section oftheharddiskinwhichtheoperatingsystemcanswapmemorysegments.Virtualmemoryisnotasefficientasrandom access memory, but it provides an impression to the CPU that it has more memory than it really does. Increasing memory resources through virtual memory provides the operating system an inexpensive solution for dynamic memory demands. Virtual memory increases the perception of more memory by using hard-disk space for swapping memory segments.

7.2 Stack and HeapUsing a combination of RAM and virtual memory, all software programs use their own area of memory called the stack. Every time a function is called in a program, the function’s variables and parameters are pushed onto the program’s memory stack and then pushed off or “popped” when the function has completed or returned. Used for storing variable and parameter contents, memory stacks are dynamic groupings of memory that grow and shrink as each program allocates and de allocates memory. After the software programs have been terminated, memory is returned for reuse for other software and system programs. Moreover, the operating system is responsible for managing this realm of unallocated memory, known as the heap. Software programs that can leverage memory allocating functions like malloc ( ), calloc ( ),and realloc () to use the heap. The heap is an area of unused memory managed by the operating system.

Once a program frees memory, it is returned back to the heap for further use by the same program or other programs. In a nutshell, memory allocating functions and the heap are extremely important to C programmers because they allow you to control a program’s memory consumption and allocation. The remainder of this chapter will deal with how to retrieve and return memory to and from the heap.

7.3 SizeofThere will be occasions when you need to know how large a variable or data type is. This is especially important inC, because C allows programmers to create memory resources dynamically. More specifically,itisimperativeforCprogrammerstoknowhowmanybytesasystemusestostoredata,suchasintegers,floats,ordoubles;becausenotallsystemsusethesameamountofspaceforstoringdata .The C standard library provides the sizeof operator to assist programmers in this type of situation. When used in the programs, the sizeof operator will help you build a more system-independent software program .The size of operator takes a variable name or data type as an argument and returns the number of bytes required to store the data in memory. The next program, and its output shown in Figure 7.1, demonstrates a simple use of the sizeof operator.

#include <stdio.h>main(){

intx;floatf;double d; char c;

typedefstruct employee {int id;

Page 79: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

69/JNU OLE

char *name;floatsalary;

} e;printf(“\nSize of integer: %d bytes\n”. sizeof(x )); printf(“Sizeoffloat:%dbytes\n”,sizeof(f));printf(“Size of double %d bytes\n”. sizeof(d ));printf( “Size of char %d byte\n”. sizeof(c));printf(“Size of employee structure: %d bytes\n”, sizeof(e));} //end main

Fig. 7.1 Using the sizeof operator to determine storage requirements

The sizeof operator can take either a variable name or a data type, as shown next.intx;printf(“\nSize of integer: %d bytes\ n”, sizeof(x)); //valid variable nameprintf(“\nSize of integer: %d bytes\n”, sizeof( int)) ; //valid data typeThe sizeof operator can also be used to determine the memory requirements of arrays.Using simple arithmetic, you can determine how many elements are contained in an array by dividing the array size by the size of the array data type, as demonstrated in the next program and its output in Figure 7.2.

#include <stdio.h>main(){ int array[1O]; printf(“ \nSize of array: %d bytes\n”, sizeof (array )) ; printf(“Number of elements in array “ ) ; printf(“ %d\ n”, sizeof (array ) / sizeof( int)) :

} //end main

Fig. 7.2 Using the sizeof operator and simple arithmetic to determine the number of elements in an array

Page 80: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

70/JNU OLE

7.4 Malloc()Sometimes it is impossible to know exactly how much memory the program will need for a given function. Fixed-sized arrays may not be large enough to hold the amount of data you are requesting to store. For example, what wouldhappenifyoucreatedaneight-element,fixed-sizecharacterarraytoholdauser’sname,andtheuserentersthe name “Alexandria” a 10-character name with an 11th character required for null.

Best-case scenario: You incorporated error checking in your program to prevent a user from entering a string larger than eight characters.

Worst-case scenario: The user’s information is sent elsewhere in memory, potentially overwriting other data.

There are many reasons for dynamically creating and using memory, such as creating and reading strings from standard input, dynamic arrays, and other dynamic data structures such as linked lists. C provides a few functions for creating dynamic memory, one ofwhich is the malloc() function. The malloc() function is part of the standard library <stdlib.h> and takes a number as an argument. When executed, malloc() attempts to retrieve designated memory segments from the heap and returns a pointer that is the starting point for the memory reserved. Basic malloc ()use is demonstrated in the next program.

#include <stdio.h>#include <stdlib.h>main( ){ char *name; name= malloc(80);} //end main

The preceding program’s use of malloc( ) is not quite complete because some C compilers may require that you perform type casting when assigning dynamic memory to a variable. To eliminate potential compiler warnings, we will modify the previous program to simply use a pointer oftype char in a type cast, as demonstrated next.

#include <stdio.h>#include <stdlib.h>main( ){ char *name; name -(char *) malloc(80);} //end main

The malloc ( )function returns a null pointer if it is unsuccessful in allocating memory.Better yet, we should be more specificwhencreatingdynamicmemorybyexplicitlytellingthesystemthesizeofthedatatypeforwhichwearerequesting memory. In other words, we should incorporate the sizeof operator in our dynamic memory allocation, as shown next.

#include <stdio.h>#include <stdlib.h>

main( ){ char *name; name = (char *} malloc(80 * sizeof(char));} //end main

Page 81: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

71/JNU OLE

Using the sizeof operator explicitly tells the system that you want 80 bytes of type char, which happens to be a 1-byte data type on most systems.

You should also always check that malloc( )was successful before attempting to use the memory. To test the malloc( )function’s outcome, simply use if condition to test for a NULL pointer, as revealed next.

#include <stdio.h>#include <stdlib.h>main(){ char *name; name- (char *} malloc(80 * sizeof(char)); if (name == NU LL ) printf(“\nOut of memory! \n”); else printf(“\nMemory allocated.\n”);

} //end main

After studying the preceding program, you can see that the keyword NULL is used to compare the pointer. If the pointer is NULL, the malloc() function was not successful in allocating memory. Always check for valid results when attempting to allocate memory. Failure to test the pointer returned by memory allocating functions such as malloc() can result in abnormal software or system behaviour.

7.4.1 Managing Strings with Malloc( )Dynamic memory allocation allows programmers to create and use strings when reading information from standard input. To do so, simply use the malloc ()function and assign its result to a pointer of char type prior to reading information from the keyboard.

Using malloc ()to create and read strings from standard input is demonstrated in the next program (see Figure 7.3).

#include <stdio.h>#include <stdlib.h>

main( ){ char *name; name = (char *)malloc(80*sizeof(char)); if (name != NU LL) { printf(“\nEnteryour name:” ); gets (name);

printf(“\nH1 %s\n”, name ); } // end if} //end main

Page 82: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

72/JNU OLE

Fig. 7.3 Using dynamic memory to read character strings from standard inputThis program allows a user to enter up to an 80-character name, the amount of storage requested by the malloc () function, for the character string.

7.5 Freeing MemoryGood programming practice dictates that you free memory after using it. For this reason, the C standard library offers the free ( ) function, which takes a pointer as an argument and frees the memory the pointer refers to. This allows your system to reuse the memory for other software applications or other malloc ( ) function calls, as demonstrated next.

#include <stdio.h>#include <stdlib.h>

main ( ){ char *name; name= (char *) malloc(80*sizeof ( char) ) ; if ( name != NULL ) { printf( “\nEnter your name: “); gets(name);

printf (“\nH1 %s\n”. name ) ; free(name); // free memory resources } // end if} // end main

Freeing memory allocated by functions such as malloc() is an important housekeeping duty of C programmers. Even with today’s memory-rich systems it’s a good idea to free memory as soon as you no longer need it because the more memory you consume the less that is available for other processes. If you forget to release allocated or usedmemoryinyourprograms,mostoperatingsystemswillcleanupforyou.Thisbenefit,however,onlyappliesafter your program terminates. It is the programmer’s responsibility, however, to free memory once it is no longer needed. Failure to release memory in your programs can result in unnecessary or wasted memory that is not returned to the heap, also known as a memory leak.

Memory allocated by malloc () will continue to exist until program termination or until a programmer “frees” it with the free ( ) function. To release a block of memory with the free() function the memory must have been previously allocated (returned) by malloc ( ) or calloc ().

7.5.1 Working with Memory SegmentsIndividual memory segments acquired by malloc ( ) can be treated much like array members; these memory segments can be referenced with indexes, as demonstrated in the next program.

Page 83: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

73/JNU OLE

#include <stdio.h>#include <stdlib.h>

main ( ){ int *numbers; int x;

numbers = (int *l malloc(5 * sizeof(int)); if ( numbers == NULL ) return; // return if malloc is not successful

numbers [O] = 100; numbers [1] = 200; numbers [2] = 300; numbers [3] = 400; numbers [4] = 500;

printf(“\nlndividual memory segments initialized to :\ n” ); for ( x = 0; x < 5; x++ ) printf(“numbers[%d] = %d\n”, x, numbers[x]);} // end mainSimply supply the pointer name with an index to initialize and access segments ofmemory. To reiterate, memory segments can be accessed via indexes similar to array elements. This is a useful and powerful concept for dissecting chunks of memory.

7.6 Calloc() and Realloc()Another memory allocating tool is the C standard library <stdlib.h> function calloc().Like the malloc()function, the calloc ()function attempts to grab contiguous segments of memory from the heap. The calloc () function takes twoarguments:thefirstdeterminesthenumberofmemorysegmentsneededandtheseconddealswiththesizeofthe data type.

A basic implementation of the calloc ()function is established in the next program.

#include <stdio.h>#include <stdlib.h>

main(){ int *numbers;

numbers = (int *) calloc( 10, sizeof(int )); if (numbers == NULL ) return;// return if calloc is not successful} //end main

We can use the calloc()function to obtain a chunk of memory to hold 10 integer data types by passing two arguments. Thefirstargumenttellscalloc()thatwewant10contiguousmemorysegmentsandthesecondargumenttellsCthatthe data types need to be the size of an integer data type on the machine it’s running.

Page 84: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

74/JNU OLE

Themainbenefitofusingcalloc()ratherthanmalloc()isthatcalloc()isabletoinitializeeachmemorysegmentallocated to it. This is an important feature because malloc () requires the programmer to be responsible forinitializing memory before using it.

Atfirstglance,bothmalloc()andcalloc()appeartobedynamicinmemoryallocation,andtheyaretosomedegree, yet they fall somewhat short in their ability to expand memory originally allocated. For example, say you allocatedfiveintegermemorysegmentsandfilledthemwithdata.Later,theprogramrequiresthatyouaddfivemore memory segments to the original block allocated by malloc() while preserving the original contents. This is an interesting dilemma. You could, of course, allocate more memory using a separate pointer, but that would not allow you to treat both memory blocks as a contiguous memory area and, therefore, would prevent you from accessing all memory segments as a single array. Fortunately, the realloc ( ) function provides a way to expand contiguous blocks of memory while preserving the original contents.

As shown next, the realloc ( ) function takes two arguments for parameters and returns a pointer as output.

newPointer = realloc (oldPointer, 10 * sizeof( int));realloc()‘sfirstargumenttakestheoriginalpointersetbymalloc()orcalloc().Thesecondargumentdescribes the total amount of memory you want to allocate.

Like the malloc ( ) and calloc ( ) functions, realloc ( ) is an easy-to-use function, but it requiressome spot-checkingafteritexecutes.Specifically,therearethreescenariosforrealloc()’soutcome,whichTable 7.1describes.

Scenario OutcomeSuccessful without move Same pointer returned

Successful with move New pointer returnedNot successful NULL pointer returned

Table 7.1 Possible realloc () Outcomes

If realloc () is successful in expanding the contiguous memory, it returns the original pointer set by malloc( ) orcalloc ( ). There will be times, however, when realloc ( ) is unable to expand the original contiguous memory and will, therefore, seek another area in memory where it can allocate the number of contiguous memory segments for both the previous data and th e new memory requested .When this happens, realloc ( ) copies the original memory contents into the new contiguous memory locations and returns a new pointer to the new starting location. Be aware that there will be times when realloc ( ) is not successful in any of its attempts to expand contiguous memory and ultimately will return a NULL pointer. Your best bet for testing the outcome of realloc ( ) is testing for NULL. If NULL pointer is not returned, you can assign the pointer back to the old pointer, which then contains the starting address of the expanded contiguous memory.

The concept of expanding contiguous memory and testing realloc()’s outcome is demonstrated in the next program, with the output shown in Figure 7.4.

#include<stdio.h>#include<stdlib.h>

main(){ int *number ; int *new Number; int x:

Page 85: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

75/JNU OLE

number = malloc(sizeof(int)* 5); if (number == NU LL ){ printf(“\nOut of memory !\n” ); return;} // end i fprintf(“\nOriginal memory:\n”};for ( x = 0; x < 5; x++ ) { number[x] = x * 100; printf(“number[%d ]= %d\n”, x , number[x]);} // end for loopnewNumber = realloc(number, 10 * sizeof(int));if (newNumber == NULL) { printf(“\nOut of memory!\n”) ; return;

}else number = newNumber;//intialize new memory onlyfor (x = 5: x < 10: x++ ) number[x] = x * 100;

printf(“\nExpanded memory:\n”);for (x = 0: x < 10; x++ ) printf (“number[%d] = %d\n”, x, number[x]);

// free memoryfree(number);

} // end main

Fig. 7.4 Using realloc () to expand contiguous memory segments

After studying the preceding program and Figure 7.4, you can see that realloc ()is quite useful for expanding contiguous memory while preserving original memory contents.

7.7 Chapter Program-Math QuizShown in Figure 7.5, the Math Quiz game uses memory allocation techniques, such as the calloc()and free( )functions, to build a fun and dynamic quiz that tests the player’s ability to answer basic addition problems. After studying the Math Quiz program, you can use your own dynamic memory allocation and random number techniques to build fun quiz programs of any nature.

Page 86: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

76/JNU OLE

Fig. 7.5 Using chapter based concepts to build the Math Quiz

All of the code required to build the Math Quiz game is demonstrated next.

#include <stdio.h>#include <stdlib.h>#include <time.h>

main(){int response;int *answer;int *op1;int *op2;char*result;int x;

srand (time(NULL));printf(“\nMath Qui z\n\n” );printf(“Enter #of problems: “);scanf(“%d”, &response);

/* Based on the number of questions the user wishes to take, allocate enough memory to hold question data. */

op1 = (int *) calloc (response, sizeof(int) );op2 = (int *) calloc (response, sizeof(int) );answer= (int *) calloc(response, sizeof(int));result = (char *) calloc(response, sizeof(char));

if ( op1==NU LL II op2 == NU LL II answer == NULL II result== NULL ) {printf(“\nOut of Memory !\n”);return:

} // end if//display random addition problemsfor (x = 0: x < response; x++) {op1 [x]= rand( ) % 100;op2 [x] =rand ()% 100;

printf(“\n%d + %d = “, op1[x], op2[x] );scanf(“%d”,&answer[x]);

Page 87: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

77/JNU OLE

if (answer[x] == op1 [x] + op2[x] )result[x] = ‘c’;elseresult[x] =’i’;} // endfor loopprintf(“\nQuiz Results\n”) ;printf(“\nQuestion\tYour Answer \tCorrect\n”) ;

//print the results of the quiz for ( x = 0; x < response; x++ ) {if ( result[x]== ‘c ‘)printf(“%d + %d\t\t%d\t\tYes\n”, op1[x], op2[x], answer[x ]);elseprintf(“%d + %d\t\t%d\t\tNo\n”,op1[x], op2[x], answer[x]);} //end for loop//free memory free(op1);free(op2);free(answer);free(result);

} // end main

Page 88: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

78/JNU OLE

SummaryRandom access memory (RAM) provides a volatile solution for allocating, storing, and retrieving data. RAM •is considered volatile because of its inability to store data after the computer loses power (shuts down).Virtualmemoryisnotasefficientasrandomaccessmemory,butitprovidesanimpressiontotheCPUthatit•has more memory than it really does.Another volatile memory storage area called virtual memory is a reserved section of the hard disk in which the •operating system can swap memory segments.Used for storing variable and parameter contents, memory stacks are dynamic groupings of memory that grow •and shrink as each program allocates and de-allocates memory.The heap is an area of unused memory managed by the operating system.•The sizeof operator takes a variable name or data type as an argument and returns the number of bytes required •to store the data in memory.The sizeof operator can also be used to determine the memory requirements of arrays.•The malloc() function attempts to retrieve designated memory segments from the heap and returns a pointer •that is the starting point for the memory reserved.The malloc() function returns a null pointer if it is unsuccessful in allocating memory.•Individual memory segments acquired by malloc() can be treated much like array members; these memory •segments can be referenced with indexes.The free () function takes a pointer as an argument and frees the memory the pointer refers to.•Like the malloc () function, the calloc ( ) function attempts to grab contiguous segments of memory from the •heap. Thecalloc()functiontakestwoarguments:thefirstdeterminesthenumberofmemorysegmentsneededand•the second is the size of the data type.Themainbenefitofusingcalloc()ratherthanmalloc()isthatcalloc()isabletoinitializeeachmemory•segment allocated to it.The realloc ( ) function provides a way to expand contiguous blocks of memory while preserving the original •contents.Dynamic memory allocation allows programmers to create and use strings when reading information from •standard input.Memory allocating functions and the heap are extremely important to C programmers because they allow you •to control a program’s memory consumption and allocation.

ReferencesPuntambekar, A. A.,• 2009. DataStructuresUsing‘C’, Technical Publications.Balagurusamy., 2011.• ComputerConcept&ProgrammingInC(ForUptu), Tata McGraw Hill Education Pvt. Ltd.Dr. Owen, C.B. • DynamicMemoryAllocation, [Pdf] Available at: <http://www.cse.msu.edu/~cse251/lecture14.pdf> [Accessed 4 June 2013]. Vine, M. 2007. • C Programming for the Absolute Beginner. [Pdf] Available at: <http://site.ebrary.com/lib/alltitles/docDetail.action?docID=10228219&ppg=272> [Accessed 5 June 2013]. 2012. • Dynamicmemoryallocation –malloc calloc realloc free. [Video online] Available at: <http://www.youtube.com/watch?v=xDVC3wKjS64> [Accessed 4 June 2013].2011. • Dynamic Memory Allocation. [Video online] Available at: <http://www.youtube.com/watch?v=Dml54J3Kwm4> [Accessed 4 June 2013].

Page 89: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

79/JNU OLE

Recommended ReadingPandey, H.M., 2009. • TroubleFreeC., University Science Press.Dixit, J.B., 2006. • ComprehensiveProgramminginCandNumericalAnalysis., Firewall Media Publications.Lichade, V. M., 2007.• C Programming., DreamTech Press.

Page 90: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

80/JNU OLE

Self AssessmentRandom access memory (RAM) provides a volatile solution for ________, storing, and retrieving data.1.

allocatinga. checkingb. orderingc. data checkd.

Which of the following statements is false?2. The sizeof operator takes a variable name or data type as an argument and returns the number of bytes a. required to store the data in memory.The sizeof operator can also be used to determine the memory requirements of arrays.b. Unlike the malloc ( ) function, the calloc ( ) function attempts to grab contiguous segments of memory from c. the heap.The free () function takes a pointer as an argument and frees the memory the pointer refers to.d.

Themainbenefitofusingcalloc()ratherthan_________isthatcalloc()isabletoinitializeeachmemory3. segment allocated to it.

realloc ( )a. malloc () b. free ( )c. sizeofd.

Which of the following statement is true?4. RAM is considered non-volatile because of its inability to store data after the computer loses power (shuts a. down). RAM is considered volatile because of its ability to store data after the computer loses power (shuts b. down). RAM is considered volatile because of its inability to not store the data after the computer loses power c. (shuts down). RAM is considered volatile because of its inability to store data after the computer loses power (shuts d. down).

Virtual memory is a _________ section of your hard disk in which the operating system can swap memory 5. segments.

data a. applicationb. reservedc. digitsd.

Used for storing variable and parameter contents, ____________ are dynamic groupings of memory that grow 6. and shrink as each program allocates and de allocates memory.

memory stacks a. input stacksb. memory heapc. output datad.

Page 91: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

81/JNU OLE

The heap is an area of unused memory managed by the ___________ system.7. dataa. operatingb. programc. bytesd.

Dynamic memory allocation allows programmers to create and use ________ when reading information from 8. standard input.

systema. shiftb. stackc. stringsd.

Increasing memory resources through __________ provides the operating system an inexpensive solution for 9. dynamic memory demands.

visual memorya. virtual memory b. error memoryc. operating memoryd.

The________functiontakestwoarguments:thefirstdeterminesthenumberofmemorysegmentsneededand10. the second deals with the size of the data type.

malloc ( )a. realloc ( )b. calloc ( )c. free ( ) d.

Page 92: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

82/JNU OLE

Chapter VIII

File Input and Output

Aim

The aim of this chapter is to:

introducedatafiles•

explain the purpose of File streams •

elucidate goto and error handling •

Objectives

The objectives of this chapter are to:

explain the purpose of bits and bytes•

classifycommontextfileopenmodes•

definefields,recordsandfiles•

Learning outcome

At the end of this chapter, you will be able to:

distinguishbetweenopeningandclosingfiles•

understanddatafilehierarchy•

explain reading and writing data•

Page 93: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

83/JNU OLE

8.1 Introduction The basics of utilizing C and volatile memory storage devices for saving, retrieving, and editing data are the basics in C programming. You know that variables are used to manage data in volatile memory areas, such as random access memory and virtual memory, and that memory can be dynamically obtained for temporarily storing data. Despite the obvious importance of volatile memory such as RAM, it does have its drawbacks when it comes to long-term data storage. When data needs to be archived or stored in non-volatile memory areas such as a hard disk, programmerslooktodatafilesasaviableanswerforstoringandretrievingdataafterthecomputer’spowerhasbeen turned off.

Datafiles areoften text-based and areused for storing and retrieving related information like that stored in adatabase.ManagingtheinformationcontainedindatafilesisuptotheCprogrammer.Inordertounderstandhowfilescanbemanaged,youwillbeintroducedtoconceptsthatareusedtobuildfilesandrecordlayoutsforbasicdatafilemanagement.

It’simportanttounderstandthebreakdownandhierarchyofdatafiles,becauseeachcomponent(parent)andsub-component (child) are used together to create the whole. Without each component and its hierarchical relationships, buildingmoreadvanceddatafilesystemssuchasrelationaldatabaseswouldbedifficult.

AcommondatafilehierarchyistypicallybrokendownintofivecategoriesasdescribedinTable 8.1

Entity DescriptionBit Binary digit, 0 or IByte Eight charactersField Grouping of bytesRecord GroupingoffieldsFile Grouping of records

Table 8.1 Data file hierarchy

8.2 Bits and BytesAlsoknownasbinarydigits,bitsarethesmallestvalueinadatafile.Eachbitvaluecanonlybea0or1.Asbitsare the smallest unit of measurement in computer systems, they provide an easy mechanism for electrical circuits to duplicate 1s and 0swith patterns of ‘off and on electrical states’. When grouped together, bits can build the next unit of data management, known as bytes.

Bytesprovidethenextstepinthedatafilefoodchain.Bytesaremadeupofeightbitsandareusedtostoreasinglecharacter, such as a number, a letter, or any other character found in a character set. For example, a single byte might contain the letter M, the number 7, or a key board character such as the exclamation point (!).Together, bytes makeupwordsor,betteryet,fields.

8.3 Fields, Records and FilesIndatabaseordata-filelingo,groupingsofcharactersaremostcommonlyreferredtoasfields.Fieldsareoftenrecognized as placeholders on a graphical user interface, but are really a data concept that groups characters in arrange of sizes and data types to provide meaningful information. Fields could be a person’s name, social security number, streetaddress,phonenumber,andsoon.Forexample,thename“Sheila”couldbeavaluestoredinafieldcalledFirstName.Whencombinedinalogicalgroup,fieldscanbeusedtoexpressarecordofinformation.Recordsarelogicalgroupingsoffieldsthatcompriseasinglerowofinformation.Eachfieldinarecorddescribestherecord’sattributes.Forexample,astudentrecordsmightbecomprisedofname,age,ID,major,andGPAfields.Eachfieldis unique in description but together describes a single record.

Page 94: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

84/JNU OLE

Individualfieldsinrecordsaresometimesseparatedordelimitedusingspaces,tabs,orcommasasshowninthenextsamplerecordthatlistsfieldvaluesforasinglestudent.

Sheila Vine, 29, 555 -55-5555, Computer Science, 4.0

Together,recordsarestoredindatafiles.Datafilesarecomprisedofoneormorerecordsandareatthetopofthedatafilefoodchain.Eachrecordinafiletypicallydescribesauniquecollectionoffields.Filescanbeusedtostorealltypesofinformation,suchasstudentoremployeedata.Datafilesarenormallyassociatedwithvariousdatabaseprocessesinwhichinformationcanbemanagedinnon-volatilestates,suchasalocaldiskdrive,USBflashdevice,or web server.

Anexampledatafilecalledstudentsdatwithcomma-delimitedrecordsisshownnext.

Michael Vine, 30, 222-22-2222, Political Science, 3.5Sheila Vine, 29, 555 -55-5555,Computer Science, 4.0Spencer Vine, 19, 777-77-7777, Law, 3.8Olivia Vine, 18, 888-88-8888, Medicine, 4.0

8.4 File StreamsPointers, pointers, and more pointers! You know you love them, or at least by now love to hate them. As you may haveguessed,anythingworthdoinginCinvolvespointers.Andofcoursedatafilesarenoexception.Cprogrammersuse pointers to manage streams that read and write data. Understanding streams is quite easy. In fact, streams are justfileorhardwaredevices,suchasamonitororprinter,whichcanbecontrolledbyCprogrammersusingpointersto the stream.

TopointtoandmanageafilestreaminC,simplyuseaninternaldatastructurecalledFILE.PointersoftypeFILEare created just like any other variable, as the next program demonstrates.

#include <stdio.h>

main()

{

//create3filepointersFILE *pRead;FILE *pWrite;FILE *pAppend;

} //end main

As you can see, three FILE pointer variables called pRead, pWrite,and pAppend were created. Using a series of functionsthatwillbeshownsoon,eachFILEpointercanopenandmanageaseparatedatafile.

8.4.1 Opening and Closing FilesThebasiccomponentsforfileprocessinginvolveopening,processing,andclosingdatafiles.Openingadatafileshouldalwaysinvolveabitoferrorcheckingand/orhandling.Failuretotesttheresultsofafile-openattemptwillsometimes cause unwanted program results in the software.

Toopenadatafile,weusethestandardinput/outputlibraryfunction-fopen().Thefopen()functionisusedinanassignment statement to pass a FILE pointer to a previously declared FILE pointer, as the next program reveals.

Page 95: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

85/JNU OLE

#include <stdio.h>

main()

{

FILE *pRead;pRead = fopen (“ f ile1.dat “, “r”);

} //end main

Thisprogramusesthefopen()functiontoopenadatafile,calledfile1.dat,inaread-onlymanner(moreonthisina moment). The fopen () function returns a FILE pointer back to the pRead variable.

Asdemonstratedinthepreviousprogram,thefopen()functiontakestwoarguments:thefirstsuppliesfopen()withthefilenametoopen,andthesecondargumenttellsfopen()howtoopenthefile.

Table8.2depictsafewcommonoptionsforopeningtextfilesusingfopen().

Mode Descriptionr Opensfileforreading

w Createsfileforwriting;discardsanypreviousdata

a Writestoendoffile(append)

Table 8.2 Common Text File Open Modes

Afteropeningafile,youshouldalwayschecktoensurethattheFILEpointerwasreturnedsuccessfully.Inotherwords,youwanttocheckforoccasionswhenthespecifiedfilenamecannotbefound.DoestheWindow’serror“Disk not ready or File not found” sound familiar?To test fopen ( )’s return value, test for a NULL value in a condition, as demonstrated next.

#include <stdio.h>

main()

{

FILE *pRead ;

pRead=fopen(“file1.dat”,“r”);

if ( pRead == NU LL )

printf(“\nFi l e cannot be opened\n”);

else

printf(“\nFi l e opened for reading \ n” ) ;

} //end main

Page 96: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

86/JNU OLE

The following condition, if (pRead == NULL) can be shortened with the next condition, if (pRead). If pRead returns a non-NULL, the ‘if’ condition is true. If pRead returns NULL, the condition is false.

Aftersuccessfullyopeningandprocessingafile,youshouldclosethefileusingafunctioncalledfclose().Thefclose()functionusestheFILEpointertoflushthestreamandclosethefile.Asshownnext,thefclose () function takes a FILE pointer name as an argument.

fclose (pRead );

In sections to come, you will see more of the fopen() and fclose () functions and how they can be used for managing thereading,writing,andappendingofinformationindatafiles.

8.4.2 Reading DataYoucaneasilycreateyourowndatafilesusingcommontexteditorssuchasvi,nano,orevenMicrosoft’sNotepad.If you’re using a Microsoft Windows operating system, you can also use a Microsoft DOS-based system function calledcopycon,whichcopiestextenteredviathekeyboardintoapredeterminedfile.Thecopyconprocesscopiestextenteredfromtheconsoleandappendsanend-of-filemarkerusingCtrl+Z.Toreadadatafile,youwillneedtoinvestigateafewnewfunctions.Specifically,youwillbeshownhowtoreadafile’scontentsandcheckforthefile’sEOF(end-of-file)markerusingthefunctionsfscanf()andfeof().

#include <stdio.h>

main ( )

{FILE *pRead;char name[10] ;

pRead = fopen (“names.dat “, “r”);

if ( pRead == NULL )

printf(“\nfilecannotbeopened\n”);

else

printf(“ \nContents of names.da t\ n \ n” ) ;fscanf( pRead. “%s”.name ) ;

while ( ! feof( pRead ) ) {

printf (“%s \ n”, name ) ;fscanf ( pRead, “%s”, name ) ;

} // end loop

} //end main

Aftersuccessfullyopeningnames.dat,usethefscanf()functiontoreadasinglefieldwithinthefile.Thefscanf()function is similar to the scanf ( ) function but works with FILE streams and takes three arguments: a FILE pointer, a data type, and a variable to store the retrieved value in. After reading the record, use the printf ( ) function to display datafromthefile.Mostdatafilescontainmorethanonerecord.Toreadmultiplerecords,itiscommontousealoopingstructurethatcanreadallrecordsuntilaconditionismet.Ifyouwanttoreadallrecordsuntiltheend-of-fileis met, the feof ( ) function provides a nice solution. Using the not operator (!), you can pass the FILE pointer to the feof()functionandloopuntilthefunctionreturnsanon-zerovaluewhenanend-of-filemarkerisreached.

Page 97: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

87/JNU OLE

fscanf()canalsoreadrecordscontainingmultiplefieldsbysupplyingtothesecondargumentaseriesoftypespecifiersforeachfieldintherecord.Forexample,thenextfscanf()functionexpectstoreadtwocharacterstringscalled name and hobby.

The%stypespecifierwillreadaseriesofcharactersuntilawhitespaceisfound,includingblank,newline,ortab.

Othervalidtypespecifiersyoucanusewiththefscanf()functionarelistedinTable8.3.

Type Descriptionc Single character d Decimal integer e, E, f, g, G Floating pointo Octal integer s String of charactersu Unsigned decimal integerx,X Hexadecimal integer

Table 8.3 Fscanf ( ) Type Specifiers

Todemonstratehowafilecontainingrecordswithmultiplefieldsisread,studythenextprogram.

#include <stdio.h>

main( )

{FILE*pRead; charname[10]; char hobby [15];

pRead = fopen(“ hobbies.dat”, “r”);

if ( pRead == NU LL )

printf(“\nfilecannotbeopened\n”);

else

printf(“\nName\tHobby\n\n”);fscanf (pRead, “%s%s”, name, hobby);

while ( !feof(pRead)){

printf(“%s\t%s\n”. name, hobby);fscanf(pRead, “%s%s”, name, hobby);

} //end loop

} //end main

Page 98: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

88/JNU OLE

8.4.3 Writing DataWritinginformationtoadatafileisjustaseasyasreadingdata.Infact,youcanuseafunctionsimilartoprintf()calledfprintf()thatusesaFILEpointertowritedatatoafile.Thefprintf()functiontakesaFILEpointer,alistofdatatypes,andalistofvalues(orvariables)towriteinformationtoadatafile,asdemonstratedinthenextprogram.

#include <stdio.h>

main( )

{

FILE *pWrite;

char fName[20];char 1Name[20]; char id[15];floatgpa;

pWrite = fopen(“students.dat”, “w”);

if ( pWrite == NULL )

printf (“\nFile not opened\n”);

else {

printf(“\nEnterfirstname,lastname,idandGPA\n\n”);printf(“Enter data separated by spaces: “);

//store data entered by the user into variables scanf(“%s%s%s%f”, fName, 1Name, id, &gpa);

//write variable contents separated by tabsfprintf(pWrite, “%s\t%s\t%s\t%.2f\n”, fName, 1Name, id, gpa);

fclose(pWrite);

} //end if

} // end main

In the preceding program the user is asked to enter student information. Each piece of information is considered afieldintherecordandisseparatedduringinputwithasinglespacecharacter.Inotherwords,itispossibletoread an entire line of data using a single scanf() function with the user entering multiple pieces of data separated byspaces.Afterreadingeachfieldofdata,usethefprintf()functiontowritevariablestoadatafilecalledstudents.dat.Byseparatingeachfieldintherecordwithatab,onecaneasilyreadthesamerecordbackwiththefollowingprogram.

Page 99: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

89/JNU OLE

#include <stdio.h>

main()

{FILE *pRead;

char fName[20]; char 1Name[20]; char id[15]; floatgpa;

pRead = fopen(“students.dat”, “r”);

if ( pRead == NULL )

printf(“\ nFile not opened\n”);

else {

//print heading printf(“\nName\t\tID\t\tGPA\n\n”);

//readfieldinformationfromdatafileandstoreinvariablesfscanf (pRead, “%s%s%s%f, fName, 1Name, id,&gpa);

//print variable data to standard outputprintf(“%s %s\t%s\t%.2f\n”, fName, 1Name, id, gpa);

fclose(p Rea d) ;

} //end if

} //end main

8.4.4 Appending DataAppending Data is a common process among Information Technology (IT) professionals as it allows programmers to continuebuildinguponanexistingfilewithoutdeletingorremovingpreviouslystoreddata.Appendinginformationtoadatafileinvolvesopeningadatafileforwritingusingtheattributeinafopen()functionandwritingrecordsordatatotheendofanexistingfile.Ifthefiledoesnotexist,however,anewdatafileiscreatedasspecifiedinthefopen () statement.

Studythefollowingprogram,whichdemonstratesappendingrecordstoanexistingdatafile.

#include <stdio.h>

void readData(void);

main()

{FILE *pWrite;char name[10];

Page 100: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

90/JNU OLE

char hobby[15];

printf(“\nCurrentfilecontents:\n”);

readData();

printf(“\nEnter a new name and hobby: “);scanf(“%s%s”, name, hobby);

//opendatafileforappendpWrite = fopen(“hobbies.dat”, “a”);

if ( pWrite == NULL )

printf(“\nFile cannot be opened\n”);

else {

//appendrecordinformationtodatafilefprintf(pWrite, “%s %s\n”, name, hobby); fclose(pWrite);readData();

} // end if

} //end main

void readData(void)

{FILE *pRead;

char name[10];char hobby[15];

//opendatafileforreadaccessonlypRead = fopen (“hobbies.dat”, “r” ) ;if ( pRead == NULL )

printf(“\nFile cannot be opened\n”);

else {

printf( “\nName\tHobby\n\n”);fscanf (pRead, “%s%s”, name, hobby);

//readrecordsfromdatafileuntilendoffileisreachedwhile ( !feof(pRead) ) {

printf(“%s\t%s\n”, name, hobby);fscanf (pRead, “%s%s”, name, hobby);

} //end loop

} // end if

Page 101: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

91/JNU OLE

fclose(pRead);

} // end readData

Withauser-definedfunctioncalledreadData(),youwillbeabletoopenthehobbies.datdatafilecreatedearlierandreadeachrecorduntiltheend-of-fileisencountered.AfterthereadData()functionisfinished,prompttheusertoenteranotherrecord.Aftersuccessfullywritingtheuser’snewrecordtothedatafile,onceagaincallthereadData( ) function to print again all records, including the one added by the user.

8.5 Goto andError HandlingWhenever your program interacts with the outside world, you should provide some form of error handling to counteract unexpected inputs or outputs. One way of providing error handling is to write your own error-handling routines.Error-handlingroutinesarethetrafficcontrolforyourprogram.Suchroutinesshouldideallyconsiderthemultitude of programming and human-generated error possibilities, resolve issues if possible, and at the very least exit the program gracefully after an error.

Because of the lack of built-in exception handling within the C language, it is acceptable to use the once infamous gotokeyword.Specifically,ifyou’dliketoseparateouterrorhandlingfromeachroutineandsaveyourselffromwriting repetitive error handlers, then goto may be a good alternative for you.

8.5.1 A Brief History of GotoThe goto keyword is a carryover from an old programming practice made popular in various languages such as BASIC, COBOL, and even C. A goto was regularly used for designing and building modularized programs. To break programs into manageable pieces, programmers would create modules and link them together using the keyword go to in hopes of simulating function calls. After years of programming with goto, programmers began to realize that this created messy “spaghetti-like” code, which at times became nearly impossible to debug. Fortunately, improvements to the structured programming paradigm and event-driven and object-oriented programming techniques have virtually eliminated the need for goto.

8.5.2 Usage of GotoUsinggotoisverysimple:firstincludealabel(adescriptivename)followedbyacolon(:)abovewhereyouwantyour error-handling routine to run (begin). To call your error-handling routine (where you want to check for an error), simply use the keyword gotofollowed by the label name as demonstrated next.

int myFunction(){

int iReturnValue = 0; //0 for success

/* process something */if(error) {

goto ErrorHandler; //go to the error-handling routine

}/* do some more processing */if(error){

ret_val = [error];goto ErrorHandler; //go to the error-handling routine

}

Page 102: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

92/JNU OLE

ErrorHandler:/* error-handling routine */return iReturnValue ;}

The label in the preceding code is ErrorHandler, which is simply a name that came up with to identify or label the error handler. In the same sample code, you can see the check for errors in each of the ‘if’ constructs and if an error exists, it is called error handler using the keyword goto.

Review the next programming example, that demonstrates the use of goto and a couple of new functions [perror () andexit()]tobuilderrorhandlingintoafileI/Oprogram.

#include <stdio.h>#include <stdlib.h>

main(){

FILE *pRead; char name[10];char hobby[15];

pRead = fopen(“hobbies.dat”, “r”);

if ( pRead == NULL)

goto ErrorHandler;else {

printf(“\nName\tHobby\n\n”);fscanf(pRead, “%s%s”, name, hobby);

while ( !feof(pRead)){

printf(“%s\t%s\n”. name, hobby);fscanf(pRead, “%s%s”, name, hobby);

} //end loop

} // end if

exit(EXIT_SUCCESS); //exit program normally

ErrorHandler:perror(“The following error occurred”);exit(EXIT_FAILURE); //exit program with error

} //end main

The exit ( )function, part of the <stdlib.h> library, terminates a program as if it were exited normally. As shown next,theexit()functioniscommonwithprogrammerswhowanttoterminateaprogramwhenencounteringfileI/O (input/output) errors.

Page 103: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

93/JNU OLE

exit(EXIT_SUCCESS); //exit program normally//orexit(EXIT_FAILURE); //exit program with error

The exit() function takes asingle parameter, a constant of either EXIT_SUCCESS or EXIT_ FAILURE, both of whichreturnapre-definedvalueforsuccessorfailure,respectively.

The perror()function sends a message to standard output describing the last error encountered. The perror()function takesasinglestringargument,whichisprintedfirst,followedbyacolonandablank,thenthesystemgeneratederror message and a new line, as revealed next.

8.6 Chapter Program-The Phone Book ProgramThePhoneBookprogramusesmanychapter-basedconcepts,includingfields,records,datafiles,FILEpointers,anderrorhandling,tobuildasimpleelectronicphonebook.Specifically,thePhoneBookprogramallowsausertoadd phone book entries and print the contents of the entire phone book. After reading this chapter and studying the codefromthePhoneBookprogram,youshouldbeabletobuildyourownprogramsthatusedatafilestostoreallkindsofinformation.Inaddition,youcouldbuildyourownPhoneBookprogramormakemodifications.Allofthecode required to build the Phone Book program is revealed next.

#include<stdio.h>#include <stdlib.h>

main()

{

int response;

char *1Name[20]= {0};char *fName[20]= {0};char *number[20]= {0};

FILE *pWrite;FILE *pRead;

printf(“\n\tPhone Book\n”); printf(“\n1 \tAdd phone book entry\n”);printf(“2\tPrint phone book\n\n”); printf(“Select an option: “); scanf(“%d”, &response);

if ( response == 1 ) {

/* user is adding a new phone book entry - get the info */

printf(“\nEnterfirstname:“);scanf(“%s•,fName);printf(“\nEnter last name: “); scanf(“%s”, 1Name);printf(“\nEnter phone number: “);scanf(“%s”, number);

pWrite = fopen(“phone_book.dat”, “a” );

Page 104: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

94/JNU OLE

if ( pWrite != NULL ) {

fprintf (pWrite, “%s %s %s\n”, fName, 1Name, number);fclose (pWrite);

}

elsegotoErrorHandler;//thereisafilei/oerror

}else if ( response == 2 ) {

/* user wants to print the phone book */

pRead = fopen(“phone_book.dat”, “r” );

if ( pRead != NULL ) {

printf(“\nPhone Book Entries\n”);

while ( !feof(pReadl

fscanf(pRead, “%s %s %s”, fName, 1Name, number);

if ( !feof(pRead) )printf(“\n%s %s\t%s”, fName, 1Name, number);

} //end loop

printf(“\n”);

}

else

gotoErrorHandler; //thereisafilei/oerror

}else {

printf(“\nlnvalid selection\n”);

}

exit(EXIT_SUCCESS); //exit program normally

ErrorHandler:perror(“The following error occurred”);exit(EXIT_FAILURE); //exit program with error

} //end main

Page 105: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

95/JNU OLE

SummaryDatafilesareoftentext-basedandareusedforstoringandretrievingrelatedinformationlikethatstoredina•database.Alsoknownasbinarydigits,bitsarethesmallestvalueinadatafile;eachbitvaluecanonlybea0or1.•Bits are the smallest unit of measurement in computer systems.•Bytes are most commonly made up of eight bits and are used to store a single character, such as a number, a •letter, or any other character found in a character set.Groupingsofcharactersarereferredtoasfields.•Recordsarelogicalgroupingsoffieldsthatcompriseasinglerowofinformation.•Datafilesarecomprisedofoneormorerecords.•UseaninternaldatastructurecalledFILEtopointtoandmanageafilestreaminC.•Thefclose()functionusestheFILEpointertoflushthestreamandclosethefile.•The fscanf() function is similar to the scanf() function but works with FILE streams and takes three arguments: •a FILE pointer, a data type, and a variable to store the retrieved value in.Totestwhenanend-of-filemarkerisreached,passtheFILEpointertothefeof()functionandloopuntilthe•function returns a non-zero value.The fprintf ( ) functiontakes a FILE pointer, a list of data types, and a list of values (or variables) to write •informationtoadatafile.Appendinginformationtoadatafileinvolvesopeningadatafileforwritingusingtheattributeinafopen()•functionandwritingrecordsordatatotheendofanexistingfile.The keyword goto is used to simulate function calls and can be leveraged to build error handling routines.•The exit () function terminates a program.•The perror() function sends a message to standard output describing the lasterror encountered.•Openingadatafileshouldalwaysinvolveabitoferrorcheckingand/orhandling.•The fopen ( ) function is used in an assignment statement to pass a FILE pointer to a previously declared FILE •pointer.Writinginformationtoadatafileisjustaseasyasreadingdata.Infact,youcanuseafunctionsimilartoprintf•()calledfprintf()thatusesaFILEpointertowritedatatoafile.Error-handlingroutinesarethetrafficcontrolforyourprogram.•Theexit()functioniscommonwithprogrammerswhowanttoterminateaprogramwhenencounteringfile•I/O (input/output) errors.The exit ( ) function, part of the <stdlib.h> library, terminates a program as if it were exited normally.•

ReferencesDixit, J.B., 2009. • Programming in C, 2nd ed., Firewall Media Publications.Mittal, A., 2010. • Programming in C: A Practical Approach, Dorling Kindersley (India) Pvt. Ltd.Schiller, T. • CFile Input andOutput (I/O), [Pdf]Available at: <https://www.cs.washington.edu/education/courses/303/09au/cfileio.pdf>[Accessed5June2013].Vine, M. 2007. • C Programming for the Absolute Beginner. [Pdf] Available at: <http://site.ebrary.com/lib/alltitles/docDetail.action?docID=10228219&ppg=272> [Accessed 5 June 2013]. 2012. • File IOTutorialC. [Video online] Available at: <http://www.youtube.com/watch?v=PZUtuka5iEg> [Accessed 4 June 2013].2012. • 13- File I/O. [Video online] Available at: <http://www.youtube.com/watch?v=euGDWV5DDzQ> [Accessed 4 June 2013].

Page 106: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

96/JNU OLE

Recommended ReadingDixit, J.B., 2006. • ComprehensiveProgramminginCandNumericalAnalysis., Firewall Media Publications.Veerana,V. K. andJankidevi, S. J.,2007.• CforUIncludingCandCGraphics.,Firewall Media Publications.Gookin, D.,2004.• CAll-in-OneDeskReferenceForDummies, Wiley Publishing, Inc.

Page 107: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

97/JNU OLE

Self AssessmentOpeningadatafileshouldalwaysinvolveabitof______________and/orhandling.1.

error checkinga. right checkingb. order checkingc. data checkingd.

Which of the following statements is true?2. Bytes are made up of two digits and are used to store a double character.a. Bytes are made up of ten bits and are used to store a triple character.b. Bytes are made up of eight bits and are used to store a single character.c. Bytesaremadeupoffivebitsandareusedtostoreasinglecharacter.d.

Match the following3. Bit1. GroupingoffieldsA. Field2. Grouping of bytesB.

Record3. Grouping of recordsC.

File4. Binary digit, 0 or 1D. 1-C, 2-B, 3-D, 4-Aa. 1-D, 2-B, 3-A, 4-Cb. 1-D, 2-A, 3-B, 4-Cc. 1-A, 2-D, 3-C, 4-Bd.

Which of the following statement elaborates the fprintf ( ) function?4. Thefprintf()functiontakesaprogram,alistofdatafiles,andanerrorlistofvalues(orvariables)towritea. informationtoaprintfile.Thefprintf()functiontakesapointer,alistofvalues(orvariables)towriteinformationtoanerrorfile.b. The fprintf ( ) function takes a FILE pointer, a list of data types, and a list of values (or variables) to write c. informationtoadatafile.The fprintf ( ) function takes a FILE data, a list of error types, and a list of variables to write information d. toadatafile.

Bitsarethesmallestvalueinadatafile,alsoknownas______________.5. data digitsa. applicationb. error digitsc. binary digitsd.

Theexit()functioniscommonwithprogrammerswhowanttoterminateaprogramwhenencounteringfile6. ____________ errors.

input/output a. data/typeb. print/programc. bit/byted.

Page 108: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

98/JNU OLE

MatchthefollowingFscanf()TypeSpecifiers7.

c1. Floating pointA.

d2. Single characterB.

e, E, f, g, G3. Decimal integerC.

u4. Unsigned decimal integerD. 1-D, 2-C, 3-B, 4-Aa. 1-B, 2-C, 3-A, 4-Db. 1-C, 2-A, 3-C, 4-Dc. 1-A, 2-D, 3-B, 4-Cd.

The fscanf ( ) function is similar to the _______ function but works with FILE streams and takes three arguments: 8. a FILE pointer, a data type, and a variable to store the retrieved value in.

pressf ( )a. dataf ( )b. rightf ( )c. scanf ( )d.

Writinginformationtoadatafileisjustaseasyas________data.9. copyinga. accountingb. readingc. writingd.

________________ routines should ideally consider the multitude of programming and human-generated error 10. possibilities, resolve issues if possible, and at the very least exit the program gracefully after an error.

Error-handling a. Error-readingb. Error-exitingc. Error-goingd.

Page 109: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

99/JNU OLE

Application I

CPythonCPython is an implementation of the Python programming language. It is the most-widely used, default implementation. This language is written in C. Besides CPython, Jython and IronPython are two other production quality implementations of the Python. Jython is written in Java whereas, IronPython is written for C#. All the three implementations of Python mentioned above have several experimental implementations.

CPython is a bytecode interpreter. The term Bytecode is used to denote various forms of instruction sets, which are designedtoensureefficientexecutionoftheinstructionbyasoftwareinterpreterandalsotoenhancethesuitabilityof the instruction for further compilation into the machine code. An interpreter executes the instructions written in a computer program. It can perform the following roles:

execute the source code directly•translate source code into intermediate code and execute the same immediately•explicitly execute the stored precompiled code made by a compiler•

CPython has a foreign function interface with C and several other languages. A foreign function interface is also referred as FFI, which is a mechanism by which a program written in one programming language is capable of calling routines and using the services written in another programming language. In C, it is necessary to explicitly write bindings in a language other than Python. A binding from a programming language to a library or OS service is referred as an API providing that service in the language.

Supported Platforms of CPythonThe supported platforms of CPython are as follows:

Unix-like•AIX operating system•BSD•Darwin•FreeBSD•HP-UX•IRIX 5 and later•Plan 9 from Bell Labs•Mac OS X•NetBSD•Linux•OpenBSD•Solaris•Tru64•Other Unixes•

Desktop OSesAROS•AtheOS•BeOS•Windows•Windows NT•OS/2•RISC OS•

Page 110: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

100/JNU OLE

Special and embeddedGP2X•iPodLinux•Nintendo DS•Nintendo Gamecube•Symbian OS Series60•Nokia 770 Internet Tablet•Nokia N800•Nokia N810•Palm OS•PlayStation 2•PlayStation 3 (Linux)•Psion•QNX•Sharp Zaurus•Xbox/XBMC•VxWorks•Openmoko•

Previously supported platformsPEP 11 lists platforms which are not supported in CPython by Python Software Foundation. These platforms can still be supported by external ports. See below.

DOS (unsupported since 2.0)•IRIX 4 (unsupported since 2.3)•Mac OS 9 (unsupported since 2.4)•MINIX (unsupported since 2.3)•

External portsTheseareportsnotintegratedtoPythonSoftwareFoundation'sofficialversionofCPython,withlinkstoitsmaindevelopmentsite.Portsoftenincludeadditionalmodulesforplatform-specificfunctionalities,likegraphicsandsound API for PSP and SMS and camera API for S60.

Amiga: AmigaPython•AS/400: iSeriesPython•DOS using DJGPP: PythonD•PlayStation Portable: Stackless Python for PSP•Symbian OS: Python for S60•Windows CE/Pocket PC: Python Windows CE port•

Concurrency issues with CPythonA drawback of using CPython on a multiprocessor computer is the presence of a Global Interpreter Lock on each CPython interpreter process. This can effectively effectively disable concurrent Python threads within one process. To be truly concurrent in multiprocessor environment, separate CPython interpreter processes have to be run, which makesestablishingcommunicationbetweenthemadifficulttask.Thereisconstantdiscussionwhethertoremovethe GIL from CPython.

Page 111: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

101/JNU OLE

QuestionsWhat is CPython and how is it linked to C?1. AnswersCPython is an implementation of the Python programming language, which is most widely used. It is written in C programming language.

Name three supported platforms of CPython separately based on Unix-like, Desktop OSes and Special Emebedded 2. platforms.AnswersSupported Platforms are:

Unix-like are – BSD, Darwin, Linux;•Desktop OSes are – Windows NT, AROS, OS/2•Special and embedded are – iPodLinux, Palm OS, QNX•

What are the advantages and disadvantages of CPython?3. AnswersAdvantages of CPython –

CPython is a bitecode interpreter.•CPython has a foreign function interface with C and several other languages.•

Disadvantages of CPython –Presence of a Global Interpreter Lock on each CPython interpreter process limits the use of CPython on a •multiprocessor computer. It shows the following drawbacks:

disable concurrent Python threads within one process �separate CPython interpreter processes have to be run to become concurrent in multiprocessor �environmentthus,communicationbetweentheinterpretersbecomesdifficult �

Name the platforms that were supported by the C programme earlier.4. Answers MINIX, DOS, IRIX 4

Page 112: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

102/JNU OLE

Application II

/* This program reads a weight in pounds from the key board representing it as an integer.It converts the weight to ounce, and prints it. Program from "Applications Programming in ANSI C".

*/

#include<stdio.h>

main( ){ int pounds;

/*Readfirstweightinpounds*/

printf("\n\n\tWeight in pounds?"); scant("%d",&pounds);

/* Loop until user signals halt with negatie integer. */

while(pounds>=0) { printf("\n\n\tEquivalent weight in ounces: %d", pounds * 16); printf("\n\n\tWeight in pounds?"); printf("\n\n\tEnter a negative integer to quit."); scanf("%d",&pounds); }}

Page 113: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

103/JNU OLE

Applications III

A program for bomber fighter plane simulation.

#include<stdio.h>#include<graphics.h>#include<conio.h>#include<dos.h>#include<math.h>void main ( ){ int gd = DETECT, gm ; floatx1,x2,y1,y2,dx,co,j; intflag=0; floatdistance,B_SPEED,F_SPEED;

initgraph(&gd,&gm.″″); cleardevice ( ) ; textcolor (RED) ;printf(″EntertheSpeedofBomberPlane(1to20):″);scanf(″%f″,&B_SPEED);printf(″ENTERtheSpeedofFighterPlane(1to20):″);scanf(″%f”,&F_SPEED);j = 120 ;

x1=10.0 ;y1=400.0 ;x2=20.0 ;y2=200.0 ;

while (x1 < 600){ cleardevice ( ) ; sound (j) ; setfillstyle(1,RED); fillellipse(x1,y1,5,5); outtextxy(x1+20,y1,″BOMBER″); / / circle (x1, y1, 10) ;x1=x1+B_SPEED ;dx = x1 - x2 ;gotoxy (1, 1) ;printf(″BOMBER x1:%2f,y1:%f″,x1,y1);gotoxy (1, 2) ;printf(″FIGHTERX2:%2f,Y2:%2f″,x2,y2);distance = pow ( (x1=x2), 2) + pow ( (y1-y2), 2) ;distance = sqrt (distance) ;gotoxy (1, 3) ;printf(″DISTANCEBETWEENBOTHPLANE:%f″,distance);co = dx/distance ;x2=x2+F_SPEED*co ;y2 = y2+F_SPPED*sqrt (1-co*co) ;/ /circle (x2, y2, 10) ;setfillstyle(1,GREEN);

Page 114: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

104/JNU OLE

fillellipse(x2,y2,5,5);outtextxy(x2=20,y2,″FIGHTER″);

if(distance≤50){

flag=1;for (int i=0; i<15; i++){sound ( i*180) ;delay (50) ;}outtextxy(220,150,″BomberPlanecrashed″);nosound ( ) ;getch ( ) ;break ;}delay (500) ;

}if(flag==0){outtextxy(220,250,″Sorry:BomberPlanehasPassedawaySafely!″);

for (int i=120; i<1000; i++){sound (i) ;delay (8) ;

}delay(50) ;}nosound ( ) ;getch ( ) ;}

Page 115: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

105/JNU OLE

Application IV

/*ThisprogramcountsthenumberofbytesinaCsourcefile.Theprogrampromptstheuserforafilenameandthen concatenates the ".c" extension to this name. It uses the function getc to read the characters.

#include<stdlib.h>#include<stdio.h>#include<string.h>

main( ){ FILE* fptr; char extension[] = ".c";

charfile_name[FILENAME_MAX];/*definedinstdio.h*/ int char_count;

printf("\n\n\tFile name (NO extension):\t");scanf("%s",file_name);strcat(file_name,extension);fptr=fopen(file_name,"rb");

for(char_count=0; getc(fptr) !=EOF; ++char_count); printf("\n\tByte size:\t%d", char_count); fclose(fptr);

return EXIT_SUCCESS;}

Page 116: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

106/JNU OLE

Bibliography

References2011. • Dynamic Memory Allocation. [Video online] Available at: <http://www.youtube.com/watch?v=Dml54J3Kwm4> [Accessed 4 June 2013].2012. • 13- File I/O. [Video online] Available at: <http://www.youtube.com/watch?v=euGDWV5DDzQ> [Accessed 4 June 2013].2012. • Dynamicmemoryallocation –malloc calloc realloc free. [Video online] Available at: <http://www.youtube.com/watch?v=xDVC3wKjS64> [Accessed 4 June 2013].2012. • File IOTutorialC. [Video online] Available at: < http://www.youtube.com/watch?v=PZUtuka5iEg> [Accessed 4 June 2013].Ackermann, C. E., 1989. • The Essentials of C Programming Language, Research & Education Assoc.ArraysandStrings• [Pdf] Available at: <http://pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/10-ArraysAndStrings.pdf> [Accessed 26 June 2013].Ashok, K., 2010. • C Programming: Test Your Skills, Pearson Education India.Balagurusamy, 2008. • Programming In Ansi C, 4th ed., Tata McGraw-Hill Education.Balagurusamy., 2011.• ComputerConcept&ProgrammingInC(ForUptu), Tata McGraw Hill Education Pvt. Ltd.C Programming Classes - Structure in C language• [Video online] Available at: <http://www.youtube.com/watch?v=Y_2DcVnOxPQ> [Accessed 26 June 2013].CProgrammingTutorial#21-ConceptofPointers-Part1• [HD] [Video online] Available at: <http://www.youtube.com/watch?v=rjo9rfRPQU4> [Accessed 26 June 2013].C Programming Tutorial 44 - Strings and Characters• [Video online] Available at: <http://www.youtube.com/watch?v=EJBb8nQD-4g> [Accessed 26 June 2013].CProgrammingTutorial:Arrays(OneandTwoDimensionalArray):Lesson2• [Video online] Available at: <http://www.youtube.com/watch?v=NFJMjgXb0uA> [Accessed 26 June 2013].CProgrammingTutorial:InputOutput(printf,scanf,formatspecifiers)Lesson1• [Video online] Available at: <http://www.youtube.com/watch?v=5v7h4ZmgMvw> [Accessed 26 June 2013].Control Statements• [Pdf] Available at: <http://download.nos.org/srsec330/330L9.pdf> [Accessed 26 June 2013].ControlStatementsinProgrammingLanguages(final)part1• [Video online] Available at: <http://www.youtube.com/watch?v=hX0Rrq8ouxY> [Accessed 26 June 2013].Control statements in programming languages-part 1-pldc• [Video online] Available at: <http://www.youtube.com/watch?v=ageuh_4_J9E> [Accessed 26 June 2013].DataStructuresUsingC• [Pdf] Available at: <http://www.gatesit.org/gitdownloads/C&DS.pdf> [Accessed 26 June 2013].Deshpande, P. S. & Kakde, O. G., 2004. • C and Data Structures, Cengage Learning.Dixit, J. B., 2005. • Fundamentals of Computers and Programming in C, Firewall Media.Dixit, J.B., 2009. • Programming in C, 2nd ed., Firewall Media Publications.Dr. Kumar, A. S., 2008. • Lecture - 1 Introduction to programming languages [Video online] Available at: <http://www.youtube.com/watch?v=EbNJ05EVXs0> [Accessed 26 June 2013].Dr. Owen, C.B. • DynamicMemoryAllocation, [Pdf]Available at: <http://www.cse.msu.edu/~cse251/lecture14.pdf> [Accessed 4 June 2013]. Functions in C• [Pdf] Available at: <http://www.nada.kth.se/kurser/master/intro/Course03-04/Handouts/Flecture05.pdf> [Accessed 26 June 2013].

Page 117: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

107/JNU OLE

Functions in C Programming• [Video online] Available at: <http://www.youtube.com/watch?v=s7ZY1E4smqU> [Accessed 26 June 2013].Goel, A., • Computerprogramming-I:Asperthefirst-yearengineeringsyllabusofUniversityofMumbai, Pearson Education India.Hoover, 2009. • SystemProgrammingWithCAndUnix, Pearson Education India.Input and Output in C• [Pdf] Available at: <http://www.prog2impress.com/downloads/Input%20and%20Output%20in%20C.pdf> [Accessed 26 June 2013].Introduction to C Programming I• [Video online] Available at: <http://www.youtube.com/watch?v=fUcSXbQnrLI&list=PL66D13A5B3585C213> [Accessed 26 June 2013].Introduction to the C Programming Language• [Pdf] Available at: <http://163.25.99.51/Huang_Computer/Programming%20Language-website2.pdf> [Accessed 26 June 2013].Jensen, T., 2003. • ATUTORIALONPOINTERSANDARRAYSINC[Pdf] Available at: <http://pdos.csail.mit.edu/6.828/2012/readings/pointers.pdf> [Accessed 26 June 2013].Kenneth, R., 2007. • Pointers On C, Pearson Education India.Kernighan, W. B. & Ritchie, D., 1988. • C Programming Language, 2nd ed. Prentice Hall.Kernighan, W. B. & Ritchie, M. D., 1988. • The C programming Language [Pdf] Available at: <http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf> [Accessed 26 June 2013].Laitinen, K., 2004. • ANaturalIntroductiontoComputerProgrammingwithC#, Trafford Publishing.Lecture 7:Arrays, strings, and functions• [Pdf] Available at: <http://www.stanford.edu/~fringer/teaching/operating_systems_03/handouts/lecture7.pdf> [Accessed 26 June 2013].Lipari, G., 2012. • Fundamentals of Programming Introduction to the C language [Pdf] Available at: <http://retis.sssup.it/~lipari/courses/infbase2012/03.c_intro-handout.pdf> [Accessed 26 June 2013].Lou, Y., 2011. • IntroductiontoCPointersandArrays [Pdf] Available at: <http://www.cs.cornell.edu/courses/CS2022/2011sp/lectures/lect04.pdf> [Accessed 26 June 2013].Mittal, A., 2010. • Programming in C: A Practical Approach, Dorling Kindersley (India) Pvt. Ltd.PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts• [Video online] Available at: <http://www.youtube.com/watch?v=c_sDgHgNR6w> [Accessed 26 June 2013].Pointers in c• [Video online] Available at: <http://www.youtube.com/watch?v=w2pbty8tLKU> [Accessed 26 June 2013].Program Control Statements• [Pdf] Available at: <http://www.uotechnology.edu.iq/dep-eee/lectures/1st/Computer%20science/2.pdf> [Accessed 26 June 2013].Puntambekar, A.A.,• 2009. DataStructuresUsing‘C’, Technical Publications.Schiller, T. • CFile Input andOutput (I/O), [Pdf] Available at: <https://www.cs.washington.edu/education/courses/303/09au/cfileio.pdf>[Accessed5June2013].Schultz, W. T., 2004. • C And The 8051, 3rd ed., PageFree Publishing, Inc.Veerana, V. K. & Jankidevi, S. J., 2007. • CforUIncludingCandCGraphics, Firewall Media.Vine, M. 2007. • C Programming for the Absolute Beginner. [Pdf]Available at: <http://site.ebrary.com/lib/alltitles/docDetail.action?docID=10228219&ppg=272> [Accessed 5 June 2013]. Vine, M. 2007. • C Programming for the Absolute Beginner. [Pdf]Available at: <http://site.ebrary.com/lib/alltitles/docDetail.action?docID=10228219&ppg=272> [Accessed 5 June 2013].

Recommended ReadingBalagurusamy, E., • Programming In Ansi C, 5E, Tata McGraw-Hill Education.Deitel, J. P. & Deitel, M. H., 2009. • C: How to Program, 6th ed. Prentice Hall.Dixit, J. B., 2006. • ComprehensiveProgramminginCandNumericalAnalysis., Firewall Media Publications.Dixit, J. B., 2006. • ComprehensiveProgramminginCandNumericalAnalysis., Firewall Media Publications.

Page 118: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

108/JNU OLE

Gookin, D., 2004. • CAll-in-OneDeskReferenceForDummies, Wiley Publishing, Inc.Hanly, 2009. • ProgrammingInCAndDataStructures(ForJntu), Pearson Education India.Kochan, 2005. • Programming In C, 3/E, Pearson Education India.Kochan, G. S., 2012. • Programming in Objective-C, 4th ed. Addison-Wesley Professional.Krishnamoorthy, 2010. • DATASTRUCTURESUSINGC, Tata McGraw-Hill Education.Lafore, 2002. • Object Oriented Programming In C++, 4/E, Pearson Education India.Lichade, V. M., 2007.• C Programming, DreamTech Press.Loudon, K., 2009. • MasteringAlgorithmswithC, O’Reilly Media, Inc.Malik, D. S., 2009. • C++ Programming: Program Design Including Data Structures: Program Design Including Data Structures, 4th ed. Cengage Learning.Malik, D. S., 2012. • C++Programming:FromProblemAnalysistoProgramDesign,6thed.:FromProblemAnalysistoProgramDesign, 6th ed., Cengage Learning.Nair, 2009. • Data Structures In C, PHI Learning Pvt. Ltd.Pandey, H.M., 2009. • TroubleFreeC., University Science Press.Parthasarthy, S., 2008. • Essentials of Programming In C For Life Sciences, Ane Books Pvt Ltd.Puntambekar, A. A., 2008. • Data Structures with C, Technical Publications.Rajaraman, V., 1994. • COMPUTERPROGRAMMINGINC, PHI Learning Pvt. Ltd.Reddy, R. & Ziegler, C., 2009. • C Programming for Scientists and Engineers with Applications, Jones & Bartlett Learning.Veerana,V. K. & Jankidevi, S. J.,2007.• CforUIncludingCandCGraphics.,Firewall Media Publications.

Page 119: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

109/JNU OLE

Self Assessment Answers

Chapter Ib1. c2. a3. c4. b5. a6. d7. b8. d9. b10.

Chapter IIc1. d2. a3. a4. d5. b6. a7. d8. b9. a10.

Chapter IIId1. c2. a3. b4. d5. b6. c7. a8. d9. c10.

Chapter IVb1. c2. d3. a4. c5. b6. d7. c8. b9. a10.

Page 120: Introduction to C Programming - jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem I/Introductio… · Introduction to C Programming This book is a part of the

Introduction to C Programming

110/JNU OLE

Chapter Vb1. a2. c3. c4. d5. c6. a7. b8. a9. d10.

Chapter VIb1. a2. c3. b4. d5. a6. c7. a8. b9. a10.

Chapter VIIa1. c2. b3. d4. c5. a6. b7. d8. b9. c10.

Chapter VIIIa1. c2. b3. c4. d5. a6. b7. d8. c9. a10.