Introduction to C Programming

Introduction to C Programming Board of Studies Prof. H. N. Verma Vice- Chancellor Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and H...
11 downloads 0 Views 4MB Size
Introduction to C Programming

Board of Studies Prof. H. N. Verma Vice- Chancellor Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune

Prof. M. K. Ghadoliya Director, School of Distance Education and Learning Jaipur National University, Jaipur

___________________________________________________________________________________________ Subject Expert Panel Dr. Ramchandra G. Pawar Director, SIBACA, Lonavala Pune

Ashwini Pandit Subject Matter Expert

___________________________________________________________________________________________ Content Review Panel Gaurav Modi Subject Matter Expert

Shubhada Pawar Subject Matter Expert

___________________________________________________________________________________________ Copyright © This book contains the course content for Introduction to C Programming. First Edition 2013 Printed by Universal Training Solutions Private Limited Address 05th Floor, I-Space, Bavdhan, Pune 411021. All rights reserved. This book or any portion thereof may not, in any form or by any means including electronic or mechanical or photocopying or recording, be reproduced or distributed or transmitted or stored in a retrieval system or be broadcasted or transmitted. ___________________________________________________________________________________________

Index I. Content....................................................................... II II. List of Figures...........................................................VI III. List of Tables......................................................... VII IV. Application.............................................................. 99 V. Bibliography........................................................... 106 VI. Self Assessment Answers...................................... 109 Book at a Glance

I

Contents Chapter I........................................................................................................................................................ 1 ‘C’ Fundamentals.......................................................................................................................................... 1 Aim................................................................................................................................................................. 1 Objectives....................................................................................................................................................... 1 Learning outcome........................................................................................................................................... 1 1.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........................................................................................................................ 2 1.2 Introduction to ‘C’..................................................................................................................................... 2 1.2.1 Low Level Languages............................................................................................................... 3 1.2.2 High Level Languages.............................................................................................................. 3 1.3 Identifier and Keywords........................................................................................................................... 3 1.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............................................................................................................ 5 1.5 Variables.................................................................................................................................................... 5 1.5.1 Variable Declaration................................................................................................................. 5 1.5.2 Variable Initialisation................................................................................................................ 6 1.5.3 Declaring Variables as Constants.............................................................................................. 6 1.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........................................................................................ 9 1.7 Preprocessor Directives............................................................................................................................ 9 1.7.1 Macro Expansion.................................................................................................................... 10 1.7.2 File Inclusion...........................................................................................................................11 Summary...................................................................................................................................................... 12 References.................................................................................................................................................... 12 Recommended Reading.............................................................................................................................. 12 Self Assessment............................................................................................................................................ 13 Chapter II.................................................................................................................................................... 15 Data Input and Output............................................................................................................................... 15 Aim............................................................................................................................................................... 15 Objectives..................................................................................................................................................... 15 Learning outcome......................................................................................................................................... 15 2.1 Introduction............................................................................................................................................. 16 2.2 Getchar Functions................................................................................................................................... 16 2.3 Putchar Function..................................................................................................................................... 16 2.4 Scanf( ) Function..................................................................................................................................... 17 2.5 Printf( ) Function..................................................................................................................................... 17 2.6 Gets ( ) and Puts ( ) Functions................................................................................................................ 18 II

Summary...................................................................................................................................................... 19 References.................................................................................................................................................... 19 Recommended Reading.............................................................................................................................. 19 Self Assessment............................................................................................................................................ 20 Chapter III................................................................................................................................................... 22 Control Statements..................................................................................................................................... 22 Aim............................................................................................................................................................... 22 Objectives..................................................................................................................................................... 22 Learning outcome......................................................................................................................................... 22 3.1 Introduction............................................................................................................................................. 23 3.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............................................................................................................. 25 3.3 The Break Statement............................................................................................................................... 26 3.4 Continue Statement................................................................................................................................. 26 3.5 ‘If’ Statement.......................................................................................................................................... 27 3.6 ‘If Else’ Statement................................................................................................................................... 27 3.7 Switch Statement.................................................................................................................................... 27 3.8 ‘If Else If Ladder’................................................................................................................................... 28 3.9 Nested If.................................................................................................................................................. 28 3.10 Iteration Statement................................................................................................................................ 29 3.11 Nested For............................................................................................................................................. 29 3.12 Goto Statement...................................................................................................................................... 29 3.12.1 Conditional Goto................................................................................................................... 29 3.12.2 Unconditional Goto............................................................................................................... 29 Summary...................................................................................................................................................... 30 References.................................................................................................................................................... 30 Recommended Reading.............................................................................................................................. 30 Self Assessment............................................................................................................................................ 31 Chapter IV................................................................................................................................................... 33 Arrays and Strings...................................................................................................................................... 33 Aim............................................................................................................................................................... 33 Objectives..................................................................................................................................................... 33 Learning outcome......................................................................................................................................... 33 4.1 Introduction............................................................................................................................................. 34 4.2 Declaration of An Array.......................................................................................................................... 34 4.3 Initialisation of Array.............................................................................................................................. 34 4.3.1 Drawbacks of Initialising An Array........................................................................................ 34 4.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.................................................................. 36 4.5 Strings..................................................................................................................................................... 36 4.5.1 String Functions...................................................................................................................... 37 4.6 Passing Array to Functions..................................................................................................................... 38 Summary...................................................................................................................................................... 39 References.................................................................................................................................................... 39 Recommended Reading.............................................................................................................................. 39 Self Assessment............................................................................................................................................ 40 III

Chapter V..................................................................................................................................................... 42 Functions and Structures........................................................................................................................... 42 Aim............................................................................................................................................................... 42 Objectives..................................................................................................................................................... 42 Learning outcome......................................................................................................................................... 42 5.1 Introduction to Functions........................................................................................................................ 43 5.2 Uses of Functions.................................................................................................................................... 43 5.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................................................................................................................. 46 5.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................................................................................................................... 47 5.5 Return Values.......................................................................................................................................... 47 5.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................................................................... 48 5.7 Recursion................................................................................................................................................ 48 5.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.................................................................................... 50 5.9 Array of Structures.................................................................................................................................. 50 5.10 Additional Features of Structures.......................................................................................................... 51 5.11 Uses of Structures................................................................................................................................. 52 5.12 Unions................................................................................................................................................... 52 Summary...................................................................................................................................................... 53 References.................................................................................................................................................... 53 Recommended Reading.............................................................................................................................. 53 Self Assessment............................................................................................................................................ 54 Chapter VI................................................................................................................................................... 56 Pointers........................................................................................................................................................ 56 Aim............................................................................................................................................................... 56 Objectives..................................................................................................................................................... 56 Learning outcome......................................................................................................................................... 56 6.1 Introduction............................................................................................................................................. 57 6.2 Pointer Declaration................................................................................................................................. 57 6.3 Reference Operator................................................................................................................................. 57 6.4 Dereference Operator.............................................................................................................................. 58 6.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............................................................................................................................ 59 6.6 Pointers with Function............................................................................................................................ 59 6.6.1 Call by Value........................................................................................................................... 60 IV

6.6.2 Call by Reference.................................................................................................................... 60 6.6.3 Callback Functions................................................................................................................. 60 6.7 Function Pointer Syntax.......................................................................................................................... 60 6.8 Initialising Function Pointer................................................................................................................... 60 6.9 Using Function Pointer........................................................................................................................... 61 6.10 Arrays and Pointer................................................................................................................................. 61 6.11 Array of Pointers................................................................................................................................... 62 6.12 Pointers with Structures........................................................................................................................ 62 6.13 Pointers on Pointer................................................................................................................................ 62 Summary...................................................................................................................................................... 64 References.................................................................................................................................................... 64 Recommended Reading.............................................................................................................................. 64 Self Assessment............................................................................................................................................ 65 Chapter VII................................................................................................................................................. 67 Dynamic Memory Allocation..................................................................................................................... 67 Aim............................................................................................................................................................... 67 Objectives..................................................................................................................................................... 67 Learning outcome......................................................................................................................................... 67 7.1 Introduction............................................................................................................................................. 68 7.2 Stack and Heap....................................................................................................................................... 68 7.3 Sizeof...................................................................................................................................................... 68 7.4 Malloc()................................................................................................................................................... 70 7.4.1 Managing Strings with Malloc( )............................................................................................ 71 7.5 Freeing Memory...................................................................................................................................... 72 7.5.1 Working with Memory Segments........................................................................................... 72 7.6 Calloc() and Realloc()............................................................................................................................. 73 7.7 Chapter Program-Math Quiz................................................................................................................... 75 Summary...................................................................................................................................................... 78 References.................................................................................................................................................... 78 Recommended Reading.............................................................................................................................. 79 Self Assessment............................................................................................................................................ 80 Chapter VIII . ............................................................................................................................................. 82 File Input and Output................................................................................................................................. 82 Aim............................................................................................................................................................... 82 Objectives..................................................................................................................................................... 82 Learning outcome......................................................................................................................................... 82 8.1 Introduction . .......................................................................................................................................... 83 8.2 Bits and Bytes......................................................................................................................................... 83 8.3 Fields, Records and Files........................................................................................................................ 83 8.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...................................................................................................................... 89 8.5 Goto andError Handling......................................................................................................................... 91 8.5.1 A Brief History of Goto.......................................................................................................... 91 8.5.2 Usage of Goto......................................................................................................................... 91 8.6 Chapter Program-The Phone Book Program.......................................................................................... 93 Summary...................................................................................................................................................... 95 References.................................................................................................................................................... 95 Recommended Reading.............................................................................................................................. 96 Self Assessment............................................................................................................................................ 97

V

List of Figures Fig. 7.1 Using the sizeof operator to determine storage requirements......................................................... 69 Fig. 7.2 U  sing the sizeof operator and simple arithmetic to determine the number of elements in an array........................................................................................................................................ 69 Fig. 7.3 Using dynamic memory to read character strings from standard input........................................... 72 Fig. 7.4 Using realloc () to expand contiguous memory segments............................................................... 75 Fig. 7.5 Using chapter­based concepts to build the Math Quiz.................................................................... 76

VI

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

VII

Chapter I ‘C’ Fundamentals Aim The aim of the chapter is to: •

explain various programming language



explicate identifiers and keywords



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: •

define operations



distinguish identifiers and keywords



understand different data types, data type qualifiers and variables

1

Introduction to C Programming

1.1 Introduction Computer 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. The computer system is classified into five main categories based on the requirement of the user. These are as discussed below. 1.1.1 Operating system It 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 software Accounting software like Tally; office automation software like Microsoft Office or designing tools like Coral Draw, Page Maker or Photoshop are available software which are developed according to the user's need. 1.1.3 Programming languages BASIC, 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 tools These are basically used in combinations. The major categories of this software include; Front end Designs screen and reports of the software. Visual Basic, Developer 2000, Visual C++ are some popular front ends. Back end DBMS 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 tools HTML, 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.

2

1.2.1 Low Level Languages These 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’ has five built-in data types and permits almost all data type conversion. ‚‚ ‘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 Keywords In ‘C’ language, every word has a keyword or an identifier. The names given to the variables by the compiler are referred to be identifiers. They refer to the name of user defined variable, arrays and functions. They should essentially be 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

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed

void

default

goto

size of

volatile

do

if

static

while

Table 1.1 Keywords The following table is the character set of ‘C’ language. letter

ABCDEFGHIJKLMNOPQRSTUVWXYZ

digit

0123456789

underscore

_

punctuation

! " # % & ' () * + , - . / ; < = > ? [ \ ] ^ { | } ~ Table 1.2 Character set of ‘C’ language

3

Introduction to C Programming

1.4 Data Types and Constants For 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 the programming languages and most database systems require the user to declare the type of each data field. The data 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

int

Floating point

float

Double floating point

double

Character

char

Void

void Table 1.3 Basic data types

Data Type

Range of values

int

- 32768 to +32767

float

3.4e-38 to 3.4e+e38

double

1.7e+308

char

-128 to 127 Table 1.4 Data type – range of values



int ‚‚ ‚‚ ‚‚ ‚‚



float ‚‚ used to define floating point numbers ‚‚ stores only floating point values ‚‚ the values should be in decimal places and it takes 32 bytes of memory to store the value on 16 bit machine



double ‚‚ used to define big floating points ‚‚ used to get the store on 16 bit machine, it requires 64 bytes of memory



char ‚‚ used to define characters ‚‚ 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

4

used to define inter numbers 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

1.4.2 Type Qualifiers Type qualifiers declare the variables along with the data types. •

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 Variables A variable is an identifier which is used to represent a specific type of information within a designated portion of a 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 using float or double data type. 1.5.1 Variable Declaration The variables are declared along with the data types so that the compiler understands which type of variable it is. General syntax used is, ; Example, ‚‚ int num ‚‚ float percent ‚‚ char grade You can use extended data types as mentioned below: ‚‚ Long int amount ‚‚ Signed int temp

5

Introduction to C Programming

1.5.2 Variable Initialisation Values are assigned for the variables through the variable initialisation. Example, int num; //variable declaration num = 1; //variable initialisation 1.5.3 Declaring Variables as Constants Constant variable values once assigned cannot be changed throughout the program. These types of variables can be declared using the keyword ‘const’. Example, consta float pi = 3.14

1.6 Operators and Expressions Individual 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’ has set of operators which can be classified as the following: 1.6.1 Arithmetic Operators •

Basic operations such as addition, subtraction, multiplication and division are performed using arithmetic operations.



% is the operator called as modulus operator and is used to find out division from the remainder.



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.



Floating point quotient is the result if a division operation is carried out with two floating point numbers or with one floating point number and one integer. Sr. No.

Operator

Meaning

1.

+

Addition or unary plus

2.

-

Subtraction or unary minus

3.

*

Multiplication

4.

/

Division

5.

%

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.

6

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

Meaning

1.




Greater than

3.



Less than or equal to

4.



Greater than or equal to

5.

=

Equal to

6.

!=

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

Meaning

1.

&&

Logical AND – True if all conditions are true

2.

||

Logical OR – True if any one or all conditions are true

3.

!

Logical NOT – Negation Table 1.7 Logical operators

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

7

Introduction to C Programming

Sr. no. Operator category

Operators

Associativity

1.

Arithmetic – multiple, divide and remainder

×, ÷, %

L→R

2.

Arithmetic – add and subtract

+, -

L→R

3.

Rational operators

, ≥

L→R

4.

Equality operators

=, !=

L→R

5.

AND

&&

L→R

6.

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.



 onditional operator is in combination of ‘? :’. This is called as tertiary operator. Its general form is, C expression 1? expression 2 : expression 3



Expression 1 is evaluated first when conditional expression is evaluated.



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 : b Here, 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 b Thus, 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.

8

Sr. No.

Operators

Meaning

1

&

Bitwise AND

2

|

Bitwise OR

3

^

Bitwise exclusive OR

4




Shift Right

1.6.7 Assignment Operators

Table 1.9 Bitwise operators



In ‘C’ language, there are several different operators that are used to form assignment expressions which assign the value of an expression to an identifier.



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 = 10 Here, value 10 is assigned to the variable b. 1.6.8 Increment and Decrement Operators Increment 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 = 1 If, x is 5, Then, after + + x or x + + , x will become 6 Or, x + + is similar to x = x + 1 -- y is similar to y = y – 1 If, x is 5, then after + + x or x + +, x will become 6 Or, y - - is similar to y = y – 1 Within variable name, increment and decrement operators can be used as prefix or postfix position.

1.7 Preprocessor Directives The ‘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, directives for the preprocessor. These lines are generally defined by a hash symbol (#). The preprocessor digests all these 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

9

Introduction to C Programming

1.7.1 Macro Expansion Consider the following program, #define UPPER 25 main ( ) { 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 been defined before ‘main ( )’ through the statement, #define UPPER 25 This statement is called ‘macro definition’ or more commonly, just a ‘macro’. During preprocessing, the preprocessor replaces every occurrence of UPPER in the program with 25. Example of macro definition, #define PI 3.1415 main ( ) { float r = 6.25 ; float area ; 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’ directive is many a times used to define operators as shown below. #define AND && #define OR || main ( ) { int f = 1, x =4, y = 90 ; if ( ( f , 5 ) AND ( x ≤ 20 OR y ≤ 45 ) ) printf ( “\nYour PC will alwys work fine…” ) ; else print (“\nIn front of the maintenance man” ) ; } A ‘#define’ directive could be used even to replace a condition. #define AND && #define ARRANGE ( a > 25 AND a < 50 ) main ( ) { 10



int a = 30 ;

if (ARRANGE) printf ( “within range” ) ; else printf ( “out of range” ) ; } A #define directive could be used to replace even an entire ‘C’ statement. #define FOUND printf ( “X virus” ) ; main ( ) { char signature ; if ( signature = =’Y’ ) FOUND else printf ( “Safe… as yet !” ) ; } 1.7.2 File Inclusion Features of file inclusion are as follows: •

If we have a very large program, the code is divided into several different files, each containing a set of related functions. It is a good programming practice to keep different sections of a large program separate. These files are ‘#included’ at the beginning of main program file.



There are some functions and some macro definitions that are needed almost in all programs that we write. These commonly used functions and macro definitions can be stored in a file and the file can be included in every program we write. This would add all the statements in the file to our program as if we have typed them in.



There are two ways to write ‘#include’ statement. ‚‚ #include “filename” – this command will look for the filename in the current directory as well as the specific list of directories as mentioned in the include search path that might have been set up. ‚‚ #include - this command will look for the filename in the specified list of directories only.

11

Introduction to C Programming

Summary •

Operating 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, every word has a keyword or an identifier along with a character set.



The constant value is the entity that does not change when the program is executed and it refers to a value.



‘C’ consists of various data types.- int, float, double, char and void.



Short, long, unsigned and unsigned long are the data qualifiers.



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. These are classified as- arithmetic operators, rational operator, logical operator, comma operator, 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.

References •

Dixit, 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: [Accessed 26 June 2013].



Introduction to the C Programming Language [Pdf] Available at: [Accessed 26 June 2013].



Dr. Kumar, A. S., 2008. Lecture - 1 Introduction to programming languages [Video online] Available at: [Accessed 26 June 2013].



PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts [Video online] Available at: [Accessed 26 June 2013].

Recommended Reading •

Deitel, 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.

12

Self Assessment 1. Low level languages interacts with machine __________. a. software b. hardware c. operating system d. programming language 2. In ‘C’ language, every __________ has a keyword or an identifier along with a character set. a. sentence b. line c. word d. segment 3. Increment 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. a. ' + + ' , ' - - ' b. ' - ' , ' + + ' c. ' +' , ' - -' d. ' - - ' , ' + +' 4. __________ is used to separate two or more expressions when only one expression is expected. a. Assignment operator b. Arithmetic operator c. Comma operator d. Conditional operator 5. Which of the following statements is true? a. Comma operator is in combination of ‘? :’ b. Conditional operator is in combination of ‘? :’ c. Conditional operator is in combination of ‘# :’ d. Conditional operator is in combination of ‘? .’ 6. Which of the following statements is true? a. Rational operators are required to compare the relationship between operands. b. Assignment operators are required to compare the relationship between operands. c. Rational operators are not required to compare the relationship between operands. d. Logical operators are required to compare the relationship between operands. 7. Which of the following statements is true? a. Greater than or equal to is the meaning of the operator ≤ b. Greater than or equal to is the meaning of the operator ± c. Greater than or equal to is the meaning of the operator ≠ d. Greater than or equal to is the meaning of the operator ≥

13

Introduction to C Programming

8. Which symbol is generally used to define the lines in the preprocessor directives? a. Percentage ( % ) sign b. Hash ( # ) sign c. Ampersand ( & ) sign d. Underscores ( _ ) sign 9. Identify data type qualifiers. a. Short and long b. Long and unsigned c. Long, unsigned and unsigned d. Short, long, unsigned and unsigned long 10. Which operators are required to compare the relationship between operands? a. Logical operators b. Rational operators c. Conditional operators d. Comma operators

14

Chapter II Data Input and Output Aim The aim of the chapter is to: •

explain data output and input functions



explain getchar function



define putchar function

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

15

Introduction to C Programming

2.1 Introduction Input 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 output functions do not require parameters. ‘C’ includes a collection of header files which provides the information that is necessary in support of various library functions. Studio.h is the header file that contains the information about the input or output library function.

2.2 Getchar Functions Getchar 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. The value of the symbolic constant ‘end-of-file’ will automatically be returned if it is encountered while reading a character with the getchar function.

2.3 Putchar Function The 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 getchar and putchar except that they can operate on files other than the standard input and output. The getc function is called with one argument. The expression getc(stdin) is similar to getchar( ) and the expression putc(c, stdout) is same as putchar(c).

16

2.4 Scanf( ) Function Scanf( ) 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 information Parameter 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 character

2

d

type of data item is decimal integer

3

e

type of data item is floating – point value

4

f

type of data item is floating point value

5

h

type of data item is short – integer

6

i

type of data item is decimal, hexadecimal or octal integer

7

o

type of data item is octal integer

8

s

type of data item is string

9

u

type of data item is unsigned decimal integer

10

[. . .]

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( ) Function This 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 17

Introduction to C Programming

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. There are two modifiers of printf( ) function. Long integer is used to display long data type and short integer is used to display short data type.

2.6 Gets ( ) and Puts ( ) Functions Gets 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.

18

Summary •

Input 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.

References •

Goel, A., Computer programming-I: As per the first-year engineering syllabus of University of Mumbai, Pearson Education India.



Veerana, V. K. & Jankidevi, S. J., 2007. C for U Including C and C Graphics, Firewall Media.



Kernighan, W. B. & Ritchie, M. D., 1988. The C programming Language [Pdf] Available at: [Accessed 26 June 2013].



Input and Output in C [Pdf] Available at: [Accessed 26 June 2013].



Introduction to C Programming I [Video online] Available at: [Accessed 26 June 2013].



C Programming Tutorial: Input Output (printf, scanf, format specifiers) Lesson 1 [Video online] Available at: [Accessed 26 June 2013].

Recommended Reading •

Rajaraman, V., 1994. COMPUTER PROGRAMMING IN C, PHI Learning Pvt. Ltd.



Reddy, R. & Ziegler, C., 2009. C Programming for Scientists and Engineers with Applications, Jones & Bartlett Learning.



Dixit, J.B., 2006. Comprehensive Programming in C and Numerical Analysis, Laxmi Publications.

19

Introduction to C Programming

Self Assessment 1. Parameters of the printf function can be written as constants, __________ variables or array names or more complex expressions. a. double b. triple c. single d. external 2. The meaning of conversion character __________ is type of data item is decimal, hexadecimal or octal integer. a. S b. U c. O d. I 3. By reading one character at a time within a multipass loop, __________ can also be used to read multicharacter strings. a. getchar function b. putchar function c. printf function d. scanf function 4. Which of the following statements is true? a. Parameters in printf function do not represent memory addresses, unlike scanf function and thus they are not preceded by ampersand (&) sign. b. Parameters in printf function do not represent memory addresses, unlike scanf function and thus they are not preceded by percentage (%) sign. c. Parameters in printf function do not represent memory addresses, unlike scanf function and thus they are not preceded by hash (#) sign. d. Parameters in scanf function do not represent memory addresses, unlike scanf function and thus they are not preceded by ampersand (&) sign. 5. Which of the following statements is true? a. In scanf function if two characters are entered, they must be separated by white space characters. b. In scanf function if two or more characters are entered, they must not be separated by white space characters. c. In printf function if two or more characters are entered, they must be separated by white space characters. d. In scanf function if two or more characters are entered, they must be separated by white space characters. 6. Which of the following statements is true? a. Type of data item is short – integer is the meaning of conversion character I. b. Type of data item is short – integer is the meaning of conversion character H. c. Type of data item is short – integer is the meaning of conversion character S. d. Type of data item is short – integer is the meaning of conversion character U.

20

7. Which function reads a single character from standard input? a. getchar b. putchar c. printf d. scanf 8. Parameter of which function must be data item that represents a string and the string may include whitespace characters. a. printf b. scanf c. putchar d. gets and puts 9. Type of data item is string which may include whitespace characters is the meaning of which conversion character? a. S b. [. . .] c. U d. I 10. The expression getc(stdin) and putc(c, stdout) are similar to which functions? a. getchar(c) and putchar(c) b. scanf() and printf() c. scanf ( ) d. printf ( )

21

Introduction to C Programming

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: •

define if statement



define if else construct



understand iteration loop, do while loop, for loop

22

3.1 Introduction Control statements are the statements in ‘C’ language that can alter the flow of a sequence of instruction. It is used to 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 10 && (b < 15 || c < 20 ) ) ‚‚ The statement within the loop may be a single line or a block of statements. in the first case the parentheses 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) ; } 24

This is an indefinite loop, since ‘i’ remains equal to 1 forever. 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; } } It is not necessary that a loop counter must only be an ‘int’. It can even be ‘float’. Example: main ( ) { float a = 10.0 ; while ( a ≤ 10.5 ) { printf ( “\nRaindrops on roses.....” ) ; printf ( “....and whiskers on kittens” ) ; a = a + 0.1 ; } } Even floating point loop counters can be decremented. Once again the increment and decrement could be by any value, 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 first and then the loop condition is checked.



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: 25

Introduction to C Programming

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 Statement In ‘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 Statement In ‘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 ) ; } } }

26

The output of the above program would be, 12 2 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 flow of execution of a program. It is often used to check whether the condition is true to not. In ‘if’ statement, only true parts are included. It is the first loop used for making any decision. If the expression is evaluated and if it is true, 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 1 else 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 Statement To 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: 27

Introduction to C Programming

__ _ _ 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 28

{ }

__ __

3.10 Iteration Statement Depending 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 ( ) { } 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 Statement •

Goto 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 : /* define the label ‘here’ */ /* . . */

Conditional and unconditional goto are the two types of goto statements used in a computer program. 3.12.1 Conditional Goto Under 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 Goto To transfer the control from one part of the program to the other part without checking any conditions, unconditional goto is used.

29

Introduction to C Programming

Summary •

Control statements are the statements in ‘C’ language that can alter the flow of a sequence of instruction. These statements enable the user to jump from one program to another.



‘If’ statement is used in making a decision and allowing the flow of execution of a program.



‘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.

References •

Ashok, 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: [Accessed 26 June 2013].



Program Control Statements [Pdf] Available at: [Accessed 26 June 2013].



Control Statements in Programming Languages (final) part1 [Video online] Available at: [Accessed 26 June 2013].



Control statements in programming languages-part 1-pldc [Video online] Available at: [Accessed 26 June 2013].

Recommended Reading •

Balagurusamy, E., Programming In Ansi C, 5E, Tata McGraw-Hill Education.



Krishnamoorthy, 2010. DATA STRUCTURES USING C, Tata McGraw-Hill Education.



Hanly, 2009. Programming In C And Data Structures (For Jntu), Pearson Education India.

30

Self Assessment 1. __________ statement is often used in making a decision and allowing the execution of a program. a. if else b. do while c. do d. if 2. The __________ loop tests at the bottom of the loop after executing the body of the loop. a. switch b. goto c. do while d. continue 3. ‘While’ statement is the simplest of all __________ structures. a. looping b. control c. programming d. data type 4. Which of the following statements is true? a. do while statements enable the user to jump from one program to another. b. control statements enable the user to jump from one program to another. c. while statements enable the user to jump from one program to another. d. goto statements enable the user to jump from one program to another. 5. Which of the following statements is true? a. The goto statement is marked by a control statement. b. The control statement is marked by a goto statement. c. The do while statement is marked by a label statement. d. The goto statement is marked by a label statement. 6. Which of the following statements is true? a. if else statement is not used to express decision. b. if else statement is used to express decision. c. goto statement is used to express decision. d. control statement is used to express decision. 7. Which of the following statements is true? a. break statements are not used with switch statements. b. control statements are generally used with switch statements. c. break statements are generally used with switch statements. d. break statements are generally used with goto statements.

31

Introduction to C Programming

8. Which statement is the simplest of all looping structures? a. while statement b. do while statement c. switch statement d. goto statement 9. What provides a more concise loop control structure? a. switch statement b. beak statement c. goto statement d. for loop 10. On what do the iterative statements depend to repeat the execution of the list of the statements? a. Case label b. Default case label c. Integer expression d. Case expression

32

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



define array and strings



explicate elements of multidimensional array

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

define and describe array



define array functions



understand strings

33

Introduction to C Programming

4.1 Introduction •

Array type is a data type. It is a variable that holds multiple elements which has the same data type.



It is the capability that enables the user to define a set of ordered data items.



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 Array •

An array must be declared before they are used like any other variable.



An array can be specified by its name, data type such as int, float, char, and the size indicates the number of element that can be stored inside the array.



A simple array syntax is mentioned below: data_type array_name[size]

4.3 Initialisation of Array •

The 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 Array Arrays are classified into three types as follows: ‚‚ single dimensional array ‚‚ two dimensional array ‚‚ multidimensional array 34

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.



Specifying the data type of the elements which are going to be stored in an array is the first requirement while 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.



The size value is called the subscript number which defines the maximum number of elements allowed to be 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.



The number of rows and columns are specified in two dimensional arrays.



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]



The above syntax defines two dimensional arrays where rows and column are constants.



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

35

Introduction to C Programming

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 Array The 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 } In the above example, the array initialises the elements of the first row to zero and those in the second row to 1. 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 Strings •

In ‘C’ language, strings are the arrays of ‘char’ object. In other words, these are defined as the arrays of characters.



An array of string can be declared like a two dimensional array.



The string characters are compiled to an array of specific character value with an additional null terminating 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 \\ \“ \‘ \n \r \b \t \f \a \v \? \ nnn \ xhh

Meaning Literal backslash Double quote Single quote Newline Carriage return Backspace Horizontal tab Form feed Alert Vertical tab Question mark Character with octal value nnn Character with hexadecimal value hh Table 4.2 Backslash escape

36

4.5.1 String Functions strcat (dest, source)

Appends the string ‘source’ to the end of the string ‘dest’

Strchr (s, c)

Finds the first instance of character ‘c’ in string ‘s’ and returns a pointer to it or a null 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)

Compare two strings according to a locale-specific collating sequence

Strcspn (s1, s2)

Returns the index of the first character in ‘s1’ that matches any character in ‘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)

Returns a pointer to the first character in ‘s1’ that matches any character in s2 or a null pointer if not found

Strspn (s1. s2)

Returns the index of the first character in ‘s1’ that matches no character in s2

Strstr (st, subst)

Returns a pointer to the first occurrence of the string ‘subst’ in St’ 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

37

Introduction to C Programming

4.6 Passing Array to Functions Array 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

38

Summary •

Array 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.

References •

Hoover, 2009. System Programming With C And Unix, Pearson Education India.



Laitinen, K., 2004. A Natural Introduction to Computer Programming with C#, Trafford Publishing.



Arrays and Strings [Pdf] Available at: [Accessed 26 June 2013].



Lecture 7: Arrays, strings, and functions [Pdf] Available at: [Accessed 26 June 2013].



C Programming Tutorial: Arrays (One and Two Dimensional Array ): Lesson 2 [Video online] Available at: [Accessed 26 June 2013].



C Programming Tutorial 44 - Strings and Characters [Video online] Available at: [Accessed 26 June 2013].

Recommended Reading •

Malik, D. S., 2012. C++ Programming: From Problem Analysis to Program Design, 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.

39

Introduction to C Programming

Self Assessment 1. Variables are called __________ in ‘C’ language. a. groups b. grades c. loops d. arrays 2. data_type array_name[size] is an __________. a. initialisation array syntax b. array syntax c. declaration array syntax d. multidimensional array syntax 3. The multidimensional array is stored in __________. a. column major order b. rows c. columns d. row major order 4. Which of the following statements is true? a. Type array_name [size] = (list of values) is a general form of initialisation of an array. b. Type array_name [size] = (list of variables) is a general form of initialisation of an array. c. Type array_name [ ] = (list of values) is a general form of initialisation of an array. d. Type array_name [ ] = (list of variables) is a general form of initialisation of an array. 5. Which of the following statements is true? a. \ xhh is the meaning of the character with decimal value hh. b. \ xhh is the meaning of the character with hexadecimal value h. c. \ xhh is the meaning of the character with hexadecimal value hh. d. \ xhh is the meaning of the character with decimal value hhh. 6. Which of the following statements is true? a. Strings are the arrays of ‘float’ object. b. Strings are the arrays of ‘char’ object. c. Strings are the arrays of ‘int’ object. d. Strings are the arrays of ‘void’ object. 7. Which of the following statements is true? a. While declaring 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. b. While initialising an array the user has to provide declaring values which are enclosed by the curly brackets in the declaration followed by an equal sign after the array name. c. While initialising an array the user has to provide initialising variable and values which are enclosed by the curly brackets in the declaration followed by an equal sign after the array name. d. 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.

40

8. What is the meaning of the escape \ n? a. horizontal tab b. vertical tab c. newline d. double quote 9. Identify multidimensional array syntax. a. float array2d [ ROWS ] [ COLUMNS ] ; b. int array2d [ ROWS ] [ COLUMNS ] ; c. void array2d [ ROWS ] [ COLUMNS ] ; d. int arrad [ ROWS ] [ COLUMNS ] ; 10. What is the meaning of the escape ( \ “ ) ? a. double quote b. single quote c. backslash d. newline

41

Introduction to C Programming

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

42

5.1 Introduction to Functions •

In ‘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.



When a function body is written, we call it a function definition. Writing of instructions which perform required actions in the program are included in function definition.



When a program is large and difficult to debug or test, the program is divided into sub programs and compiled 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 Functions •

Writing 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 Functions We need to write some steps for writing the user defined functions. While including these functions in the program, the following three sections are mainly used: •

Function declaration



Function call



Function definition

5.3.1 Function Declaration •

Function declaration is very similar to variable declaration.



When the user is in need of some variables in the program, the first step is to declare them. Like wise, if we 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, by default it returns an ‘int’ value. More specifically, whenever a call is made to a function, 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.

43

Introduction to C Programming



Suppose we want to find out square of a number using function, consider following simple program.

main ( ) { float a, b ;

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

}

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

square ( float x ) { float y ; }

y=x*x; return ( y ) ;

The sample runs of this program are mentioned below: Enter any number - 3 Square of 3 is 9.000000 Enter any number 1.5 Square of 1.5 is 2.000000 Enter any number 2.5 Square of 2.5 is 6.000000 The first answer among the three is correct. The square of 1.5 is definitely not 2, nor is 6 a square of 2.5. This happened 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 ( )’ is not capable of returning a ‘float’ value to overcome this. Let us consider the following program segment to illustrate how to make ‘square( )’ capable of returning a ‘float’ value. main ( ) { float square ( float ) ; float a, b printf ( “\nEnter any number” ) ; scanf ( “%f”, &a ) ; }

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

float square ( float x ) ; { float y ; y=x*x; 44

}

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, float square ( float ) ; This statements is often called a prototype declaration of the ‘square ( )’ function. What it means is ‘square ( )’ is a function that receives a ‘float’ and returns a ‘float’. We have done the prototype declaration in ‘main ( )’ because we 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.



Values may get conflicted or interchanged in complicated and large programs making it is risky to call function 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.



Call by reference works more efficiently than call by value. 45

Introduction to C Programming

5.3.3 Function Definition •

The actual statements that are to be executed are included in the function definition.



After the completion of main ( ) function, the function definition is done.

5.4 Scope and Lifetime of Variables •

A 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 ( ) { extern float amt; __ __ } fun1( ) { extern float y: / / declarations __ } float y; / / definition 46

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 Values •

These 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: return or return (expression)



5.6 Function Categories The 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 Values 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.

47

Introduction to C Programming

5.6.2 Functions with Arguments and No Return Values •

The called function receives the actual arguments that we pass in its definition as formal parameters. But no out 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’ or an array or pointer.

5.6.3 Functions with No Arguments and Return Values The 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 Values This function returns a value of required data type.

5.7 Recursion A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself. 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 - 3 Factorial value = 6

5.8 Introduction to Structure •

Structure 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.

48

Consider the example, main ( ) { struct book { char name ; float price ; 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. All a structure declaration does is, it defines the ‘form’ of the structure.



Usually the structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs, they are put in a separate header file, and the file is included (using the pre-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 use a dot (.) operator. So to refer to ‘pages’ of the structure defined in our sample program we have to use, b1.pages • Similarly, to refer to ‘price’ we have to use, b1.price 49

Introduction to C Programming

5.8.3 Process of Storing Structure Elements Whatever 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 ; float price ; 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 = 65518 Address of price = 65579 Address of pages = 65523

5.9 Array of Structures •

Structure 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 ; float price ; 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 ) ; 50

} for ( i = 0 ; i ≤ 99, i ++ ) printf ( “\n%c %f %d”, b[i].name, b[i].price, b[i].pages ) ; } linkboat ( ) { float a = 0, *b ; b = &a ; /* cause emulator to be linked */ a = *b ; /* suppress the warning – variable not used */ }

5.10 Additional Features of Structures The 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 ; float salary ; }; 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.

51

Introduction to C Programming

5.11 Uses of Structures •

changing 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



finding out the list of equipment attached to the computer



formatting a floppy



hiding a file from the directory



displaying the directory of a disk



sending the output to printer



interacting with the mouse

5.12 Unions Like 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.

52

Summary •

Function 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.



The called function receives the actual arguments that we pass in its definition as formal parameters.



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.

References •

Deshpande, 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: [Accessed 26 June 2013].



Data Structures Using C [Pdf] Available at: [Accessed 26 June 2013].



C Programming Classes - Structure in C language [Video online] Available at: [Accessed 26 June 2013].



Functions in C Programming [Video online] Available at: [Accessed 26 June 2013].

Recommended Reading •

Nair, 2009. Data Structures In C, PHI Learning Pvt. Ltd.



Puntambekar, A. A., 2008. Data Structures With C, Technical Publications.



Reddy, R. & Ziegler, C., 2009. C Programming for Scientists and Engineers with Applications, Jones & Bartlett Learning.

53

Introduction to C Programming

Self Assessment 1. When we call function by passing normal values or variables, the function call is called __________. a. call by reference b. call by value c. call by variable d. reference 2. Array of structures is used to store more than ________ record. a. one b. three c. two d. four 3. Recursion is one of the _________ properties. a. array b. pointer c. function d. variable 4. The __________ remains alive till the end of the program. a. static external variable b. internal variable c. static internal variable d. external variable 5. Which of the following statements is true? a. The function which calls a value is called call by value function. b. The function which does not calls a function is called calling function. c. The function which calls a reference is called call by reference function. d. The function which calls a function is called calling function. 6. Which of the following statements is true? a. A period in which the values hold the given variable at the time of program execution is called lifetime of variables. b. A period in which the variables hold the given value is called lifetime of variables. c. A period in which the variables hold the given value at the time of program execution is called lifetime of variables. d. A period in which the variables hold the given value at the time of program execution is called lifetime of values. 7. Which of the following statements is true? a. 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. b. If we pass the values of variables at the time call, instead of passing variables or values, then function call is called call by reference. c. If we pass the reference of variables or values at the time call, instead of passing functions, then function call is called call by reference. d. 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 value. 54

8. What can be declared in both the main ( ) as well as above main ( )? a. internal declaration b. external declaration c. external values d. static variables 9. Which function receives the actual arguments that we pass in its definition as formal parameters? a. Called function b. Call by reference c. Call by value d. Global function 10. Which functions are declared above the main ( ) as they are accessible throughout the program? a. Local function b. Static function c. Static internal function d. Global function

55

Introduction to C Programming

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: •

define pointers



understand pointer arithmatic



describe pointer with function

56

6.1 Introduction •

Pointer 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.



The pointers are one of the powerful tools of ‘C’ programming. They are very efficient. There are many advantages 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 Declaration • A 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 Operator •

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.



The amount of memory needed for it is assigned at a specific location in memory, as soon as the variable is 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.



The reference to a variable can be obtained by preceding the identifier of a variable with an ampersand (&) sign, known as reference operator and can be translated as ‘address of’. Example, A = &B Here, 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. •

The concept of reference must not be confused with other values namely; identifiers or keys that uniquely identify 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.

57

Introduction to C Programming



References increase flexibility where the objects are stored, how they are allocated and how they are passed 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 Operator •

Dereference 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 Arithmetic •

Pointer 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’ language supports five arithmetic operators on pointers. Those are given below: ‚‚ Increment (++) ‚‚ Decrement (++) ‚‚ Addition(+) ‚‚ Subtraction (-) ‚‚ Differencing

58

6.5.1 Increment (++) Increment of pointer depends on the data type like 2 for ‘int’, 4 for ‘float’. 6.5.2 Decrement (--) Decrement of pointer also depends on the type like 2 for ‘int’, 4 for ‘float’. 6.5.3 Addition (+) and Subtraction (-) ‘C’ supports to add and subtract integer from pointer. 6.5.4 Differencing Subtraction of two pointers is called as differencing. Example, #include #include Void main ( ) { int i [ ] = {4,5,21,7}, *pointer, j; }

clrscr( ); pointer = & i; for (j = 1;j=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",£s); }

102

Applications III A program for bomber fighter plane simulation. #include #include #include #include #include void main ( ) { int gd = DETECT, gm ; float x1, x2, y1, y2, dx, co, j ; int flag=0 ; float distance, B_SPEED, F_SPEED ; initgraph (&gd, &gm. ″ ″ ) ; cleardevice ( ) ; textcolor (RED) ; printf ( ″Enter the Speed of Bomber Plane (1 to 20) : ″ ) ; scanf ( ″%f″, &B_SPEED) ; printf ( ″ENTER the Speed of Fighter Plane (1 to 20) : ″ ) ; 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 ( ″FIGHTER X2 : %2f, Y2 : %2f″, x2, y2) ; distance = pow ( (x1=x2), 2) + pow ( (y1-y2), 2) ; distance = sqrt (distance) ; gotoxy (1, 3) ; printf ( ″DISTANCE BETWEEN BOTH PLANE : %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) ; 103

Introduction to C Programming

fillellipse (x2, y2, 5, 5) ; outtextxy (x2=20, y2, ″FIGHTER″) ; if (distance≤50) { flag = 1 ; for (int i=0; i