You are on page 1of 106

Programming in ‘C’ and Data Structure

Board of Studies

Prof. H. N. Verma Prof. M. K. Ghadoliya


Vice- Chancellor Director,
Jaipur National University, Jaipur School of Distance Education and Learning
Jaipur National University, Jaipur
Dr. Rajendra Takale
Prof. and Head Academics
SBPIM, Pune

___________________________________________________________________________________________
Subject Expert Panel

Dr. Ramchandra G. Pawar Ashwini Pandit


Director, SIBACA, Lonavala Subject Matter Expert
Pune

___________________________________________________________________________________________
Content Review Panel

Gaurav Modi Shubhada Pawar


Subject Matter Expert Subject Matter Expert

___________________________________________________________________________________________
Copyright ©

This book contains the course content for Programming in ‘C’ and Data Structure.

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

V. Bibliography............................................................. 93

VI. Self Assessment Answers........................................ 96

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 Long........................................................................................................................... 5
1.4.2.2 Unsigned.................................................................................................................... 5
1.4.2.3 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...................................................................................................................... 9
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..................................................................................................................... 37
Summary...................................................................................................................................................... 38
References.................................................................................................................................................... 38
Recommended Reading.............................................................................................................................. 38
Self Assessment............................................................................................................................................ 39

III
Chapter V..................................................................................................................................................... 41
Functions and Structures........................................................................................................................... 41
Aim............................................................................................................................................................... 41
Objectives..................................................................................................................................................... 41
Learning outcome......................................................................................................................................... 41
5.1 Introduction to Functions........................................................................................................................ 42
5.2 Uses of Functions.................................................................................................................................... 42
5.3 Elements of User Defined Functions...................................................................................................... 42
5.3.1 Function Declaration............................................................................................................... 42
5.3.2 Function Call........................................................................................................................... 44
5.3.2.1 Call by Value............................................................................................................ 44
5.3.2.2 Call by Reference..................................................................................................... 44
5.3.3 Function Definition................................................................................................................. 44
5.4 Scope and Lifetime of Variables............................................................................................................. 45
5.4.1 Automatic Variables................................................................................................................ 45
5.4.2 External Variables................................................................................................................... 45
5.4.3 External Declaration............................................................................................................... 45
5.4.4 Static Variables....................................................................................................................... 46
5.4.5 Register Variables................................................................................................................... 46
5.5 Return Values.......................................................................................................................................... 46
5.6 Function Categories................................................................................................................................ 46
5.6.1 Functions with No Arguments and No Return Values............................................................ 46
5.6.2 Functions with Arguments and No Return Values.................................................................. 46
5.6.3 Functions with No Arguments and Return Values.................................................................. 47
5.6.4 Functions with Arguments and Returning Values................................................................... 47
5.7 Recursion................................................................................................................................................ 47
5.8 Introduction to Structure......................................................................................................................... 47
5.8.1 Declaring of a Structure.......................................................................................................... 48
5.8.2 Accessing Structure Elements................................................................................................. 48
5.8.3 Process of Storing Structure Elements.................................................................................... 49
5.9 Array of Structures.................................................................................................................................. 49
5.10 Additional Features of Structures.......................................................................................................... 50
5.11 Uses of Structures................................................................................................................................. 51
5.12 Unions................................................................................................................................................... 51
Summary...................................................................................................................................................... 52
References.................................................................................................................................................... 52
Recommended Reading.............................................................................................................................. 52
Self Assessment............................................................................................................................................ 53

Chapter VI................................................................................................................................................... 55
Pointers........................................................................................................................................................ 55
Aim............................................................................................................................................................... 55
Objectives..................................................................................................................................................... 55
Learning outcome......................................................................................................................................... 55
6.1 Introduction............................................................................................................................................. 56
6.2 Pointer Declaration................................................................................................................................. 56
6.3 Reference Operator................................................................................................................................. 56
6.4 Dereference Operator.............................................................................................................................. 57
6.5 Pointer Arithmetic................................................................................................................................... 57
6.5.1 Increment (++)........................................................................................................................ 58
6.5.2 Decrement (--)......................................................................................................................... 58
6.5.3 Addition (+) and Subtraction (-)............................................................................................. 58
6.5.4 Differencing............................................................................................................................ 58
6.6 Pointers with Function............................................................................................................................ 58
6.6.1 Call by Value........................................................................................................................... 59

IV
6.6.2 Call by Reference.................................................................................................................... 59
6.6.3 Callback Functions................................................................................................................. 59
6.7 Function Pointer Syntax.......................................................................................................................... 59
6.8 Initialising Function Pointer................................................................................................................... 59
6.9 Using Function Pointer........................................................................................................................... 60
6.10 Arrays and Pointer................................................................................................................................. 60
6.11 Array of Pointers................................................................................................................................... 61
6.12 Pointers with Structures........................................................................................................................ 61
6.13 Pointers on Pointer................................................................................................................................ 61
Summary...................................................................................................................................................... 63
References.................................................................................................................................................... 63
Recommended Reading.............................................................................................................................. 63
Self Assessment............................................................................................................................................ 64

Chapter VII................................................................................................................................................. 66
Introduction to Data Structure.................................................................................................................. 66
Aim............................................................................................................................................................... 66
Objectives..................................................................................................................................................... 66
Learning outcome......................................................................................................................................... 66
7.1 Introduction............................................................................................................................................. 67
7.2 Types of Data Structure........................................................................................................................... 67
7.3 Linear Data Structure.............................................................................................................................. 67
7.4 Types of Linear Data Structure............................................................................................................... 67
7.4.1 Array....................................................................................................................................... 67
7.4.2 Linear Link List...................................................................................................................... 71
7.4.3 Stack........................................................................................................................................ 73
7.4.4 Queues.................................................................................................................................... 74
7.5 Non-Linear Data Structure...................................................................................................................... 76
7.5.1 Tree......................................................................................................................................... 76
7.5.1.1 Definition of Tree..................................................................................................... 76
7.5.1.2 Types of Trees.......................................................................................................... 76
7.5.1.3 Tree Terminology..................................................................................................... 76
7.5.1.4 Rooted Tree.............................................................................................................. 77
7.5.1.5 Ordered Tree............................................................................................................. 78
7.5.1.6 Binary Trees............................................................................................................. 78
7.5.1.7 Example of Trees...................................................................................................... 79
7.5.1.8 Binary Search Tree................................................................................................... 80
7.5.1.9 ++ Tree Traversal Types........................................................................................... 81
7.5.1.10 Traversal Method................................................................................................... 82
Summary...................................................................................................................................................... 83
References.................................................................................................................................................... 83
Recommended Reading.............................................................................................................................. 83
Self Assessment . ......................................................................................................................................... 84

V
List of Figures
Fig. 7.1 Classification of data structures....................................................................................................... 67
Fig. 7.2 Visual example of Array.................................................................................................................. 68
Fig. 7.3 Inserting element............................................................................................................................. 70
Fig. 7.4 Linear link list.................................................................................................................................. 72
Fig. 7.5 Stack................................................................................................................................................ 73
Fig. 7.6 Stack physical view......................................................................................................................... 74
Fig. 7.7 Queue............................................................................................................................................... 75
Fig. 7.8 Queue physical view........................................................................................................................ 75
Fig. 7.9 Tree.................................................................................................................................................. 76
Fig. 7.10 Tree terminology........................................................................................................................... 77
Fig. 7.11 Rooted tree..................................................................................................................................... 78
Fig. 7.12 Binary tree..................................................................................................................................... 78
Fig. 7.13 Example of trees............................................................................................................................ 79
Fig. 7.14 Binary search tree’s example......................................................................................................... 80

VI
List of Tables
Table 1.1 Keywords........................................................................................................................................ 3
Table 1.2 Character set.................................................................................................................................... 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............................................................................................................................. 8
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

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
Programming in ‘C’ and Data Structure

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.

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

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

3
Programming in ‘C’ and Data Structure

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
‚‚ 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
• 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
1.4.2 Type Qualifiers
Type qualifiers declare the variables along with the data types.

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,

<data type> <variable name>;

Example,
• int num
• float percent
• char grade

You can use extended data types as mentioned below:


• Long int amount
• Signed int temp

5
Programming in ‘C’ and Data Structure

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 vari-
ables 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. < Less than
2. > 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.

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

7
Programming in ‘C’ and Data Structure

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.
• Conditional operator is in combination of ‘? :’. This is called as tertiary operator. Its general form is, 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.

Sr. Operators Meaning


No.
1 & Bitwise AND
2 | Bitwise OR
3 ^ Bitwise exclusive
OR
4 << Shift Lift
5 >> Shift Right

Table 1.9 Bitwise operators

8
1.6.7 Assignment 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 newline character is found. By preceding the newline 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

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 ) ;

9
Programming in ‘C’ and Data Structure

}
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 ( )
{
int a = 30 ;

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

10
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 <filename> - this command will look for the filename in the specified list of directories only.

11
Programming in ‘C’ and Data Structure

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.
• Further, the programming languages are divided into two main types:
‚‚ low level programming language
‚‚ high level programming language
• 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: <http://retis.
sssup.it/~lipari/courses/infbase2012/03.c_intro-handout.pdf> [Accessed 26 June 2013].
• Introduction to the C Programming Language [Pdf] Available at: <http://163.25.99.51/Huang_Computer/
Programming%20Language-website2.pdf> [Accessed 26 June 2013].
• Dr. Kumar, A. S., 2008. Lecture - 1 Introduction to programming languages [Video online] Available at: <http://
www.youtube.com/watch?v=EbNJ05EVXs0> [Accessed 26 June 2013].
• PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts [Video online] Available at:
<http://www.youtube.com/watch?v=c_sDgHgNR6w> [Accessed 26 June 2013].

Recommended 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
Programming in ‘C’ and Data Structure

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

• explicate 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 out function

15
Programming in ‘C’ and Data Structure

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 Meaning


character
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
each output data item. Each character group must start with a percent sign (%) followed by a conversion character

17
Programming in ‘C’ and Data Structure

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: <http://net.pku.
edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf> [Accessed 26 June 2013].
• Input and Output in C [Pdf] Available at: <http://www.prog2impress.com/downloads/Input%20and%20
Output%20in%20C.pdf> [Accessed 26 June 2013].
• Introduction to C Programming I [Video online] Available at: <http://www.youtube.com/watch?v=fUcSXbQn
rLI&list=PL66D13A5B3585C213> [Accessed 26 June 2013].
• C Programming Tutorial: Input Output (printf, scanf, format specifiers) Lesson 1 [Video online] Available at:
<http://www.youtube.com/watch?v=5v7h4ZmgMvw> [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
Programming in ‘C’ and Data Structure

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
Programming in ‘C’ and Data Structure

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<b

3.2 Loops
The versatility of the computer lies in its ability to perform a set of instruction repeatedly. This involves some portion
of the program, either a specified number of times or until a particular condition is being satisfied. This repetitive
operation is done through a loop control instructions. There are three methods by which we can repeat a part of a
program. They are as follow:
• using a ‘for’ statement
• using a ‘while’ statement
• using a ‘do-while’ statements

3.2.1 For Loop Statement


• The ‘for’ loop provides a more concise loop control structure.
• It is used to repeat the actions given within the limit. ‘for’ statement has three conditions as follows:
‚‚ initial condition – from where the loop execution starts
‚‚ final condition – it is a test condition
‚‚ increment or decrement - directs loop how to proceed
• As long as the test condition is being a newline or a carriage return, the for loop is used to read a character from
the keyboard.
• The ‘for’ loop allows us to specify two things about a loop in a single line. These are:
‚‚ setting a loop counter to an initial value testing the loop counter to determine whether its value has reached
the number of repetitions desired.
• General form of ‘for’ statement is:

for (initialise counter ; test counter ; increment counter)


{
do this ;
and this ;
and this ;
}

3.2.1.1 Execution of ‘For’ Statement


• When the ‘for’ statement is executed for the first time, the value of ‘count’ is set to an initial value 1.
• Now the condition ‘count ≤ 3’ is tested. Since ‘count’s 1, the condition is satisfied and the body of the loop is
executed for the first time.
• Upon reaching the closing brace of ‘for’, control is sent back to the ‘for’ statement, where the value of ‘count’
gets incremented by 1.
• Again the test is performed to check whether the new value of ‘count’ exceeds 3.
• If the value of ‘count’ is still within the range 1 -3, the statements within the braces of ‘for’ are executed
again.
• The body of the ‘for’ loop continues to get executed till ‘count’ doesn’t exceed the final value 3.
• When ‘count’ reaches the value 4, the control exits from the loop and is transferred to the statement (if any)
immediately after the body of ‘for’.

23
Programming in ‘C’ and Data Structure

3.2.2 While Loop


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

While ( test condition )


{
Body of the loop
}

• The following points are to be noted about ‘while’ loop:


‚‚ The statements within the ‘while’ loop would keep on getting executed till the condition under testing
remains true. When the condition becomes false, the control passes to the first statement that follows the
body of the ‘while’ loop.
‚‚ Any other valid expression can be used in place of the condition. So as long as the expression evaluates to
a non-zero value, the statements within the loop would get executed.
‚‚ The condition being tested may use logical operators.The following example may be considered:

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

‚‚ 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
Programming in ‘C’ and Data Structure

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
Programming in ‘C’ and Data Structure

__
_ _ 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 ( <integer expression> ) {


<statement list>
}

The representation above is a simple iteration statement syntax.


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

3.11 Nested For


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

3.12 Goto 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
Programming in ‘C’ and Data Structure

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: <http://download.nos.org/srsec330/330L9.pdf> [Accessed 26 June
2013].
• Program Control Statements [Pdf] Available at: <http://www.uotechnology.edu.iq/dep-eee/lectures/1st/
Computer%20science/2.pdf> [Accessed 26 June 2013].
• Control Statements in Programming Languages (final) part1 [Video online] Available at: <http://www.youtube.
com/watch?v=hX0Rrq8ouxY> [Accessed 26 June 2013].
• Control statements in programming languages-part 1-pldc [Video online] Available at: <http://www.youtube.
com/watch?v=ageuh_4_J9E> [Accessed 26 June 2013].

Recommended 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
Programming in ‘C’ and Data Structure

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

• describe array functions

• understand strings

33
Programming in ‘C’ and Data Structure

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
Programming in ‘C’ and Data Structure

4.4.2.1 Elements of Multidimensional Array

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


35.5 40.5 45.5
Marks [1][0] Marks [1][1] Marks [1][2]
50.5 55.5 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 Meaning
\\ Literal backslash
\“ Double quote
\‘ Single quote
\n Newline
\r Carriage return
\b Backspace
\t Horizontal tab
\f Form feed
\a Alert
\v Vertical tab
\? Question mark
\ nnn Character with octal value nnn
\ xhh Character with hexadecimal value hh

Table 4.2 Backslash escape

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

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

37
Programming in ‘C’ and Data Structure

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: <http://pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/10-
ArraysAndStrings.pdf> [Accessed 26 June 2013].
• Lecture 7: Arrays, strings, and functions [Pdf] Available at: <http://www.stanford.edu/~fringer/teaching/
operating_systems_03/handouts/lecture7.pdf> [Accessed 26 June 2013].
• C Programming Tutorial: Arrays (One and Two Dimensional Array ): Lesson 2 [Video online] Available at:
<http://www.youtube.com/watch?v=NFJMjgXb0uA> [Accessed 26 June 2013].
• C Programming Tutorial 44 - Strings and Characters [Video online] Available at: <http://www.youtube.com/
watch?v=EJBb8nQD-4g> [Accessed 26 June 2013].

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

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

39
Programming in ‘C’ and Data Structure

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

40
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

41
Programming in ‘C’ and Data Structure

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.
• Suppose we want to find out square of a number using function, consider following simple program.

42
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;
return ( y ) ;
}

43
Programming in ‘C’ and Data Structure

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.

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.

44
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

45
Programming in ‘C’ and Data Structure

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.

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.

46
• 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.

Consider the example,

main ( )
{
struct book

47
Programming in ‘C’ and Data Structure

{
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

48
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 ) ;

49
Programming in ‘C’ and Data Structure

}

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.

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

51
Programming in ‘C’ and Data Structure

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: <http://www.nada.kth.se/kurser/master/intro/Course03-04/Handouts/
Flecture05.pdf> [Accessed 26 June 2013].
• Data Structures Using C [Pdf] Available at: <http://www.gatesit.org/gitdownloads/C&DS.pdf> [Accessed 26
June 2013].
• C Programming Classes - Structure in C language [Video online] Available at: <http://www.youtube.com/
watch?v=Y_2DcVnOxPQ> [Accessed 26 June 2013].
• Functions in C Programming [Video online] Available at: <http://www.youtube.com/watch?v=s7ZY1E4smqU>
[Accessed 26 June 2013].

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

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

53
Programming in ‘C’ and Data Structure

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

54
Chapter VI
Pointers

Aim
The aim of this chapter is to:

• explain the concept of pointers

• explicate pointer declaration

• explain 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, you will be able to:

• define pointers

• understand pointer arithmetic

• describe pointer with function

55
Programming in ‘C’ and Data Structure

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.
• References increase flexibility where the objects are stored, how they are allocated and how they are passed
between areas of code.

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

57
Programming in ‘C’ and Data Structure

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<srdio.h>
#include<conio.h>

Void main ( )
{

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

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

6.6 Pointers with Function


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

Return_type (*pointer_name) (variable1_type variable1_name, variable2_type variable2_name, variable3_type


variable3_name......................);

• The usage of pointers in a function definition is classified into two types. Those are:
‚‚ Call by value
‚‚ Call by reference

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

6.6.2 Call by Reference


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

6.6.3 Callback Functions


• Another use for function pointers is to set up ‘listener’ or’ callback’ functions that are invoked when a particular
event happens. The function is called, and it notifies your code that something of interest has taken place.
• For instance, most of the time the user will interact with a loop that allows the pointer to move and when the
user is writing a code for a graphical user interface(GUI), that redraws the interface.
• These operations are ‘events’ that may require a response that user’s program needs to handle.

6.7 Function Pointer Syntax

void (*foo) (int);

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

6.8. Reading Function Pointer Declaration

Void * (*foo) (int*) ;

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

6.8 Initialising Function Pointer


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

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

return 0;
}

59
Programming in ‘C’ and Data Structure

6.9 Using Function Pointer


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

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

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

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

6.10 Arrays and Pointer


• Arrays have a strong relationship to pointers in ‘C’ language. The concept of arrays is very much bound to the
pointers.
• The identifier of an array is equivalent to the address of its first element, whereas a pointer is equivalent to the
address of the first element that it points to.
• An array is very much like a pointer. The user can declare the arrays first element as a [0] or as ‘int’ *a because
a [0] is an address and *a is also an address, thus, the form of declaration is equivalent. The difference is that
the pointer is a variable and appears on the left of the assignment operator.
• Consider,

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

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

6.12 Pointers with Structures


Pointers can be declared by structure type. The ‘≥’ sign is used to point the members of the structure.
The general form of declaring a pointer to the structure is,

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

6.13 Pointers on Pointer


When the “pass by pointer” is used to pass a pointer to a function, only a copy of the pointer is passed to the function.
In other words, “pass by pointer” is passing a pointer by value. In most cases, this does not present a problem. But
problem comes when you modify the pointer inside the function. Instead of modifying the variable, the user has to
modify a copy of the pointer and the original pointer remains unmodified. Thus, it still points to the old variable.
Consider,
//global variable
int g_One = 1;
// function prototype

void func ( int* pInt);

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

return 0;
}

void func (int* pInt)


{
pInt = &g_One;
}

61
Programming in ‘C’ and Data Structure

General syntax of pointer to pointer,

//function prototype
void func (int++ ppInt);

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

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

References
• Kenneth, R., 2007. Pointers On C, Pearson Education India.
• Schultz, W. T., 2004. C And The 8051, 3rd ed. PageFree Publishing, Inc.
• Jensen, T., 2003. A TUTORIAL ON POINTERS AND ARRAYS IN C [Pdf] Available at: <http://pdos.csail.mit.
edu/6.828/2012/readings/pointers.pdf> [Accessed 26 June 2013].
• Lou, Y., 2011. Introduction to C Pointers and Arrays [Pdf] Available at: <http://www.cs.cornell.edu/courses/
CS2022/2011sp/lectures/lect04.pdf> [Accessed 26 June 2013].
• Pointers in c [Video online] Available at: <http://www.youtube.com/watch?v=w2pbty8tLKU> [Accessed 26
June 2013].
• C Programming Tutorial # 21 - Concept of Pointers - Part 1 [HD] [Video online] Available at: <http://www.
youtube.com/watch?v=rjo9rfRPQU4> [Accessed 26 June 2013].

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

63
Programming in ‘C’ and Data Structure

Self Assessment
1. ________ is a variable that stores a reference to another variable.
a. Array
b. Pointer
c. Function
d. Constants

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

3. __________ is a value that enables a program to indirectly access a particular data item such as a variable or a
record in the computer memory or in some other storage device.
a. Call by reference
b. Call by value
c. Reference
d. Pointer

4. The __________ is equivalent to the address of its first element, whereas a pointer is equivalent to the address
of the first element that it points to.
a. identifier of a pointer
b. identifier of an array
c. identifier of a constant
d. array

5. Which of the following statements is true?


a. Void (foo) (int); is function point syntax.
b. Void (*foo) (*int); is function point syntax.
c. Void (foo) (*int); is function point syntax.
d. Void (*foo) (int); is function point syntax.

6. Which of the following statements is true?


a. When the “pass by pointer” is used to pass a pointer to a function, only a copy of the pointer is passed to
the function.
b. When the “pointer” is used to pass a “pass by pointer” to a function, only a copy of the pointer is passed to
the function.
c. When the “pass by pointer” is used to pass a array to a function, only a copy of the pointer is passed to the
function.
d. When the “pass by array” is used to pass a array to a function, only a copy of the pointer is passed to the
function.

7. Which of the following statements is true?


a. Pointers are formed by declaring its capacity with it.
b. Array and pointers is formed by declaring its capacity with it.
c. Array of pointers is formed by declaring its capacity with it.
d. Array is formed by declaring its capacity with it.

64
8. What is it called when a function supports and a link is established between the formal and actual
parameters?
a. Call by reference
b. Pointer
c. Call by value
d. Pass by pointer

9. Which sign is used to point the members of the structure?


a. <
b. ≥
c. ≤
d. >

10. What is the subtraction of two pointers is called?


a. Differencing
b. Increment
c. Decrement
d. Addition and subtraction

65
Programming in ‘C’ and Data Structure

Chapter VII
Introduction to Data Structure

Aim
The aim of this chapter is to:

• introduce the concept of data structure

• enlist the types of data structure

• describe the concept of array

Objectives
The objectives of this chapter are to:

• explain the function of queue

• explain the difference between nonlinear and linear data structure

• elucidate an overview of tree

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

• understand the concept of linear and nonlinear data structure with java code

• enlist code for various data type of data structure

• describe an overview of stack

66
7.1 Introduction
Data structure can be defined as the collection of elements and all the possible operations which are required for
the set of elements. The operation includes inserting, deleting, searching and printing an element. It is the way of
representing logical relationship between individual data elements.

7.2 Types of Data Structure


The data structure can be divided into two types:
• Linear data structures
• Nonlinear data structures

These two types are further classified into:

Fig. 7.1 Classification of data structures

7.3 Linear Data Structure


A data structure is said to be linear, if its elements form a sequence or a linear list.

Operations on linear structure


The operations on linear structure are as follows:
• Traversal - Travel through the data structure.
• Search - Traversal through the data structure for a given element.
• Insertion - Adding new elements to the data structure.
• Deletion - Removing an element from the data structure.
• Sorting - Arranging the elements in some type of order.
• Merging - Combining two similar data structures into one.

7.4 Types of Linear Data Structure


The various types of linear data structures are mentioned below:

7.4.1 Array
Array is a consecutive group of memory locations which all have the same name and are of identical type.

67
Programming in ‘C’ and Data Structure

Grades 651 322 763 911 550 826

Grades 0 Grades 5

Fig. 7.2 Visual example of Array

Array terminology and declaration


Array declaration

type Array Name[]= new type[<array size>]

Example:
Float Grades[] = new float[7];
• Grades is an array of type float with size 7.
• Grades[0], Grades[1], …, Grades[6] are the elements of the Grades; each is of type float.
• 0, 1, 2,…,6 are the indices of the array. Also called subscripts. (Note that the indices start at 0 and NOT 1)
• During array declaration we may also put the brackets before the variable name:
• i.e., float [ ]Grades = new float[7];

Initialising arrays
Arrays may be initialised in the following ways:
int n[] = { 2, 4, 6, 8, 10 };
• Creates and initialises a five element array with specified values

int n[] = new int[10];


• Creates and initialises a 10 element array of zeros

Note:
• If data type is a non primitive type then above expression would create and initialise a 10 element array of
nulls.
• You cannot assign data to arrays like:
List = {1, 2, 3, 4, 5}; Wrong!
• Array elements are indexed between zero and the size of the array minus one.
• Arrays can have any type.
• You can check the size of your array by calling the length member variable.

int anArray[] = new int[5];


System.out.println(anArray.length);

68
The above example will print out 5 to the terminal

Array parameters
One can pass arrays into functions as part of the function parameter like any other variable.

int results = new


int[20];
printResults (results);

The function prototype for “printResults” was defined as:

void printResults(int SomeArray[ ]);


Note:
• Arrays in Java are treated like objects thus all arrays are passed in by reference.
• We don’t need to pass in the array size since we can get this from the length method.

Traversing linear arrays


• Usual way to traverse a linear 1-d array is to use a loop.
• For example, getting the overall average grade

Pseudo-Code: Get_Average (Array [])


Begin
index = 0;
sum = 0;
for index = 0 to index = ArraySize -1
}
sum = sum + Array[index];
}
average = sum / ArraySize;
End

Example: sample java code


/
* function which calculates and returns the average overall grade
/*
float Get_Average(float Grades[ ]);
}
float sum = 0; // initialise the sum variable
// We use a for loop for traversal here because
// it’s the handiest loop for what we want done
for(int index = 0; index < Grades.length; index++)
}
sum += Grades[index];
{
// Return the average
return sum/Grades.length;
}

69
Programming in ‘C’ and Data Structure

Inserting elements
Adding an element to an array/list at an arbitrary position without overwriting the previous values, requires that you
move all elements "below" that position.

Fig. 7.3 Inserting element

Algorithm
Insert (List [], position, element, ArraySize)
• Start at the top element of the array.
• Traverse the array backwards so as not to overwrite any previous data.
• Replace the current element that we are on with the element before it.
• Stop once we have reached our insertion position in the array.
• Insert our data into that position.

Sample Pseudo-code

Pseudo-Code: Insert (List [], position, element)


Begin
for index = ArraySize-1 to index = position+1
}
List[index] = List[index-1];
{
List[position] = element;
End

Multidimensional array
• Arrays can be more than one dimensional.
• Used to represent tables of data, etc.
• Declaration of 2-d array: int grid [][] = new int[5][6];
• This declaration is interpreted as an array consisting of 5 rows and 6 columns
• Another way of declaring a 2-d array is given below.

int grid[][] = new int[2][];


grid[0] = new int[2];
grid[1] = new int[2];

• Same as declaring a 2 x 2 array except we are doing it one row at a time here.

70
Example for 3-d array:
int space = new int[100][100][100];

Initialising multidimensional arrays


Example:
int array1[ ][ ] = {{1,2,3}, {4,5,6}};
int array2[ ][ ] = new int[3][2];
int array3[ ][ ] = {{1,2}, {4}};

If we were to print out the values of these arrays by row we would get:
Array 1 Array 2 Array3
123 000 12
456 00 4

Note: If there are not initialisers for a given row, primitive types are initialised to zero and non primitive types are
initialised to null.

Multidimensional arrays as parameters


Example:
Void warp(int space[ ][ ][ ]);

Same as declaring a one dimensional array as parameters except that we must remember to include extra square
brackets for each additional dimension.

7.4.2 Linear Link List


A linear list is a list in which each element has a unique successor.

Types of lists
• General: Data can be inserted and deleted anywhere in the list
‚‚ Unordered or random data
‚‚ Ordered data: data are arranged according to a key
• Restricted: Data can be inserted or deleted at the ends of the list
‚‚ LIFO (stack)
‚‚ FIFO (queue)
• Four basic operations associated with linear lists are as follows:
‚‚ Insertion
‚‚ Deletion
‚‚ Retrieval
‚‚ Traversal

71
Programming in ‘C’ and Data Structure

Fig. 7.4 Linear link list

Basic operation of linked lists


• A linked list is an ordered collection of data in which each element contains the location of the next element.
• Each element (item) called node contains two parts: data and link.
• Link contains a pointer variable that identifies the first element in the list.
• Nodes are called self-referential structures. Each instance of the structure contains a pointer to another instance
of the same structural type.
• Unlike arrays, data can be easily inserted and deleted in the linked list, but the search becomes sequential as the
elements are no longer physically sequenced.
• Linked list abstract data type consists of the data structure and all operations that manipulate the data.
• A head node contains metadata about the list such as, count, a head pointer to the first node and a rear pointer
to the last node.
• Data node contains the data type which depends entirely on the application and a pointer to another data structure
of its own type.
• The ten low-level algorithms are as follows:
‚‚ Create list
‚‚ Insert node
‚‚ Delete node
‚‚ Search list
‚‚ Retrieve node
‚‚ Empty list
‚‚ Full list
‚‚ List count
‚‚ Traverse list
‚‚ Destroy list
• The three high-level algorithms include:
‚‚ Add node
‚‚ Remove node
‚‚ Print list

72
Linked list using java

• Declaring a class for nodes


Public class IntNode
{
private int data
private IntNode link
}

Declaring two nodes


IntNode head
IntNode tail

Constructor for the IntNode


public IntNode(int initialData, IntNode initialLink)
{
data = initialData
link = initialLink
}

Complex linked list structures


The various complex linked-list structures are as follows:
• Doubly-linked list - Each node has a pointer to both its successor and its predecessor.
• Multilinked list - List has two or more logical key sequences and data can be ordered chronologically.

7.4.3 Stack
• A stack is a linear list in which all additions and deletions are restricted to one end called top. It is a Last In
First Out (LIFO) data structure.
• Basic stack operations include:
‚‚ Push: adds an item at the top of the stack.
‚‚ Pop: removes the item at the top of the stack and return it to the user.
‚‚ Stack top: reads the stack top and returns the data to the user.
• Stack-linked list implementation is discussed below.
Usually implemented with a pointer to a stack head structure stored in dynamic memory.

Fig. 7.5 Stack

73
Programming in ‘C’ and Data Structure

Fig. 7.6 Stack physical view

• Head node contains metadata about the stack such as count and a pointer to the top of the stack.
• Data node looks like a typical linked list data node.

Stack algorithms
• Create stack
• Push stack
• Pop stack
• Stack top
• Empty stack
• Full stack
• Stack count
• Destroy stack

Stack applications
Four common stack applications are:
• Reversing data - A given set of data is recorded so that the first and last elements are exchanged, with all of the
positions between the first and the last elements are relatively exchanged also.
• Parsing - Any logic that breaks down the data into independent pieces for further processing.
• Postponement - The usage of data can be deferred until some later point.
• Backtracking - Making decisions between two or more paths. Stacks are also useful for implementing recursive
algorithms.

7.4.4 Queues
A queue is a linear list in which data can be inserted at one end (called the rear), and deleted from the other end
(called the front). It is a First In First Out (FIFO) data structure.

74
Fig. 7.7 Queue
Basic queue operations
The various queue operations are as follows:
• Enqueue - Inserts an element at the rear of the queue.
• Dequeue - Deletes an element at the front of the queue.
• Queue front - Examines the element at the front of the queue.
• Queue rear - Examines the element at the rear of the queue.

Fig. 7.8 Queue physical view


Queue-linked list implementation
• Queue-linked list is usually implemented as a linked list in dynamic memory.
• Head node contains metadata about the stack such as count, and two pointers to the front and rear of the
queue.
• Data node looks like a typical linked list data node.

Queue algorithms
• Create queue
• Enqueue
• Dequeue
• Queue front
• Queue rear
• Empty queue

75
Programming in ‘C’ and Data Structure

• Full queue
• Queue count
• Destroy queue

7.5 Non-Linear Data Structure


Non-linear data structures are the data structures in which data may be arranged in hierarchical manner.
• There are four type of non-linear data structures:
‚‚ Tree
‚‚ Graph
‚‚ Table
‚‚ Set

7.5.1 Tree
A tree is discussed in detail below:

7.5.1.1 Definition of Tree


• A set of related interconnected nodes in a hierarchical structure.
• A non-empty collection of vertices and edges that satisfies certain requirements.
• Structure resembles branches of a “tree”, hence the name.

7.5.1.2 Types of Trees


The different types of trees are as follows:
• Rooted tree
• Ordered tree
• M-ary tree and binary tree

Fig. 7.9 Tree

7.5.1.3 Tree Terminology


• A vertex (or node) is a simple object that can have a name and can carry other associated information.
• The first or top node in a tree is called the root node.
• An edge is a connection between two vertices.
• A path in a tree is a list of distinct vertices in which successive vertices are connected by edges in the tree.
Example :{ a, b, d, i} is path.
• The defining property of a tree is that there is precisely one path connecting any two nodes.
• A disjoint set of trees is called a forest.

76
• Nodes with no children are leaves or terminal nodes.

Fig. 7.10 Tree terminology

• The various terminologies used in tree include:


‚‚ Root - This is the unique node in the tree to which further sub trees are attached.
‚‚ Degree of the node - The total number of subtrees attached to that node is called the degree of the node.
For node A degree is 2.
‚‚ Leaves - These are the terminal nodes of the tree. The nodes with degree 0 are always the leaves. Here
nodes are e, f, g, h, i.
‚‚ Internal nodes - The nodes other than the root node and the leaves are called the internal node. Here b, c,
d and f are internal nodes.
‚‚ Parent node - The node which is having further sub branches is called the parent node of those sub branches.
In fig 7.8 node b is parent node of d, e and f and c is parent node of g and h. whereas d, e, f, g and h is child
of b and c parent.

7.5.1.4 Rooted Tree


• A Rooted tree is one, where we designate one node as the root (i.e., the tree examples we have been looking at
so far are all rooted trees).
• In computer science, the term tree is reserved to refer rooted trees. The more general structure is a free tree.
• In a rooted tree, any node is the root of a sub-tree that consists of many roots and the nodes below it.
• There is exactly one path between the root and each of the other nodes in the tree.
• Each node except the root has exactly one node above it in the tree, (i.e., it is parent), and we extend the family
analogy talking of children, siblings, or grandparents.

77
Programming in ‘C’ and Data Structure

Root

Vertex Vertex

Leaf Leaf
Leaf Leaf

Fig. 7.11 Rooted tree

7.5.1.5 Ordered Tree


• An ordered tree is a rooted tree in which the order of the children at every node is specified.
• If each node must have a specific number of children appearing in a specific order, then we have a M-ary
tree.
• The simplest type of M-ary tree is the binary tree.

7.5.1.6 Binary Trees


A binary tree is a tree, where each node has exactly zero, one or two children. i.e., each parent can have not more
than 2 children. As with any Abstract Data Structure , a binary tree can be implemented in a number of ways, using
arrays, strings, or structures and pointers.

Fig. 7.12 Binary tree

78
7.5.1.7 Example of Trees

Fig. 7.13 Example of trees

Representing a Binary Tree Data Structure in Java


Question: How do we represent a binary tree using java?

79
Programming in ‘C’ and Data Structure

Solution:
One way of representing A node of a binary tree in Java as follows:
class BTreeNode
{
int data = 0;
BTreeNode left = null;
BTreeNode right = null;
}
Data : 0

Left (Null) Right (Null)

We may then build our binary tree using this node structure

Constructing the Binary Tree


Lets draw the following code sequence.

BTreeNode root = null, temp = null;


root = new BTreeNode();
root.data = 5;
temp = new BTreeNode();
temp.data = 2;
temp.left = null;
temp.right = null;
root.left = temp;
root.right = null;

7.5.1.8 Binary Search Tree


• A binary tree which conforms to the following properties is called a binary search tree.

Properties of binary search tree


• Each value (key) in the tree exists at most once (i.e., no duplicates).
• The "greater-than" and "less-than" relations are well defined for the data value.
• Sorting constraints for every node n
‚‚ All data in the left subtree of n is less than the data in the root of that subtree.
‚‚ All data in the right subtree of n is greater than the data in the root of that subtree.

Fig. 7.14 Binary search tree’s example

80
Question: How to construct a BST in java?
Answer: The most intuitive way of creating BST/adding nodes to a BST is to use recursive approach.

Question: What are the base and recursive cases?


Answer: Base case: if tree is empty, create new node for item.
Recursive case: if key < root's value, add to the left subtree, otherwise to the right subtree
BST Add Node Method

Code for add node method


BTreeNode Add_node(BTreeNode node, int value)
{ // Method returns newly added node
if(node == null)
{ // The base case
node = new BTreeNode(); // Create the new node
node.data = value; // Give it specified data
node.left = null; // Set up left and right pointers
node.right = null;
return node; // Return the new node to the calling method
{
else
{ // The Recursive cases
if ((value > node.data) && (node.right == null)) // If node is a leaf and node to add is right child
return node.right = Add_node(node.right, value); // Prepare to accept a new right “child”
else if ((value > node.data) && (node.right != null)) // Else if node not a leaf, traverse as appropriate
return Add_node(node.right, value);
else if ((value < node.data) && (node.left == null)) // If node is a leaf and node to add is left child
return node.left = Add_node(node.left, value); // Prepare to accept a new left “child”
else // Else node not a leaf, traverse as appropriate
return Add_node(node.left, value);
}
}

7.5.1.9 ++ Tree Traversal Types


We may traverse a binary tree in 3 ways. These are:
• preorder
• postorder
• inorder

These are described below:


• Preorder traversal
‚‚ Visit the node first and process.
‚‚ Do preorder traversal of left subtree.
‚‚ Do preorder traversal of right subtree, i.e., visits and processes each node in a tree BEFORE visiting and
processing its children.

• Postorder traversal
‚‚ Do postorder traversal of left subtree.
‚‚ Do postorder traversal of right subtree.
‚‚ Visit the node last and process, i.e., visits and processes each node in the tree AFTER visiting and processing
its children.

81
Programming in ‘C’ and Data Structure

• Inorder traversal
‚‚ Do inorder traversal of left subtree.
‚‚ Visit the node and process.
‚‚ Do inorder traversal of right subtree, i.e., processes nodes in the tree in an ascending sorted order.

7.5.1.10 Traversal Method


The three methods of tree traversal are discussed briefly below.
Inorder

void inorder(BTreeNode the_node)


{
if (the_node == null)
; // do nothing
else
{
inorder(the_node.left);
System.out.print(the_node.data);
inorder(the_node.right);
}
}

Preorder

void preorder(BTreeNode the_node)


{
if (the_node == null)
; // do nothing
else
{
System.out.print(the_node.data);
preorder(the_node.left);
preorder(the_node.right);
}
}

Postorder

void postorder(BTreeNode the_node)


{
if (the_node == null)
; // do nothing
else
{
postorder(the_node.left);
postorder(the_node.right);
System.out.print(the_node.data);
}
}

82
Summary
• The data structure can be defined as the collection of element and all the possible operations which are required
for those set of elements.
• The operation includes inserting, deleting, searching and printing an element. It is the way of representing logical
relationship between individual data elements.
• The data structure can be divided into two types, namely Linear and Nonlinear data structures.
• Traversal: Travel through the data structure.
• Search: Traversal through the data structure for a given element.
• Insertion: Adding new elements to the data structure.
• Deletion: Removing an element from the data structure.
• Sorting: Arranging the elements in some type of order.
• Merging: Combining two similar data structures into one.
• A consecutive group of memory locations that all have the same name and of identical type.
• Usual way to traverse a linear 1-d array is to use a loop. For example, getting the overall average grade.
• Adding an element to an array/list at an arbitrary position without overwriting the previous values requires that
you move all elements "below" that position.
• A linear list is a list in which each element has a unique successor.
• Types of lists are General and Restricted.
• Four basic operations associated with linear lists are Insertion, Deletion, Retrieval and Traversal.

References
• Storer, A. J., 2002. An Introduction to Data Structures and Algorithms, Springer.
• Baitipuli, N. V., 2009. Introduction to Data Structures Using C, Laxmi Publications, Ltd.
• INTRODUCTION TO DATA STRUCTURE [Pdf] Available at: <http://www.csbdu.in/econtent/DataStructures/
Unit1-DS.pdf> [Accessed 26 June 2013].
• Introduction to Data Structures Using C [Pdf] Available at: <http://vijayacollege.ac.in/Content/PDF/ds_notes.
pdf> [Accessed 26 June 2013].
• Lecture - 1 Introduction to Data Structures and Algorithms [Video online] Available at: <http://www.youtube.
com/watch?v=zWg7U0OEAoE> [Accessed 26 June 2013].
• Dr. Chakraborty, P. P., 2010. Lec-1 Introduction [Video online] Available at: <http://www.youtube.com/
watch?v=S47aSEqm_0I> [Accessed 26 June 2013].

Recommended Reading
• Kamthane, N. A., 2012. Introduction to Data Structures in C, Pearson Education India.
• Group, I., 2006. Data Structures Using C, Tata McGraw-Hill Education.
• Puntambekar, A. A., 2008. Advanced Data Structures And Algorithms, Technical Publications.

83
Programming in ‘C’ and Data Structure

Self Assessment
1. The ___________can be defined as the collection of element and all the possible operations which are required
for those set of elements.
a. data structure
b. molecular structure
c. chemical structure
d. code structure

2. Which of the following statements is true?


a. The data structure has one type.
b. The data structure can be divided into three types.
c. The data structure can be divided into four types.
d. The data structure can be divided into two types.

3. A data structure is said to be linear, if its elements form a sequence or a___________.


a. line list
b. least list
c. linear list
d. non-linear list

4. Which of the following statements is traversal statement?


a. Travel through the data structure
b. Travel through the data structure for given element
c. Adding new elements to data structure
d. Travel in the data structure

5. _____________ is removing an element from the data structure.


a. Sorting
b. Insertion
c. Deletion
d. Merging

6. ___________ is combining two similar data structures into one.


a. Sorting
b. Insertion
c. Deletion
d. Merging

7. _____________ is a arranging the elements in some type of order.


a. Sorting
b. Insertion
c. Deletion
d. Merging

84
8. __________ is adding new elements to the data structure.
a. Sorting
b. Insertion
c. Deletion
d. Merging

9. __________ is traversal through the data structure for a given element.


a. Search
b. Insertion
c. Deletion
d. Merging

10. ______________ is a consecutive group of memory locations that all have the same name and of identical
type.
a. Array
b. Pointer
c. Data
d. Element

85
Programming in ‘C’ and Data Structure

Application I
CPython
CPython is an implementation of the Python programming language. It is the most-widely used, default
implementation. This language is written in C. Besides CPython, Jython and IronPython are two other production
quality implementations of the Python. Jython is written in Java whereas, IronPython is written for C#. All the three
implementations of Python mentioned above have several experimental implementations. CPython is a bytecode
interpreter. The term Bytecode is used to denote various forms of instruction sets, which are designed to ensure
efficient execution of the instruction by a software interpreter and also to enhance the suitability of the instruction for
further compilation into the machine code. An interpreter executes the instructions written in a computer program.
It can perform the following roles:
• execute the source code directly
• translate source code into intermediate code and execute the same immediately
• explicitly execute the stored precompiled code made by a compiler

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

Supported Platforms of CPython


The supported platforms of CPython are as follows:
• Unix-like
• AIX operating system
• BSD
• Darwin
• FreeBSD
• HP-UX
• IRIX 5 and later
• Plan 9 from Bell Labs
• Mac OS X
• NetBSD
• Linux
• OpenBSD
• Solaris
• Tru64
• Other Unixes

Desktop OSes
• AROS
• AtheOS
• BeOS
• Windows
• Windows NT
• OS/2
• RISC OS

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

Previously supported platforms


PEP 11 lists platforms which are not supported in CPython by Python Software Foundation. These platforms can
still be supported by external ports. See below.
• DOS (unsupported since 2.0)
• IRIX 4 (unsupported since 2.3)
• Mac OS 9 (unsupported since 2.4)
• MINIX (unsupported since 2.3)

External ports
These are ports not integrated to Python Software Foundation's official version of CPython, with links to its main
development site. Ports often include additional modules for platform-specific functionalities, like graphics and
sound API for PSP and SMS and camera API for S60.
• Amiga: AmigaPython
• AS/400: iSeriesPython
• DOS using DJGPP: PythonD
• PlayStation Portable: Stackless Python for PSP
• Symbian OS: Python for S60
• Windows CE/Pocket PC: Python Windows CE port

Concurrency issues with CPython


A drawback of using CPython on a multiprocessor computer is the presence of a Global Interpreter Lock on each
CPython interpreter process. This can effectively effectively disable concurrent Python threads within one process.
To be truly concurrent in multiprocessor environment, separate CPython interpreter processes have to be run, which
makes establishing communication between them a difficult task. There is constant discussion whether to remove
the GIL from CPython.

87
Programming in ‘C’ and Data Structure

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

2. Name three supported platforms of CPython separately based on Unix-like, Desktop OSes and Special Emebedded
platforms.
Answers
Supported Platforms of:
• Unix-like are – BSD, Darwin, Linux;
• Desktop OSes are – Windows NT, AROS, OS/2
• Special and embedded are – iPodLinux, Palm OS, QNX

3. What are the advantages and disadvantages of CPython?


Answers
Advantages of CPython :
‚‚ CPython is a bitecode interpreter.
‚‚ CPython has a foreign function interface with C and several other languages.
Disadvantages of CPython :
• Presence of a Global Interpreter Lock on each CPython interpreter process limits the use of CPython on a
multiprocessor computer. It shows the following drawbacks:
‚‚ disable concurrent Python threads within one process
‚‚ separate CPython interpreter processes have to be run to become concurrent in multiprocessor
environment
‚‚ thus, communication between the interpreters becomes difficult

4. Name the platforms that were supported by the C programme earlier.


Answers
MINIX, DOS, IRIX 4

88
Application II

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

*/

#include<stdio.h>

main( )
{
int pounds;

/* Read first weight in pounds */

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

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

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

Question
1. Write a program to count blanks, tabs and newlines.

89
Programming in ‘C’ and Data Structure

Application III

1. A program for bomber fighter plane simulation.

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<dos.h>
#include<math.h>
void main ( )
{
int gd = DETECT, gm ;
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) ;

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

if (distance≤50)
{

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

}
if (flag = = 0)
{
outtextxy (220, 250, ″Sorry : Bomber Plane has Passed away Safely!″) ;

for (int i=120; i<1000; i++)


{
sound (i) ;
delay (8) ;

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

Question
1. Write a chat program in C.

91
Programming in ‘C’ and Data Structure

Application IV

/* This program counts the number of bytes in a C source file. The program prompts the user for a file name and
then concatenates the ".c" extension to this name. It uses the function get c to read the characters.

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

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

char file_name[FILENAME_MAX]; /* defined in stdio.h*/


int char_count;

printf("\n\n\tFile name (NO extension):\t");


scanf("%s",file_name);
strcat(file_name,extension);
fptr=fopen(file_name,"rb");

for(char_count=0; getc(fptr) !=EOF; ++char_count);


printf("\n\tByte size:\t%d", char_count);
fclose(fptr);

return EXIT_SUCCESS;
}

Question
1. Write a program that takes three variable (a, b, b) in as separate parameters and rotates the values stored so that
value a goes to be, b, to c and c to a.

92
Bibliography
References
• Ackermann, C. E., 1989. The Essentials of C Programming Language, Research & Education Assoc.
• Ajay, M., 2010. Programming In C: A Practical Approach, Pearson Education India.
• Arrays and Strings [Pdf] Available at: <http://pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/10-
ArraysAndStrings.pdf> [Accessed 26 June 2013].
• Ashok, K., 2010. C Programming: Test Your Skills, Pearson Education India.
• Baitipuli, N. V., 2009. Introduction to Data Structures Using C, Laxmi Publications, Ltd.
• Balagurusamy, 2008. Programming In Ansi C, 4th ed. Tata McGraw-Hill Education.
• C Programming Classes - Structure in C language [Video online] Available at: <http://www.youtube.com/
watch?v=Y_2DcVnOxPQ> [Accessed 26 June 2013].
• C Programming Tutorial # 21 - Concept of Pointers - Part 1 [HD] [Video online] Available at: <http://www.
youtube.com/watch?v=rjo9rfRPQU4> [Accessed 26 June 2013].
• C Programming Tutorial 44 - Strings and Characters [Video online] Available at: <http://www.youtube.com/
watch?v=EJBb8nQD-4g> [Accessed 26 June 2013].
• C Programming Tutorial: Arrays (One and Two Dimensional Array ): Lesson 2 [Video online] Available at:
<http://www.youtube.com/watch?v=NFJMjgXb0uA> [Accessed 26 June 2013].
• C Programming Tutorial: Input Output (printf, scanf, format specifiers) Lesson 1 [Video online] Available at:
<http://www.youtube.com/watch?v=5v7h4ZmgMvw> [Accessed 26 June 2013].
• C programming tutorial-5- Dealing with the DATATYPES [Video online] Available at: <http://www.youtube.
com/watch?v=oLjV3vfmZmg> [Accessed 26 June 2013].
• Chapter 2: C Data Types [Pdf] Available at: <http://www.informatik.uni-giessen.de/staff/brass/iii01/c2_cdata.
pdf> [Accessed 26 June 2013].
• Control Statements [Pdf] Available at: <http://download.nos.org/srsec330/330L9.pdf> [Accessed 26 June
2013].
• Control Statements in Programming Languages (final) part1 [Video online] Available at: <http://www.youtube.
com/watch?v=hX0Rrq8ouxY> [Accessed 26 June 2013].
• Control statements in programming languages-part 1-pldc [Video online] Available at: <http://www.youtube.
com/watch?v=ageuh_4_J9E> [Accessed 26 June 2013].
• Data Structures Using C [Pdf] Available at: <http://www.gatesit.org/gitdownloads/C&DS.pdf> [Accessed 26
June 2013].
• Deshpande, P. S. & Kakde, O. G., 2004. C and Data Structures, Cengage Learning.
• Dixit, J. B., 2005. Fundamentals of Computers and Programming in C, Firewall Media.
• Dr. Chakraborty, P. P., 2010. Lec-1 Introduction [Video online] Available at: <http://www.youtube.com/
watch?v=S47aSEqm_0I> [Accessed 26 June 2013].
• Dr. Gupta, P., Aggarwal, V. & Varshney, M., 2007. Data Structures Using ‘C’, Firewall Media.
• Dr. Kumar, A. S., 2008. Lecture - 1 Introduction to programming languages [Video online] Available at: <http://
www.youtube.com/watch?v=EbNJ05EVXs0> [Accessed 26 June 2013].
• Functions in C [Pdf] Available at: <http://www.nada.kth.se/kurser/master/intro/Course03-04/Handouts/
Flecture05.pdf> [Accessed 26 June 2013].
• Functions in C Programming [Video online] Available at: <http://www.youtube.com/watch?v=s7ZY1E4smqU>
[Accessed 26 June 2013].
• Goel, A., Computer programming-I: As per the first-year engineering syllabus of University of Mumbai, Pearson
Education India.
• Hoover, 2009. System Programming With C And Unix, Pearson Education India.

93
Programming in ‘C’ and Data Structure

• Input and Output in C [Pdf] Available at: <http://www.prog2impress.com/downloads/Input%20and%20


Output%20in%20C.pdf> [Accessed 26 June 2013].
• Introduction to C Programming I [Video online] Available at: <http://www.youtube.com/watch?v=fUcSXbQn
rLI&list=PL66D13A5B3585C213> [Accessed 26 June 2013].
• INTRODUCTION TO DATA STRUCTURE [Pdf] Available at: <http://www.csbdu.in/econtent/DataStructures/
Unit1-DS.pdf> [Accessed 26 June 2013].
• Introduction to Data Structures Using C [Pdf] Available at: <http://vijayacollege.ac.in/Content/PDF/ds_notes.
pdf> [Accessed 26 June 2013].
• Introduction to the C Programming Language [Pdf] Available at: <http://163.25.99.51/Huang_Computer/
Programming%20Language-website2.pdf> [Accessed 26 June 2013].
• Jensen, T., 2003. A TUTORIAL ON POINTERS AND ARRAYS IN C [Pdf] Available at: <http://pdos.csail.mit.
edu/6.828/2012/readings/pointers.pdf> [Accessed 26 June 2013].
• Kenneth, R., 2007. Pointers On C, Pearson Education India.
• Kernighan, W. B. & Ritchie, D., 1988. C Programming Language, 2nd ed. Prentice Hall.
• Kernighan, W. B. & Ritchie, M. D., 1988. The C programming Language [Pdf] Available at: <http://net.pku.
edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf> [Accessed 26 June 2013].
• Laitinen, K., 2004. A Natural Introduction to Computer Programming with C#, Trafford Publishing.
• Lecture - 1 Introduction to Data Structures and Algorithms [Video online] Available at: <http://www.youtube.
com/watch?v=zWg7U0OEAoE> [Accessed 26 June 2013].
• Lecture 3: Data types and variables [Pdf] Available at: <http://cs.ucsb.edu/~koc/cs60/lectures/Lecture03-
DataTypes.pdf> [Accessed 26 June 2013].
• Lecture 7: Arrays, strings, and functions [Pdf] Available at: <http://www.stanford.edu/~fringer/teaching/
operating_systems_03/handouts/lecture7.pdf> [Accessed 26 June 2013].
• Lesson 6.4 : Numeric Data Types in C [Video online] Available at: <http://www.youtube.com/
watch?v=D8M6RifBoLk> [Accessed 26 June 2013].
• Lipari, G., 2012. Fundamentals of Programming Introduction to the C language [Pdf] Available at: <http://retis.
sssup.it/~lipari/courses/infbase2012/03.c_intro-handout.pdf> [Accessed 26 June 2013].
• Lou, Y., 2011. Introduction to C Pointers and Arrays [Pdf] Available at: <http://www.cs.cornell.edu/courses/
CS2022/2011sp/lectures/lect04.pdf> [Accessed 26 June 2013].
• PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts [Video online] Available at:
<http://www.youtube.com/watch?v=c_sDgHgNR6w> [Accessed 26 June 2013].
• Pointers in c [Video online] Available at: <http://www.youtube.com/watch?v=w2pbty8tLKU> [Accessed 26
June 2013].
• Program Control Statements [Pdf] Available at: <http://www.uotechnology.edu.iq/dep-eee/lectures/1st/
Computer%20science/2.pdf> [Accessed 26 June 2013].
• Schultz, W. T., 2004. C And The 8051, 3rd ed. PageFree Publishing, Inc.
• Storer, A. J., 2002. An Introduction to Data Structures and Algorithms, Springer.
• Veerana, V. K. & Jankidevi, S. J., 2007. C for U Including C and C Graphics, Firewall Media.

Recommended Reading
• Balagurusamy, E., Programming In Ansi C, 5E, Tata McGraw-Hill Education.
• Deitel, J. P. & Deitel, M. H., 2009. C: How to Program, 6th ed. Prentice Hall.
• Dixit, J.B., 2006. Comprehensive Programming in C and Numerical Analysis, Laxmi Publications.
• Ghosh, 2004. Programming In C, PHI Learning Pvt. Ltd.
• Ghosh, All Of C, PHI Learning Pvt. Ltd.
• Group, I., 2006. Data Structures Using C, Tata McGraw-Hill Education.

94
• Hanly, 2009. Programming In C And Data Structures (For Jntu), Pearson Education India.
• Kamthane, N. A., 2012. Introduction to Data Structures in C, Pearson Education India.
• Kochan, 2005. Programming In C, 3/E, Pearson Education India.
• Kochan, G. S., 2012. Programming in Objective-C, 4th ed. Addison-Wesley Professional.
• Krishnamoorthy, 2010. DATA STRUCTURES USING C, Tata McGraw-Hill Education.
• Lafore, 2002. Object Oriented Programming In C++, 4/E, Pearson Education India.
• Loudon, K., 2009. Mastering Algorithms with C, O’Reilly Media, Inc.
• Malik, D. S., 2009. C++ Programming: Program Design Including Data Structures: Program Design Including
Data Structures, 4th ed. Cengage Learning.
• Malik, D. S., 2012. C++ Programming: From Problem Analysis to Program Design, 6th ed.: From Problem
Analysis to Program Design, 6th ed. Cengage Learning.
• Nair, 2009. Data Structures In C, PHI Learning Pvt. Ltd.
• Pandey, M. H., 2009. Trouble Free C, Laxmi Publications.
• Parthasarthy, S., 2008. Essentials Of Programming In C For Life Sciences, Ane Books Pvt Ltd.
• Puntambekar, A. A., 2008. Advanced Data Structures And Algorithms, Technical Publications.
• Puntambekar, A. A., 2008. Data Structures With C, Technical Publications.
• 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.

95
Programming in ‘C’ and Data Structure

Self Assessment Answers


Chapter I
1. b
2. c
3. a
4. c
5. b
6. a
7. d
8. b
9. d
10. b

Chapter II
1. c
2. d
3. a
4. a
5. d
6. b
7. a
8. d
9. b
10. a

Chapter III
1. d
2. c
3. a
4. b
5. d
6. b
7. c
8. a
9. d
10. c

Chapter IV
1. b
2. c
3. d
4. a
5. c
6. b
7. d
8. c
9. b
10. a

96
Chapter V
1. b
2. a
3. c
4. c
5. d
6. c
7. a
8. b
9. a
10. d

Chapter VI
1. b
2. a
3. c
4. b
5. d
6. a
7. c
8. a
9. b
10. a

Chapter VII
1. a
2. d
3. c
4. a
5. c
6. d
7. b
8. b
9. a
10. a

97