0% found this document useful (0 votes)
13 views170 pages

II BSC EC - III SEM - Programming in C

The document is a syllabus for a Programming in C course for B.Sc. Electronics and Communication students, detailing various units covering topics such as the overview of C, data types, operators, decision-making, arrays, strings, user-defined functions, structures, pointers, and file management. Each unit includes specific subtopics that outline the essential concepts and skills students are expected to learn. The document also lists recommended textbooks and reference materials for further study.

Uploaded by

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

II BSC EC - III SEM - Programming in C

The document is a syllabus for a Programming in C course for B.Sc. Electronics and Communication students, detailing various units covering topics such as the overview of C, data types, operators, decision-making, arrays, strings, user-defined functions, structures, pointers, and file management. Each unit includes specific subtopics that outline the essential concepts and skills students are expected to learn. The document also lists recommended textbooks and reference materials for further study.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

PROGRAMMING IN C

(For [Link]., Electronics& Communication ,


Semester - III)
(Subject code:12UCSA02)

Prepared By

[Link] CHARANYA., MCA., M. Phil., Ph.D

DEPARTMENT OF COMPUTER SCIENCE

SALEM SOWDESWARI COLLEGE


SELF - FINANCING COURSES WING

SALEM – 10

Version: 2018 – 2019- 1.0


CONTENTS
UNIT - I..............................................................................................................................................1

1.1 OVERVIEW OF C...............................................................................................................1

1.1.1 History of C................................................................................................................1

1.1.2 Importance of C.......................................................................................................1

1.1.3 Basic Structure of C Programs.......................................................................1

1.2 CONSTANTS, VARIABLES AND DATA TYPES....................................................3

1.2.1 Character Set............................................................................................................3

1.2.2 C Tokens......................................................................................................................4

1.2.3 Keywords and Identifiers...................................................................................5

1.2.4 Constants....................................................................................................................5

1.2.5 Variables.....................................................................................................................7

1.2.6 Declaration of Storage Class.........................................................................14

1.2.7 Assigning values to a variables...................................................................15

1.2.8 Defining symbolic constants..........................................................................16

1.3 OPERATORS AND EXPRESSION.............................................................................18

1.3.1 Evaluation of expressions...............................................................................29

1.3.2 Precedence of arithmetic operators.........................................................29

1.3.3 Type conversion in Expressions...................................................................30

1.3.4 Operator Precedence and Associatively.................................................31

1.3.5 Mathematical Function.....................................................................................32

1.4 MANAGING INPUT AND OUTPUT OPERATIONS.............................................33

1.4.1 Reading and Writing a character................................................................33

1.4.2 Formatted Input and output..........................................................................36

UNIT – II..........................................................................................................................................41

2.1 DECISION MAKING AND BRANCHING.................................................................41

2.1.1 Simple if statement............................................................................................41

2.1.2 The if…else statement......................................................................................42


2.1.3 Nesting of if … else statements...................................................................44

2.1.4 The else..if ladder................................................................................................46

2.1.5 The switch statement........................................................................................48

2.1.6 The goto statement............................................................................................51

2.2 DECISION MAKING AND LOOPING.......................................................................52

2.2.1 While Statement...................................................................................................55

2.2.2 Do Statement.........................................................................................................56

2.2.3 For Statement.......................................................................................................57

2.2.4 Jumps In Loops.......................................................................................................58

2.3 ARRAYS..............................................................................................................................58

2.3.1 Definition & Declaration...................................................................................58

2.3.2 One-dimensional arrays...................................................................................59

2.3.3 Two dimensional arrays...................................................................................63

2.3.4 Multidimensional array.....................................................................................66

2.3.5 Dynamic array........................................................................................................67

UNIT - III.........................................................................................................................................68

3.1 CHARACTER ARRAYS AND STRINGS...................................................................68

3.1.1 Introduction.............................................................................................................68

3.1.2 Declaring and Initializing String Variables...........................................68

3.1.3 Reading Strings from Terminal....................................................................69

3.1.4 Writing Strings to Screen................................................................................73

3.1.5 String Handling Functions..............................................................................75

3.1.6 Table of Strings.....................................................................................................83

3.2 USER DEFINED FUNCTION........................................................................................83

3.2.1 Introduction.............................................................................................................83

3.2.2 Need for User-Defined Functions................................................................84

3.2.3 A Multi-Function Program...............................................................................85


3.2.4 Elements of user-defined functions..........................................................86

3.2.5 Definition of functions.......................................................................................86

3.2.6 Return Values And Their Types....................................................................88

3.2.7 Function Calls.........................................................................................................89

3.2.8 Function Declaration..........................................................................................90

3.2.9 All Category Of Functions...............................................................................90

3.2.10 Nesting of Functions.......................................................................................98

3.2.11 Recursion...............................................................................................................99

3.2.12 Passing arrays to functions.......................................................................101

3.2.13 Passing strings to functions.....................................................................103

UNIT- IV.........................................................................................................................................106

4.1 STRUCTURES AND UNIONS....................................................................................106

4.1.1 Introduction...........................................................................................................106

4.1.2 Defining a Structure.........................................................................................106

4.1.3 Declaration of Structure Variable.............................................................107

4.1.4 Accessing Structure Members....................................................................109

4.1.5 Structure Initialization....................................................................................109

4.1.6 Copying and Comparing Structure Variables.....................................111

4.1.7 Array of Structures...........................................................................................113

4.1.8 Array within Structures..................................................................................115

4.1.9 Structures Within Structures......................................................................115

4.1.10 Structure and Functions..............................................................................116

4.1.11 Unions....................................................................................................................117

4.1.12 Size of Structures............................................................................................118

4.1.13 Bit Fields...............................................................................................................118

4.2 POINTERS........................................................................................................................119

4.1.1 Introduction...........................................................................................................119
4.1.2 Understanding Pointers.................................................................................120

4.1.3 Accessing the address of variables.........................................................121

4.1.4 Initializing Of Pointer Variables.................................................................122

4.1.5 Chain Of Pointers...............................................................................................123

4.1.6 Pointer Expressions..........................................................................................123

4.1.7. Pointers And Arrays........................................................................................124

4.1.8 Pointers And Character Strings.................................................................127

4.1.9 Array Of Pointers................................................................................................128

4.1.10 Pointers As Function Arguments............................................................129

4.1.11 Function Returning Pointers.....................................................................130

4.1.12 Pointers To Functions...................................................................................131

4.1.13 Pointers and Structures..............................................................................131

UNIT - V.........................................................................................................................................133

5.1 FILE MANAGEMENT....................................................................................................133

5.2.1 Introduction...........................................................................................................133

5.2.2 Defining and opening a file..........................................................................134

5.2.3 Closing a file..........................................................................................................136

5.2.4 Input/ Output Operations on Files............................................................137

5.2.5 Error handling during I/O Operations.....................................................143

5.2.6 Random access files.........................................................................................145

5.2.7 Command line arguments.............................................................................149

MODEL QUESTION PAPER 1...............................................................................................152

MODEL QUESTION PAPER 2...............................................................................................154

MODEL QUESTION PAPER 3...............................................................................................156

OBJECTIVE TEST.......................................................................................................................158
SYLLABUS

UNIT – I
Overview of C: History of C – Importance of C – Basic structure of C
programs. Constants, variables and data types: Character set – C Tokens –
Keywords and identifiers – Constants – Variables – Declaration of storage
classes – Assigning values to variables- Defining symbolic constants.
Operators and expression – Evaluation of expressions – Precedence of
arithmetic operators – Type conversions in expressions – Operator
precedence and associatively – Mathematical functions. Managing input and
output operations: Reading and writing a character – Formatted input and
output.
UNIT – II
Decision making and branching: Simple IF, IF-ELSE, Nesting of IF-ELSE,
ELSE-IF ladder, Switch statements – GOTO statements. Decision making and
looping: WHILE statement – DO statement – FOR statement – Jumps in loops.
Arrays: Definition & Declaration – One dimensional – Two dimensional – Multi
dimensional arrays - Dynamic arrays.
UNIT – III
Character arrays and strings: Introduction – Declaring and initializing
string variables – Reading strings from terminal – Writing strings to screen –
String handling functions – Table of strings. User – Defined functions:
Introduction – Need for user – Defined function – A Multi- function program –
Elements of user – Defined function – Definition of functions – Return values
and their types – Function calls – Function declaration – All category of
functions – Nesting of functions – Recursion – Passing arrays to functions –
Passing strings to function.
UNIT – IV
Structures and Unions: Introduction – Defining a structure – Declaring
structure variables – Accessing structure members – Structure initialization –
Copying and comparing structure variables – Arrays of structures – Arrays
within structures – Structures within structures – Structures and functions –
Unions – Size of structures – Bit fields. Pointers: Introduction – Understanding
pointers – Accessing the address of a variable – Initializing of pointer
variables. Chain of pointers – Pointer expressions –Pointers and arrays –
Pointers and character strings – Arrays of pointers – Pointers as function
arguments – Functions returning pointers – Pointers to functions – Pointer
and structures.

UNIT – V

File Management : Introduction – Defining and opening a file –Closing a


file – Input/Output operation on files – Error handling during I/O operations –
Random access files-command line arguments.

BOOK FOR STUDY

1. E. Balgurusamy, “Programming in ANSI C”, 5 Edition, Tata McGraw Hill,


New Delhi, 2010.

REFERENCE BOOKS

1. Herbert Schildt, “C: The complete Reference”, 4 Edition, McGraw Hill,


2003. st

2. [Link],“Programming in C”, 1 Edition, Cengage Learning, 2012


Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
UNIT - I
1.1 OVERVIEW OF C
1.1.1 History of C
In 1967, Martin Richards developed a language called BCPL. (Basic
Combined Programming Language). In 1970, ken Thompson created a
language using many features of BCPL and called it simply B. C was evolved
from ALGOL, BCPL, and B by Dennis Ritchie at Bell laboratories in 1972.

1.1.2 Importance of C
It is a robust language. It is rich in set of built-in functions and
operators that can be used to write any complex program. The C compiler
combines the capabilities of an assembly language with the features of a
high-level language. It was well suited for writing both system software and
business packages.

Programs written in C are efficient and fast. C is highly portable. C


programs written for one computer can be run on different with little or no
modification. Portability is important if we want to use computer with
different operation system. C language is well suited for structured
programming. Another important feature of C is its ability to extend itself.

1.1.3 Basic Structure of C Programs


Program can be viewed as a group of building blocks called functions.
Functions are subroutine that may include one or more statements designed
to perform a specific task. A C program may contain one or more sections.

1
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
DOCUMENTATION SECTION

LINK SECTION

DEFINITION SECTION

GLOBAL DECLARATION SECTION

main() Function Section


{
Declaration Part
Execution Part
}

Subprogram section
Function1
Function2
----
----
Function

(User-defined functions)

The documentation section consists of a set of comment lines giving


the name of the program, the author and other details which the
programmer would like to use later. The link section provides instructions to
the compiler to link functions from the system library. The definition section
defines all symbolic constants.
Global section which is outside of all functions used to declare
variables used in more than one function.
2
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Every C program must have main() function section. The section
contains two parts namely declaration part and executable part. The
declaration part declares all the variables used in the executable part. There
should be one statement in the executable part.
The two parts must appear between opening and closing braces. The
program execution begins at the opening brace and ends at the closing
brace. The closing brace of the main function section is the logical end of the
program. All statements in the declaration and executable parts end with a
semicolon.
The subprogram section contains all the user-defined functions that
are called in the main function. All section except the main function section
may be absent when they are not required.
1.2 CONSTANTS, VARIABLES AND DATA TYPES
1.2.1 Character Set
The characters can be used to form words, numbers and expressions.
The character set in C are:
 letters A – Z (Uppercase) , a – z (Lowercase)
 Digits 0-9
 Special characters ( , comma ; semicolon etc. )
 White spaces,
 Blank space , horizontal tab, carriage return, new line, form feed.

3
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Trigraph Characters:-
Each trigraph sequence consists of three characters i.e, two question
marks followed by another character.
??= # number sign ??( left bracket [ ??) right
bracket[
??< { left brace ??> } right brace ??!
vertical bar
??/ \ back slash ??’ ^ caret ??_ ~ tilde
1.2.2 C Tokens
The smallest individual units are known as tokens. C has six
types of tokens as shown in figure:

C TOKENS

STRINGS
KEYWORDS OPERATORS
CONSTANTS IDENTIFIERS

SPECIAL SYMBOLS

Special symbols [ ] {}
Keywords - float, while
Constants - 15.0, 100
Identifiers - main, amount
Strings - “ABC”, “YEAR”
Operators - +, - , *

4
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
1.2.3 Keywords and Identifiers
 All keywords have fixed meanings and these meanings cannot be
changed.
 All keywords must be written in lower case.
 Ex: auto, int, float, for, if , struct, do, char, long
Identifiers:-
Identifiers refer to the name of variables, functions and arrays. They
are user defined names.
Rules for Identifiers:-
 It consists of sequence of letters, digits with a letter as a first
character.
 Both uppercase and lower case letters are permitted, underscore is
also permitted.
 Only first 31 characters are significant.
 Cannot use a keyword.
 Must not contain white space.

1.2.4 Constants
It refers to fixed values that do not change during the execution of a
program. C supports several types of constants as shown in fig:

CONSTANTS

NUMERIC CHARACTER

INTEGER REAL SINGLE CHARACTER


STRING

5
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
a) Integer Constant
 An integer constant refers to a sequence of digits. There are
three types of integers called decimal, octal, and hexadecimal.
Integer constant

Decimal Octal Hexadecimal

i) Decimal Constant
 Decimal integers consists of set of digits 0-9 , preceded by an
optional - or + sign.
Ex: 123, - 123
 Embedded spaces, commas and digit character are not
permitted between
digits.
Ex: 15,750 $’ 1000
ii) Octal
 An octal integer constant consists of any combination of digits
from the set 0 – 7 with a leading zero.
Ex: 037 0
iii) Hexadecimal
 A sequence of digits (0-9) (A-F) by ox or OX is considered as
hexadecimal integer. They include alphabets A – F (or) a – f. A
– F represent from 10 – 15
Ex OX2 ox OXbcd
b) Real Constants
 The number followed by a decimal point and the fractional part
is known as real Constants.
Ex 215. -.71
 It may be expressed in exponential
Mantissa e exponent
6
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 The mantissa is either a real number or an integer. Exponent is
an integer number with an optional + or - sign.

0.65e4 12e-2 3.18e3 -1.2 e-1

c) Single Character Constants

 A single character constant contains a single character enclosed


by a pair of single quote marks.
Ex : ‘5 ‘ ‘ X‘ ‘; ‘ ‘ ‘
d) String constants

 A string constant is a sequence of character enclosed in double


quotes. The character may be letters, numbers, special
character, and blank space.

E x: “Hello “ “1987 “ “5+3”

1.2.5 Variables
 Variable is a data name used to store a data value. It may take
different values at different times during execution.
Rules used to denote the variables:-
 It must begin with a letter.
 ANSI recognizes a length of 31 characters.
 The length should not be more than 8 characters.
 Uppercase and lowercase are significant.
 Variables should not be a keyword. White space is not allowed.
Ex: value t_raise > valid
123 % 25th > invalid

7
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Declaration of variables:-

It tells the compiler what the variable name is. It specifies


what type of data
the variable will hold. The declaration of variable must be done before
they are
used in the program.
Primary type declaration:-
 A variable can be used to store a value of any data type.
Data type v1, v2, v3……vn;
 v1, v2, v3…….vn are the names of variables. Variables are
separated by commas.
 All declaration statement must end with a semicolon.
Ex: int c1;
double ratio;
int no, total;
Data types used in declaration is:

Data type
keyword

Character char

Unsigned character
unsigned char

Integer int

Floating point float

Double precision

Floating point double

8
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Data types-
ANSI C supports three classes of data types.
I. Primary (or fundamental) data types.
II. Derived data types
III. User - defined data types
I. Primary or fundamental data types
1. Integer (int)
2. Character (char)
3. Floating point (float)
4. Double precision floating point (double).

Primary Data types

Integral type

Integer
Character

signed type unsigned type


signed char
int unsigned int
unsigned char
short int unsigned short int

long int unsigned long int

Floating point type

Float double long double

9
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Data type Range of values

char -128 to 127

int -32768 to 32,767

float 3.4e -38 to 3.48e + 38

a) Integer type
It is a Whole number. It occupies one word of storage. The range is -
32768 to 32,767( 16 bit machines) & -2,1417,483,648 to 2,147,483,647
Three classes of integer storage are - short int, int, and long int
in both signed and unsigned forms. A signed integer uses one bit for sign
and 15 bits for the magnitude of the number.

short int

int

long int

Size(bit
Type Range
s)

8 -128 - 128
char
16 0 - 65535
unsigned
int 32 -32768 to 32767

long int 32 -2147,483,648 -


2,147,483,647
float

10
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
b) Floating Point Type
Floating point type (or real) number is stored in 32 bits with 6 digits of
precision. Floating point numbers are defined in C by the keyword float. A
double data type number uses 64 bits giving a precision of 14 digits. To
extend the precision we may use long double which uses 80 bit.

float

double

long double

c) Void Type

The void type has no values. This is usually used to specify the type of
functions when they are not return any values.

d) Character Type:

A single character can be defined as a char type data. Characters are


usually stored in 8 bits. The qualifier signed or unsigned may be applied
to char. While unsigned chars have values between 0 and 255. Signed
chars have values from -128 to 127.

II. Derived data type


Arrays:-
An array is a group of related data items that share a common name.
For example:
int salary[10];
Arrays can be of any variable type.

11
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Functions:-
A function is a self-contained block of code that performs a particular
task.
For example:
printline()
{
int i;
for(i=1;i<=10;i++)
printf(i);
}
Structures: -
Structure is a method for packing of different types.
for example:
struct book
{
char name[10];
int pages;
float price;
};
Pointers:-

A pointer is a variable that hold memory address of another variable.

for example:

int *p;

p=&quantity;

III. User defined type

 typedef

 enum

12
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
typedef:-
It allows users to define an identifier that would represent an existing
data type.
It takes the general form:

typedef type identifier ;

Where type refers to an existing data type and identifier refers to the
new name given to the data type. typedef cannot create a new type.

For example: typedef int units;

typedef float marks;

units b1,b2;

marks f1[10],f2[10];
enum:-
 Another user defined data type is enumerated data type. It is
defined as follows:

enum identifier { value1, value 2,…,valuen};

 The identifier is a user defined enumerated data type which is


used to declare Variables that can have one of the values
enclosed within braces.
 The enumerated variables can only have one of the values
value1, value2,…, value n.
An example:
enum day { Monday, Tuesday,… Sunday};
weekst=Monday;
Weekend=Sunday;
 The compiler automatically assigns integer digits beginning with
0 to all the enumeration constants.
13
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
1.2.6 Declaration of Storage Class
Storage class provides information about the location and visibility.
The storage class decides the portion of the program with in which the
variables are recognized.
/*Example of storage classes*/
int m;
main ()
{
int i;
float bal;
……
function1 ();
}
function1 ()
{
int i;
float sum;
}
The variable m which has been declared before the main is called
global variable. It can be used in all the functions in the program. A global
variable is known as external variable.
The variables i, sum are called local variable because they are
declared inside a function. Local variables are visible and meaningful only
inside the functions. They are not known to other functions.

auto int count;


register char ch;
static int x;
extern long total;

14
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Storage Meaning

auto Local variable known to only to the


function in which it is declared. Default is
auto.

static Local variable which exists and retains its


value even after the control is transferred
to the calling function.

extern Global variable known to all functions in


the life.

register Local variable which is stored in the


register.

Static and external (extern) variables are automatically


initialized to zero. Automatic (auto) variables contain undefined values
(known as ‘garbage’) unless they are initially explicitly.

1.2.7 Assigning values to a variables


 Values can be assigned to variables using the assignment operator
=.

e
Variable_name = constant
constant
bat = 78.84;

 C permits multiple assignments in one line. For example,

i=0, j=10;

15
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 An assignment statement implies that the value of the variable on
the left of the = is set equal to the value of the quantity on the
right. The statement

year = year+1;

means that new value of year is equal to the old value of the
year+1;
 It is also possible to assign a value to a variable at the time
variable is
declared. This takes the following form:
data-type variable_name = constant;
Some examples are:
int val=100;
char yes= ‘x’;
 The process of giving values to variable is called initialization. C
permits the initialization of more than one variable in one
statement using multiple assignment operators.
For example:
a=b=c=0;
x=y=z=max;
 The external and static variables are initialized to zero by default.
1.2.8 Defining symbolic constants
These constants may appear repeatedly in a number of places in the
program. Mathematical constant “pi”. We face 2 problems in the subsequent
use of such programs.

a. Problem in modification of the program.


b. Program in understanding the program.
Syntax:

16
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

#define symbolic name value of


constant

17
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Ex:
# define STRENGTH 100
# define PASS MARK 50
#define MAY 200
#define PI 3.14159
Symbolic name are sometimes called constant identifier.
I .Rules

 Symbolic names have the same form as variable name (written in


capital)
 No blank space between the bound sign ‘#’ and the word define is
permitted.
 ‘#’ must be the first character in line.
 A blank space is required between # define and symbolic name and
between the symbolic name and constant.
 #define statement is must
 Symbolic names are NOT declared for data types its data type depends
on type of constant.
 #define statements may appear anywhere in the program but before it
is referenced in the program.

II. Declaring a variable as constant:


The value of certain variable to remains constant during the execution of
the program.
 Declaring variables with the qualifier const at the time of
initialization.
Ex: const int class_size=40;
 It tells the complier that the value of int variable class size must
not be modified by the program.

18
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

III. Declaring a variable as volatile:

It could be used to tell explicitly the compiler that a variable value may
be changed at any time by external sources.

Volatile int date;

1.3 OPERATORS AND EXPRESSION

An operator is a symbol that tells a computer to perform certain


mathematical or logical manipulations. C operators can be classified in to
a number of categories.
a. Arithmetic operators
b. Relational operators
c. Logical operators
d. Assignment operators
e. Increment and decrement operators
f. Conditional operators
g. Bitwise operators
h. Special operators
a. Arithmetic Operator
C provides the entire basic arithmetic operator.
Two types:
i. Binary operators
ii. Unary operators

19
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
i. Binary operators
Numeric calculations between two constant values

Binary arithmetic Exampl


operator es

+ 2+2=4

- 5-3=2

/ 10/2=5

% 11%3=2

* 2*3=6

ii. Unary operators

Unary operators are increment operator (++), decrement operator(--) and


minus(-)

Operat Description
or

- Minus

++ Increment

-- Decrement

& Address operator

Sizeof Gives the size of


operator

20
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Arithmetic operations:-

a) Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b
are integer the expression called an integer expressions and the
operation is called integer arithmetic.
a = 14
a-b =10
a+b = 18
a*b = 56
a/b = 3
a%b = 2
During integer division if both operands are of same sign the result is
truncated towards zero if one of them is negative the direction of function
is implementation dependent.
6/7 = 0 and -6/-7 = 0
-6/7 may be 0 or -1(machine dependent)
Ex:
main ()
{
int months, days;
printf (“Enter days \n”);
scanf(“%d”,&days);
days=days%3;
printf(“months=%d, days=%d”, months, days);
}

21
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
b) Real Arithmetic
An arithmetic operation involving only real operands is called real
arithmetic. An real operand may assume value either in decimal or
exponential notation

If x,y,z are floats

X=6.0/7.0=0.8571

Y=1.0/3.0=0.3333

Z=-2.0/3.0=-0.666

The operator % cannot be used with real operands.

c) Mixed-mode Arithmetic
When one of the operands is real and other is integer, the expression is
called a mixed mode arithmetic expression. If either operand is of the real
type then only the real operation is performed and result is always a real
number

15/10.0=1.5

When as 15/10=1

The arithmetic operators are used for performing basic arithmetic


operations on numerals and characters. The following table lists arithmetic
operator

22
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Operat Examp Resu


Name Description
or le lt

Adds the two operands(Can also


a+b Addition 3+5 8
be used for String concatenation)

Subtracts the second operand


A–b Subtraction 3–5 -2
from the first Operand

A*b Multiplication 3*5 15 Multiply both the operands

Divides the first operand by the


a/b Division 15 / 3 5
second

Returns the remainder after


Modulo
a%b 3%2 1 dividing the first number by the
Division
second

b. Relational Operators
Relational operators are symbols that are used to test the relationship
between two variables or between a variable and a constant. These
operators are used for checking conditions in control statements. The table
shows the various relational operators and their meaning.

23
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Operat Examp
Name Description
or le

a==
== Equal operator True if a equals b else False
b;

True if a does not equal b else


!= Not Equal operator a ! = b;
False

< Less than operator a < b; True if a less than b else False

True if a greater than b else


> Greater than operator a > b;
False

Less than or Equal a<= True if a less than or equals b


<=
operator b; else False

Greater than or equal a>= True if a greater than or equals


>=
operator b; b else False

c. Logical Operators:

Operat Symb
Example
or ol

AND && exp1 &&

24
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

exp2

exp1 ||
OR ||
exp2

NOT ! ! exp1

Operators, which are used to combine two or more relational


expressions, are called as logical operators. These operators are used to test
more than one condition at a time. The table shows the various logical
operators and their meaning:
d. Assignment Operators
Assignment operator is the most common operator almost used with
all programming languages. It is represented by “=” symbol in C which is
used to assign a value to a variable lying to the left side of the assignment
operator.

But if the value already exists in that variable then it will be


overwritten by the assignment operator(=)
Syntax: <variable> = <expression>;
Example:
X = y = z = 2;
X = (y + z);
e. Increment and decrement operators

C allows 2 very useful operators not generally found in other


languages. These are the increment and decrement operators: ++ and --
The operator ++ adds 1 to the operand, while – subtracts 1. Both are unary
operators and take the following form:

Operator Symbol Action


25
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Examples

Increment ++ Increments the operand by one


++x, x++

Decrement -- Decrements the operand by one --x,


x--

Unary operator:-

The operators that act upon a single operand to produce a new value
are called as unary operators. When the operator is used before the variable,
the operation is applied to the variable first, and then the result is used in
the expression. This type of notation is referred as prefix notation.

When the operator is used after the variable, the value of the variable
is used first, and then the operation is applied to the variable. This type of
notation is referred as postfix notation. If the value of the operand X is 3 the various
expressions and their results are

Expression Result

++X 4

X++ 3

--X 2

X-- 3

26
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 The pre-increment operation (++x) increments x by 1 and then
assigns the value to x. The post increment operation (x++)
assigns the value to x and then increments 1.
 The pre-decrement operation (--x) decrements 1 and then assigns
to x. The post –decrement operation (x--) assigns the value to x
and then decrements 1.
 These operators are usually very efficient, but cause confusion if
you try to use too many evaluations in a single statement.
f. Conditional Operators
C supports conditional operator that is known as the ternary operator

“?:&quot; It is basically used as an short hand for simple if..else

Boolean expression ? operand 1: operand 2;

The “?: operator evaluates an expression which may also be an


operand and returns operand1 if the expression is true; otherwise returns
operand2, if the expression is false. We can understand this thing with the
help of a diagram shown as:

Expression ? op1 : op2


Example:
int a=14, b=20;
int x=(a>b) ? a : b;
In the above example the value of x is assigned the value of b
since the condition is false.

g. Bitwise Operators
Bitwise operators operate on individual bits of integer (int and long)
values. If an operand is shorter than an int, it is promoted to int before doing
the operation.
It helps to know how integers are represented in binary. For example
the decimal number 3 is represented as 11 in binary and the decimal
27
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
number 5 is represented as 101 in binary. Negative integers are store in
two’s complement form. For example, -4 is 1111 1111 1111 1111 1111 1111
1111 [Link] following table lists bitwise operators.

28
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Operat Examp Resu


Name Description
or le lt

A& b And 3&5 1 1 if both bits are 1

A|b Or 3|5 7 1 if either bit is 1

A^b Xor 3^5 6 1 if both bits are different

~a Not ~3 -4 Inverts the bits

Shifts the bits of n left p positions. Zero


Left
n << p 3<<2 12 bits are shifted in to the lower order
shift
positions

Shifts the bits of n right p positions. If n is


Right a 2’s complement signed number, the
n >> p 5>>2 1
shift sign bit is shifted in to the high- order
positions

-
n >>> Right Shifts the bits of n right p positions. Zeros
4>>>2 15
p shift are shifted in to the high-order positions
8

29
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

h. Special Operators

The comma operator:-


Comma (,) operator is used to link the related expressions together.
Comma used expressions are linked from left to right and the value of the
right most expression is the value of the combined expression. The comma
operator has the lowest precedence of all operators.
Example
sum= (x=5, y=3,x+y);
The result will be sum = 8. The comma operator is used to separate
variables during declaration.

Example

int a,b,c;

The sizeof operator:-


The size of operator is not a library function but a keyword, which
returns the operand in bytes. The size of operator always, precedes its
operand. The information obtained from this operator can be very useful
when transferring a program to a different computer. This operator can be
used for dynamic memory allocation. The various expressions and results of
size of operator are

Expression Result

Sizeof(char) 1

Sizeof(int) 2

Sizeof(float) 4

30
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Sizeof(double) 8

1.3.1 Evaluation of expressions


Expression evaluated using an assignment statement of the form:
variable = expression;
x=a*b-c;
Example:
main()
{
float a,b,x,y,c;
a=9; b=12;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
printf(“x=%f\n”,x);
printf(“y=%f\n”,y);
}

Output:
x= 10.000000 y= 7.000000
1.3.2 Precedence of arithmetic operators
An arithmetic expression without parenthesis will be evaluated from
left to right using precedence of operators.
High priority * / %
Low priority + -
x= a-b/3+c*2-1
Let a=9,b=12 and c=3
x= 9-12/3+3*&2-1
Step 1=9-4+6-1
Step 2= 5+6-1
Step 3= 10
31
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
I. Rules
 First, parent the sized sub expression from left to right are evaluated
 If parentheses are nested, the evaluation begins with innermost sub
expressions
 The associability rule is applied when two or more operators of the
same precedence level appear in sub expressions
 Arithmetic expressions are evaluated from left to right using the rules
of precedence
 When parentheses are used, the expressions within parentheses
assume highest priority
1.3.3 Type conversion in Expressions
a. Implicit Type Conversion

C permits mixing of constants and variables of different types in an


expressions. C automatically converts any inter mediate values to the proper
type so that the expression can be evaluated without losing any significance.
This automatic conversation is known as implicit type conversion.

Example:
int i, x;
float f;
double d;
long int l;
b. Explicit conversion
The process of such a local conversion is known as explicit conversion
or casting
a value. Type name) expression. X=(int)+5-- 7.5 id converted to integer by
truncation

32
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
1.3.4 Operator Precedence and Associatively
Each operator in C has a precedence associated with it. This
precedence is used to determine how an expression involving more than one
operator is evaluated.
There are distinct levels of precedence and an operator may belong to
one of these levels. The operators at the higher level of precedence are
evaluated first.
The operators of the same precedence are evaluated either from left to
right or from right to left depending on the level.
This is known as associativity property of an operator. The groups are
in the order of decreasing precedence. Rank1 indicates the highest
precedence level and 15 the lowest.
I. Rules of Precedence and Associatively
a. Precedence rules decides the order in which different operators are
applied.
b. Associatively rule decides the order in which multiple occurrences of
the same level operator are applied.
 Consider the following conditional statement:
If (x = = 10 + 15 & & y <10)
 The precedence rules says that the addition operator has a higher
priority than the logical operator (&&) and the relational
operators(= = and <).
If(x = = 25 && y < 10)
 The next step is to determine whether x is equal to 25 and y is less
than 10. if we assume a value of 20 for x and 5 for y, then
X = = 25 is false (0)
Y < 10 is true (1)

 Note that since the operator < enjoys highest priority compared to
= = , y <10 is tested first and then x = = 25 is tested,

33
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

We get finally as;

If ( FALSE &&TRUE)

 Because the condition is false , the complex condition is FALSE.

1.3.5 Mathematical Function

C support the following math function

Function Meaning

acos(x) Arc cosing of x

asin(x) Arc sine of x

atan(x) Arc tangent of x

atan2(x,y) Arc tangent of x/y

cos(x) Cosine of x

sin(x) Sine of x

tan(x) Tangent of x

34
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Other function:

x rounded up to the nearest


ceif(x)
integer

exp(x) e to the power(ex)

fabs(x) Absolute value of x

X rounded down to nearest


floor(x)
integer

fmod(x,
Remainder of x/y
y)

log(x) Natural log of x,x>0

Log(109
Base 10 log of x,x>0
x)

pow(x,y) X to the power is (xy)

sqrt(x) Square root of x,x>=0

1.4 MANAGING INPUT AND OUTPUT OPERATIONS


1.4.1 Reading and Writing a character
The simplest of all input/output operations is reading a character from
standard input unit and writing it to the standard output unit. Reading single
character can be done by using the function getchar.
35
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Variable-name = getchar();

When this statement is encountered, the computer waits unit a key is


pressed and then assigns this character as a value to getchar functions
Ex: char name;
name= getchar();
Example:
#include<stdio.h>
main()
{
char answer;
printf(“would you like my name ?\n”);
printf(“type y for yes and n for no:”);
answer=getchar();
if(answer= =’y’ || answer = =’y’)
printf(“\n My name is Busy BEE \n”);
else

printf(“\n \n you are good for nothing \n”);

}
Character test function:-
a .Function
isalnum(c)  is c an alphanumeric character
isaplha(c)  is c an alphabetic character
isdigit(c)  is c a digit
islower(c)  is c a lowercase
isprintf(c)  is c a printable character
ispunct(c)  is a punctuation marks
isspace  is a while space character
isupper(c) is a uppercase letter

36
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
b. Writing a character
putchar for writing characters
putchar(variable name)
where variable name is a type char variable containing a character
answer = ‘y’;
putchar(answer);
c. Program contain 3 new functions
 islower  is conditional fun and takes value true
 toupper  if arguments is lowercase alphabet
 tolower  upper to lower
#include<stdio.h>
#include<conio.h>
main()
{
char alphabet;
printf(“Enter an alphabet”);
putchar(“\n”);
alphabet = getchar();
if (islower(alphabet));
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
Output:
Enter an alphabet
a
A

Enter an alphabet
q
37
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
q

1.4.2 Formatted Input and output


a. Formatted Input
 Formatted input refers to an input data that has been arranged in
particular format
Ex: 15.73 123 john
 This line contains three pieces of data arranged in a particular form.
Reading the formatted data with scanf function.
 General form of scanf is
scanf(“control string”,arg1,arg2,……arg n);
 Control string contains field specification of the conversion
character % data type character and an optional number specifying
the field width. Blanks, tabs or new line.
b. Inputting Integer Numbers
 The field specification for reading an integer number is : %w d. (%)
indicated that a conversion specification. w is an integer number
that specifies the field with of the number to be read, d is known as
data type character

Ex: scanf(“%2d %5d”,&num1, &num2);

 An input field may be skipped by specifying * is the place of field


width

scanf(“%d %d %d”,&a,&b)

assign data 123 436 789

38
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
c. Inputting real numbers
scanf(“%f%f%f”,&x,&y,&z);

%f or real number type

d. Inputting character strings


 Following are the specification for reading character strings

%ws or %wc
 Some version of scanf supports the following conversion
specification for string
%[character]
%(^character)
Ex:
main()
{
char address[80];
printf(“Enter address\n”);
scanf(“%[a-z]” address);
printf(“% 80 s\n\n”,address);}
Output:
Enter address
new delhi 110002
new delhi
Commonly used scanf format codes:
Code Meaning
%c read a single character
%d read a decimal integer
%c read a floating point value
%f read a floating point value
%g read a floating point value
%h read a short integer
39
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
%o read a octal integer
%s read a string
%i read a decimal hexadecimal or octal
integer
%u read an unsigned integer
%x read a hexadecimal integer
I. Rules for scanf
 Each variable to be read must have a field specification.
 For each field specification there must be a variable address pf proper
type.
 Any non white space character used in the format string must have a
matching character in the user input.
 Never end the format string with white space. It is fatal error.
 The scanf reads until.
 A white space character is found in a numeric specification or
 The maximum number of character have been read.
 An error is detected or
 The end of file is reached.
a. Formatted output
 printf statement is provide formatted output
 printf (“control string”,arg1,arg2,………….argn);
Control string consist of 3 items:-
 Charcter that will be printed on the screen as they appear.
 Format specification that defines the output format for display of each
item.
 Escape sequence character such as \n, \t and \b

40
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
A simple format specification has the following form:-

%w.p type-
specifier
 w is an integer number that specifies that total no’ of columns for
output value
 p is optional
Output of integer numbers:-
% wd
d is value to b printed is an integer.
The number is written right justified.
Format Output
printf(“%d”,9876) 9 8 7 6
printf(“%6d”,9876) 0 9 8 7 6 0
printf(“%2d”,9876) 9 8 7 6
printf(“%-6d”,9876) 9 8 7 6 0 0
printf(“%06d”,9876) 0 0 9 8 7 6
Output of real numbers:-
The output of a real number may be displayed in decimal notation
using following format specification
%wpf
w indicates minimum no’ of positions that are to be used for display
values
y=98.7654
p indicates the no’ of digits to be displayed after the decimal point

41
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Format Output

printf(“%7.4f”,y) 9 8 .7 6 5 4 0

printf(“7.2f”,y) 0 0 9 8 . 7 7

printf(“%-7.2f’,y) 9 8 . 7 7 0 0

printf(“%f”,y) 9 8 . 7 6 5 4

printf(“%*.*f”, width, precision, number);

It is equivalent to printf(“%7.2f”, number);

b. Printing of a single character

%wc

The character will be displayed right justified in the field of w


columns. The default for w is 1

Ex: printing string “NEWDELHI 110001” containing 16 character

Specification used printf codes:-

Code Meaning

%c print a single character


%d print a decimal integer
%e print a floating point value in exponential form
%f floating point value
%g floating point value either e-type or f-type
%i signed decimal integer
%s print a string
%o octal number
%u unsigned decimal integer

42
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
UNIT – II
2.1 DECISION MAKING AND BRANCHING
C program executes program sequentially. Sometimes, a program
requires checking of certain conditions in program execution. C provides
various key condition statements to check condition and execute statements
according conditional criteria. These statements are called as 'Decision
Making Statements' or 'Conditional Statements.

(a) Decision making with IF statement

The if statement is powerful decision- making statement and is


used to control the flow of execution of statement. The if statement may be
implemented in different forms depending on the complexity of condition to
be executed.

The different forms are

 Simple if statement
 If…..else statement
 Nested if..else statement
 Else…..if ladder

2.1.1 Simple if statement


The general form of a Simple IF statement is

if (test expression)

statement-block;

statement-x;
Where the statement –block may be a single statement or a group of
statements. If the test expression is true, the statement-block will be

43
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
executed; otherwise the statement-block will be skipped and the execution
will jump to the statement-x. Note: when the condition is true both the
statement block and the statement-x are executedFlow chart

Test
expression
?

Statement-x Statement block

Next statement

EXAMPLE :
A=10;
B=5;
if (A>B)
printf(“ A is the largest number”);
If the given condition is satisfied then computer will print the message
“A is the largest number” and if not simply skip this statement.
2.1.2 The if…else statement
The if…else statement is an extension of the simple if statement.
The general format is
if(condition)
{
Statements;
}
else
statements;

44
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
If the test expression is true, then the true-block statement(s),
immediately following the if statements are executed; otherwise ,the false-
block statement(s) are executed. In both the case, the control is transferred
subsequently to the statements-x.

FLOW CHART OF if…Else CONTROL

entry

True false
Test
Condition
?
True-block
False-block statement
statement

Statement-x

EXAMPLE :
int x=10, y=20;
if(x > y)
printf(“ x is largest number”, x);
else
printf(“y is largest number “,y);

45
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.1.3 Nesting of if … else statements
When a series of decision are involved, we may have to use more
than one if….else statement in nested form as shown below

if (test condition-1)

if (test condition-2)

statement -1;

else

statement-2;

else

statement-3;

statement-x;

If the condition-1 is false, the statement-3 will be executed; otherwise if


continues to perform the second test. If the condition-2 is true, the

46
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
statement-1 will evaluated; otherwise the statement-2 will be evaluated and
then the control is transferred to the statement-x.
EXAMPLE:
main()
{
float a,b,c;
printf(“enter the three values”);
scanf(“%f%f%f”,&a, &b, &c);
if (a>b)
{
if(a>c)
printf(“a is greater”);
else
printf(“c is greater”);
}
else
{
if(c>b)
printf(“c is greater”);
else
printf(“b is greater”);
}
}

47
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.1.4 The else..if ladder
There is another way of putting if’ together when multipath decisions
are involved. A multipath decision is a chain of if’s in which the statement
associated with each else is an if.

It takes the following general form

if (condition-1)

statement-1;

else if (condition-2)

statement-2;

else if (condition-3)

statement-3;

else if (condition-n)

statement-n;

else

default-statement;

statement-x;

This construction is known as the else..if ladder. The conditions are


evaluated from the top downwards. As soon as a true condition is found, the
statement associated with it is executed and the control is transferred to the
statement-x. When all the n conditions become false, then the final else
containing the default –statement will be executed.

48
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Example:
Average marks Grade
80 to 100 Honors
60 to 79 First division
50 to 59 Second Division
0 to 39 fail
This grading can be done using the else if ladder as follows:
if (marks > 79)
grade = “honors”;
else if (marks>59)
grade = “first division”;
else if (marks >49)
grade = “second division”;
else if (marks>39)
grade=”third division”;
else
grade=”fail”;
printf(“%s\n”,grade);
Rules for indentation:-
 Indent statement that are dependent on the pervious statement;
provide at least three spaces of indentation
 Align vertically else clause with their matching if clause
 Use braces on separate lines to identify a block of statement
 Indent the statements in the block by at least three spaces to right of
the braces
 Align the opening and closing braces
 Use appropriate comments to signify the beginning and of blocks
 Indent the nested statement as per the above rules
 Code only one clause or statement on each line

2.1.5 The switch statement


49
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
C has a built-in-multi way decision statement known as a switch. The
switch statement tests the value of a given variable against a list of case
values and when a match is found, a block of statement associated with that
case is executed. The general form of the switch statement is as shown
below:

switch (expression)

case value-1:

block-1;

break;

case value-2:

block-2;
……..
break;
default:

default-block;

break;

statement-x;

 Where, the expression is an integer expression or character


value1,value2,…. are constants or expressions and are known as case
labels.
 Each of these values should be unique within a switch statement
Block1, block2 are statement list and may contain zero or more
statements.

50
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 The break statement at the end of each block signals the end of a
particular case and causes an exit from switch statement, block1,
block2 are statement list and may contain zero or more statements.
Statement x;

The break statement at the ends of each block signal the end of a
particular case and causes an exit from the switch statement, transferring
the control to the statement x following switch. The default is an optional
case, when present it will be executed if the value of the expression downs
not match with any of the case values.

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char choice;
printf(“\n enter choice:”);
choice=gerchar();
if(choice>=’a’&& choice<=’z’)
choice=32;
switch(choice)
{
case ‘c’:
printf(“\n computer science”);
break;
case ’b’:
printf)”\n bca”);
break;
case ’c’:
printf)”\n mca”);
break;
51
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
default:
printff(“\n error”)
break;
}
getch();
}
Rules for switch statement:-
 The Switch expression must be in integral type.
 Case labels must be constant expressions.
 Case labels must be unique. No two labels can have the same
value.
 Case labels must end with semicolon.
 The break statement transfers the control out of the switch
statement.
 The break statement is optional. That is two or more case
labels may belong to the same statements
 The default label is optional. If present it will be executes
when the expression does not find a matching case label.
 The default may be placed anywhere but usually placed at the
end.
 It is permitted to nest switch statements.
The ?: operator:-
The c language has an unusual operator, useful for making two-way
decisions. This operator is a combination of ? and :, and takes three
operands. This operator is popularly known as the conditional operator. The
general form of use of the conditional operator is as follows
Conditional expression ? expression1 : expression2
The conditional expression is evaluated first. if the result is
nonzero, expression1 is evaluated and is returned as the value of the

52
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
conditional expression. Otherwise, expression2 is evaluated and its value is
returned. for example
if(x>0)
flag = 0;
else
flag = 1;
can be written as
flag =(x<0) ? 0 : 1 ;
2.1.6 The goto statement
 The goto statement helps to branch unconditionally from one
point to another in the program.
 The goto requires a label in order to identify the place where
the branch is to be made.
 A label is any valid variable name and must be followed by a
colon.
 The label is placed immediately before the statement when
the control is to be transferred.
Syntax:
goto label; label;
………… statement;
………… …………
label; …………
statement; goto label;

Forward jump Backward jump

The label: can be anywhere in the program before or after the goto
label : statement, a loop will be found and some statements will be executed
repeatedly, such a jump is known as a backward jump. If the label: is placed

53
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
after the goto label, some statements will be skipped and the jump is known
as a forward jump.

Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
x=16;
y=12;
if(x==y)
x++;
else
goto ERROR;
ERROR:
printf(“Fatal error,existing \n”);
getch();
}
2.2 DECISION MAKING AND LOOPING
Looping statement used at perform repetitive processes without the
use of go two statements. A program loop consists of two statements. i.e
 Body of the loop
 Control statement
The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statements in the loop, a control
structure may classify in to two types.
 Entry-controlled loop
 Exit-controlled loop
54
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Entry- controlled Loop:-
In this loop, the control conditions are tested before the start of the
loop execution. If the conditions are not satisfied, then the body of the loop
will not be executed. Otherwise it is called as pre-test loop.

Exit-controlled Loop:-
In this loop, the test is performed at end of the loop and therefore the
body is executed Unconditionally for the first time. Another name for exit
controlled loop is post-test loop.
A looping process includes the following four steps:
 Setting and initialization of a condition variable.
 Execution of the statements in the loop.

 Test for a specified values of the condition variable for execution


of the loop.

 Incrementing or updating the condition variable.

The decision making and looping statements in C are follows:

 The While statement


 The Do statement
 The For statement

55
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Entry Entry

False Body of the


Test loop
conditio
n

True

Test
Body of the condit
ion
loop
True False

Exit controlled loop Entry controlled loop

56
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.2.1 While Statement
Syntax:
while (test condition)
{
statement 1;
}
statement 2;
 The while is an entry-controlled loop statement. The test-condition
is true,
 Then the body of the loop will be executed, otherwise statements 2
is executed.
 The process of repeated execution continuous until the test-
condition finally becomes false and the control is transferred out of
the loop. The body of the loop may have one or more statement.
 The braces are need only if the body contains two or more
statements.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int digit=1;
clrscr();
while(digit<=10)
{
printf(“%d\n”,digit);
getch();
}

57
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.2.2 Do Statement
Syntax:
Do

Statements;

While(condition)

The do-while is an exit controlled loop.

o The program proceeds to evaluate the body of the loop first.


o At the end of the loop, the test condition in while is evaluate.
o If the test condition is true, the program continues to evaluate the
body of the loop once again.
o The process continues as long as the condition is true.
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int count=0;
char c;
do
{
c=getchar();
If(c==’\n’)
++count;
}
while(c!=EOF);

printf(“the no of lines entered are:%d\


n”,count);
58
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}

2.2.3 For Statement


The loop is another entry-controlled loop and is used when an action is
to be repeated for a predetermined no of times.

Syntax:
for(initialization; test-condition; increment)

body of the loop

 The initialization of the control variable is done first.


 The value of the control variable is tested using the test-condition.
 If the test condition is true, the body of the loop is executed; otherwise
the loop is terminated and the execution continues with the statement
that immediately follows loop.
 The execution of the for statement is as follows:
 Initialization of the control variable is done first using assignment
statement
 The value of the control variable is done first using the test condition
 When the body of the loop is executed the control is transferred back
to the for statement after evaluating the last statement in the loop.
 The expression is an initialization it is executes only once for any loop.
The expression2 is the termination test. It is checked on every iteration
through the loop and as long as it remains true the loop continues. It is
false at the beginning of the loop the statements within the body of the
loop are never executed.

59
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.2.4 Jumps In Loops
 Break statements(Jumping out of a loop):
 The break is used inside a loop or conditional statement.
 It causes the remainder of the statement to be skipped and execution
to proceed to the next statement.
 With a loop, this means that no further iterations are executed.
Skipping a part of a loop:-
The continue is used inside a loop, it causes the remainder of the
current iteration to be skipped and the next iteration to be started.
Difference between break statements and continue statements.
Break Statement Continue Statement

It can be used in switch statement It cannot be used in switch statement

It causes premature exit of the It causes skipping of the statements


loop enclosing it. following it in the body of the loop.

The control is transferred to the The control is transferred back to the


statement following the loop. loop.

The loop may not complete the The loop completes the intended
intended number of iterations. number of iterations.

2.3 ARRAYS
2.3.1 Definition & Declaration
An array is a group of related data items that store a common name. A
list of items can be given one variable name using only one subscript and
such a variable is called a single –subscripted variable or a one-dimensional
array.

60
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.3.2 One-dimensional arrays
 A list of items can be given one variable name using only one subscript
and such a variable is called as subscripted variable or one
dimensional array. In mathematics, we often deal with variables that
are single subscripted that instance we use the equation to calculate
the average of n values of x.

 The subscripted variable xi refers to the i th element of x. In c, single-


subscripted variable xi can be expressed as

x[1],x[2],x[3],…x[n]

 The subscripted can begin with number 0. That is x[0] is allowed. For
example, if we want to represent a set of five numbers, say (35, 40,
20, 57, and 19) by an array variable number, then we any declare the
variable number as follows

int number[5];
and the computer reserves five storage locations as shown below

int number[5];

and the computer reserves five storage locations shown below

number[0]=35

number[1]=40

number[2]=20

number[3]=57

number[4]=19

61
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Declaration of one dimensional array:-
Syntax:
type variable name[size]
The type specifies the type of element that will be contained in the
array, such as int , float ,or char and the size indicates the maximum
number of elements that can be stored inside the array.
Example:
int value[20];
It declares the value to be an array of integers containing 20 integer
elements.
The C language treats character strings as array of characters. Thus
the size in this case will indicate the maximum number of characters the
string variable can hold.
Example: char address[50];
It declares the address as a character array variable that can hold a
maximum of 50 characters.
The last element position is always occupied by a null character like’\
0’, so the size should be chosen one more than the actual string being
stored.
Example:
float height[50];
int group[10];

char name[7];

It ‘M’ declares the name as a character array (string) variable


that can hold a maximum 7characters“MCA BCA”.
‘C’

‘A’

‘‘

‘B’
62

‘C’

‘A’
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Each character of the string is treated as an element of the array


name and is stored in the memory as follows:

Initialization of one-dimensional arrays:-


The elements of arrays can be initialized in same way as the ordinary
variables are declared. The Array can be initialized in either of the two
stages.
 At Compile time
 At Runtime
Compile time initialization:-
Syntax:
type array-name[size]={list of values}
The values in the list are separated by commas.
Example: int number[3]={0,0,0};
The size can be omitted. In such case the compiler allocates enough space
for all initialized elements
Example: int counter[]={1,1,1,1}

63
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Run time initialization:-
An array can be explicitly initialized at run time.
Example:
#include<stdio.h> Output:
#include<conio.h> Enter the Value:3
void main() 235
{ 125
int a[10]I,j,n,t; 346
clrscr(); Largest of 3 Numbers is
: 346
printf(“Enter the Value”); Smallest of 3 Numbers is :
125
scanf(“%d”,&n);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
for(i=1;i<=n-1;i++)
for(j=1;j<=n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf (“Largest of %d Numbers is %d”,n,a[n]);
printf(“Smallest of % Numbers is %d”,n,a[1]);
getch();
}

64
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.3.3 Two dimensional arrays
Two dimensional array is mainly used to store a set of values in matrix
form.
Syntax:
Datatype array-name[row_size][colmn_size];
 Data type alomg with the array name is being given, row size indicates
the size of the row with column size indicates the column size of the
matrix.
 The data type is common for all elements of the array. The
representation of memory storage of two dimensional arrays can be
visualized as follows
Column 0 Column1
[0][0] [0][1]
Row 0-------- 100 200

[1][0] [1][1]
Row 100 200 1--------

Example:
int a[2][3];
 2 rows,3 colunms
 Each row contain 3 column.
 a(1,1) a(1,2) a(1,3)
 a(2,1) a(2,2) a(2,3)
 There are 6 integer elements in the matrix a.
Initialization:-
Similar to the one-dimensional the two-dimensional arrays are
initialized.
Example:
int array[2][3]={1,2,3,4,5,6};

65
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
In the above case elements of the first row are initialized to 1,2,3 &
second row elements are initialized to 4,5,6. The initialization can be done
row wise also, for the above example it is
int array[2][3]={{1,2,3,},{4,5,6}};
If the initialization has some missing values then they are
automatically initialized to 0.
Example:
int array[2][3]={{3,4},{5}}
In this case the first two elements of the first row are initialized to 3,4 while
the first element of the second row is initialized to 5 & rest all elements are
initialized to 0.
int a[2][2] ={0,0,2,1} int a[2][2]={{0,0},{2,1}}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],I,j,k;
clrscr();
printf(“Matrix A:”);
for(i=1;i<=2;i++)
{
printf(“\n”);
for(j=1;j<=2;j++)
scanf(“%d”,&a[i][j]);
}
printf(“Matrix B:”);
for(i=1;i<=2;i++)
{
printf(“\n”);
66
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
for(j=1;j<=2;j++)
scanf(“%d”,&b[i][j]);
}
printf(“\n ADDITION OF MATRIX A AND B:”):
for(i=1;i<=2;i++)
{
printf(“\n”);
for(j=1;j<=2;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(“%d”,c[i][j]);
}
}
printf(“\n SUBRACTION OF MATRIX A AND B:”):
for(i=1;i<=2;i++)
{
printf(“\n”);
for(j=1;j<=2;j++)
{
c[i][j]=a[i][j]-b[i][j];
printf(“%d”,c[i][j]);
}
}
printf(“\n MULTIPLICATION OF MATRIX A AND B:”):
for(i=1;i<=2;i++)
{
c[i][j]=0;
printf(“\n”);
for(j=1;j<=2;j++)
for(k=1;k<=2;k++)
67
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
{
c[i][j]=a[i][j]+b[k][j]*b[i][k];
printf(“%d”,c[i][j]);
}
}
printf(“\n TRANSPOSE OF MATRIX A AND B:”):
for(i=1;i<=2;i++)
{
printf(“\n”);
for(j=1;j<=2;j++)
{
printf(“%d”,a[i][j]);
}
getch();
}
2.3.4 Multidimensional array
C allows arrays more than two (or) three (or) more dimensions.
Syntax:
type array_name[s1][s2][s3]……[sn];
The total number of elements in any dimension of arrays is the product
of all sizes included in the declaration. So it will be s1*s2* s3*……..*sm.
Higher dimension arrays are required in the field of scientific
computing, weather forecasting , time-space analysis ,etc.,
Example:
int a[3][2][2];
 3 for college
 2 for department
 2 for class

68
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.3.5 Dynamic array
An array is created at compile time by specifying the size in the source
code, that is it has a fixed size and cannot be modified at run time. The
process of allocating memory at compile time is known as static memory
allocation and the arrays that receive static memory allocation are called
static array. This approach works fine as long as the user knows exactly what
the data requirements are created by using pointer variable and memory
management function malloc, calloc, and realloc. These function are
included in the header fine # include<stdlib.h>. The concept of dynamic
array is used in creating and manipulating data structures such as linked list
stacks and queues.
The application of an array
 It is used in printers for accessing array.
 By passing array as function parameters.
 It is used as members of structure.
 By using structure type data as array lement.
 Arrays are used as dynamic data structures.
 It is used in manipulating character arrays and strings.

69
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
UNIT - III
3.1 CHARACTER ARRAYS AND STRINGS
3.1.1 Introduction
A string is a sequence of characters that is treated as a single data
item. Any group of characters (except double quote sign) defined between
double quotation marks is a string constant. Example

“Man is obviously made to think”

Character arrays or strings are used by programming languages to


manipulate text such as words and sentences. The common operations
performed on character strings include:

 Reading and writing strings.


 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.
A string constant is a one dimensional array of characters terminated
by a null(‘\0’). For example

char name[]={‘H’,’E’,’L’,’L’,’O’,’\0’};

Each character in the array occupies one byte of memory and the last
character is always ‘\0’.

3.1.2 Declaring and Initializing String Variables


 C does not support strings as a data type. However, it allows us to
represent strings as character arrays. In C, therefore, a string variable
is any valid C variable name and is always declared as an array of
characters.

 The general form of declaration of string variable is :

70
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

char string_name[size];

 The size determines the number of characters in the string_name.


Some examples are:

char city[10];

 When the compiler assigns a character string to a character array, it


automatically supplies a null character(‘\0’) at the end of the string.
Therefore the size should be equal to the maximum number of
characters in the string plus one.

 C also permits us to initialize a character array without specifying the


number of elements. For example, the statement

char string[ ] = {‘G’,’O’,’O’,’D’.’\0’}

defines the array string as a five element array. We can also declare
the size munch larger than the string size in th initialize. For example, the
statement

char string[10] = “GOOD”

is permitted.

3.1.3 Reading Strings from Terminal


(a) Using scanf function
The input function scanf can be used with %s format specification to
read in a string of characters.
Example:
char address[10];
scanf(“%s”,address);

71
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The scanf function automatically terminates the string that is read
with a null character and therefore the character array should be large
enough to hold the input string plus the null character.
We can also specify the field width using the form %ws in the scanf
statement for reading a specified number of characters from the input string.
Example:
scanf(“%ws”,name);
The width w is equal to or greater than the number of characters typed
in. The entire string will be stored in the string variable. The width w is less
than the number of characters in the string. The excess characters will be
truncated and left unread.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
char name[25];
clrscr();
printf(“Enter Your Name”);
scanf(“%s”,name);
printf(”Hello %s!”,name);
getch();
}
Output:
Enter Your Name
POOJA
Hello POOJA!

72
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
(b) Reading a Line of Text
The scanf statement with %s or %ws can read only strings without
whitespaces. That is, they cannot be used for reading a text containing more
than one word. However, C supports a format specification known as the edit
set conversion code %[..] that can be used to read a line containing a variety
of characters, including whitespaces.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
char name[25]:
clrscr();
printf(“Enter the string\n”);
scanf(“%[^\n]s”,name);
printf(“%s”,name);
}
Output:
Enter the string
SALEM SOWDESWARI COLLEGE
SALEM SOWDESWARI COLLEGE
(c) Using getchar and gets functions
To read a single character from the terminal, getchar function is used.
We can use this function repeatedly to read successive single characters
from the input and place them into a character array. Thus, an entire line of
text can be read and stored in an array.
The reading is terminated when the new line character(‘\n’) is entered
and the null character is then inserted at the end of the string.
The getchar function call takes the form:

char ch;
73
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
ch=getchar();

Another and more convenient method of reading a string of text


containing white spaces is use the library function gets available in the
<stdio.h> header file. The general format is:
char string_name[20];
gets(string_name);
Example:
#include<stdio.h>
#include<conio.h>
main()
{
char my_name[30];
clrscr();
printf(“Enter Your Name\n”);
gets(my_name);
puts(“My name is:”);
puts(my_name);
getch();}
Output:
Enter Your Name
RISHI KUMAR
My name is RISHI KUMAR

74
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
3.1.4 Writing Strings to Screen
(a) Using printf Function
The printf function with %s format is used to print strings to the
screen. The format %s can be used to display an array of characters that is
terminated by the null character. For example, the statement
printf(“%s’,name);
can be used to display the entire contents of the array name. We can also
specify the precision with which the array is displayed. For instance, the
specification
%10.4
indicates that the first four characters are to be printed in a field width of 10
columns. The features of the %s specifications are :
 When the field width is less than the length of the string, the entire
string is printed.
 The integer value on the right side of the decimal point specifies the
number of characters to be printed.
 When the number of characters to be printed in specified as zero,
nothing is printed.
 The minus sign in the specification causes the string to be printed left-
justified.
 The specification % .ns prints the first n characters of the string.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
char name[25];
clrscr();
printf(“Enter the name”);
scanf(“%s”,name);
75
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(”Name is %s”,name);
}
Output:
Enter the name
Raguvaran
Name is Raguvaran
(b) Using putchar and puts Functions
C supports another character handling function putchar to output
the values of character variables. It takes the following form:
char ch=’A’
putchar(ch);
Another and more convenient way of printing string values is to use
the function puts declared in the header file<stdio.h>. The general
format is:
puts(str);
Example:
#include<stdio.h>
#include<conio.h>
main()
{
char name[20];
clrscr();
printf(“Enter the name\n”);
gets(name);
puts(“Name is : ”);
puts(name);
}

76
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Output:
Enter the name
RAMYA
Name is : RAMYA
3.1.5 String Handling Functions
The C library supports a large number of string-handling functions that can be used to carry out
many of the string manipulations. Following are the most commonly used string-handling functions
Function Action
strcat() Concatenates two strings
strcmp() Compares two strings
strcpy() Copies one string over
another
strlen() Finds the length of a string
(a) Combining strings together (strcat)
The strcat function concatenates the string2 to the end of the string1.
The general format is:
strcat(string1,string2);
where string1 and string2 are the name of the string variables.
Example:
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char s1[20],s2[10];
clrscr();
puts(“Enter two strings : ”)
scanf(“%s”,s1);
scanf(“%s”,s2);
printf(“Concatenate function\n %s”,strcat(s1,s2));
77
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(“\nS1=%s”,s1);
printf(“\nS2=%s”,s2);
}
Output:
Enter two strings :
Indira
Gandhi
Concatenate function
IndiraGandhi
S1=IndiraGandhi
S2=Gandhi
(b) Comparing two strings (strcmp)
The strcmp function compares two strings and finds out whether they
are same or different. If two strings are equal, this function returns a value
zero.
Otherwise, the numerical difference between the first non-matching
character is returned. The general format is:
strcmp(string1,string2);
where, string1 and string2 are the name of the string variables. This
compares the left-most n characters of string1 and string2 and returns
 0 if they are equal
 negative number, if string1 sub-string is less than string1 and
 positive number
Example:
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char string1[]=”Jerry:;

78
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
char string2[]=”Ferry”;
int i,j;
clrscr();
i=strcmp(string1,”Jerry”);
j=strcmp(string1,string2);
printf(“\ni=%d\tj=%d”,I,j);
}
Output:
i=0 j=4;
(c) Copying one string into another (strcpy)
The strcpy function copies the contents of one string into another. The
strcpy function works like a string assignment operator.
The content of string2 is copied to string1. The general format is:
strcpy(string1,string2);
where string1 and string2 are character arrays.
Example:
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char source[]=”sayonara”;
char target[20];
strcpy(target,source);
printf(“\nSource string=%s”,source);
printf(“\nTarget string=%s”,target);
}
Output:
Source string=sayonara
Target string=sayonara

79
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
(d) Finding the length of a string (strlen)
The strlen() function counts and returns the number of characters in a
string. It takes the form,
n=strlen(string);
where n is an integer, which receives the value of the length of the string.
The argument may be a string constant. The counting ends at the first null
character.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
int length;
char name[20]=”Sowdeswari College”;
clrscr();
length=strlen(name);
printf(“The length of %s is %d”,name,length);
}
Output:
The length of Sowdeswari College is 18.
(e) Other String functions
The header file <sting.h> contains many more string manipulation
functions.

80
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
(i) strncpy
The strncpy function copies only left most n characters of the source
string to the target string variable. The general format is :
strncpy(string1,string2,n);
where string1 and string2 are character arrays and n is the number of
characters to be copied from the left of the string2. The left most n
characters of string2 is copied to string 1.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char *s1,*s2;
clrscr();
s1=”Computer”;
s2=”Course”;
puts(“S1=”);
puts(s1);
puts(“S2=”);
puts(s2);
strncpy(s2,s1,4);
puts(“S2=”);
puts(s2)
}
Output:
S1=Computer
S2=Course
S2=Compse
(ii) strncmp function
81
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The strncmp function compares the left most n characters of string1 and
string2 and returns:
 0 if they are equal
 negative number, if string1 sub-string is less than string1 and
 positive number
The general format is :
strncmp(string1,string2,n);
where string1 and string2 are the name of the string variables and n is the
number of characters to be compared from the left of the string1.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char *s1,*s2;
int n;
clrscr();
s1=”Pooja”;
s2=”Pooja reena”;
puts(“S1=”);
puts(s1);
puts(“S2=”);
puts(s2);
n=strncmp(s1,s2,5);
printf(“\nThe result of comparison is %d”,n);
}
Output:
S1=Pooja
S2=Pooja reena
82
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The result of comparison is 0
(iii) strncat function
The strcat function will concatenate the left most n characters of
string1 to the end of string2. The general format is :
strncat(string1,string2,n);
where string1 and string2 are the name of the string variables and n is the
number of characters to be concatenated from the left of the string2.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{ char *s1,*s2;
clrscr();
s1=”Sowdeswari”;
s2=”College”;
puts(“S1=”);
puts(s1);
puts(“S2=”);
puts(s2);
strncat(s1,s2,7);
puts(“S1=”);
puts(s1)
}
Output:
S1=Sowdeswari
S2=College
S1=SowdeswariCollege
(iv) strstr function

83
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The strstr function is used to locate a sub string in a string. The
general format is:
strstr(string1,sub-string1);
where sub-string1 is a part of the string1. This function searches the string1
to see whether the sub-string1 is contained in string1. If yes, the function
returns the position of the first occurrence of the sub-string1. Otherwise, it
returns a NULL value.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char *s1,*s2,s;
clrscr();
s1=”Good day”;
s2=”day”;
s=strstr(s1,s2);
printf(“Sub string is %s”,s);
}
Output:
Sub string is day

84
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
3.1.6 Table of Strings
A list of names can be treated as a table of strings and a two-
dimensional character array can be used to store the entire list. The table
can be conveniently stored in a character array city by using the following
declaration:

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char colours[5][10]={“Blue”,”Pink”,”Yellow”,”Orange”,”Red”};
int i;
clrscr();
printf(“The colours are \n”);
for(i=0;i<5;i++)
printf(\n\t%s”,colours[i]);
}
Output:
The colours are
Blue
Pink
Yellow
Orange
Red
3.2 USER DEFINED FUNCTION
3.2.1 Introduction
C functions can be classified into two categories, namely, library
functions and user-defined functions. Main is an example of user-defined

85
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
functions. printf and scanf belong to the category of library functions. We
have also used other library functions such as sqrt, cos, strcat, etc.
The main distinction between these two categories is that library
functions are not required to be written by us whereas a user-defined
function has to be developed by the user at the time of writing a program.
3.2.2 Need for User-Defined Functions
Every program must have a main function to indicate where the
program has to begin its execution. The program may become too large and
complex and as a result the task of debugging, testing and maintaining
becomes difficult.
If a program is divided into functional parts, then each part may be
independently coded and later combined into a single unit. These
independently coded programs are called subprograms that are much easier
to understand, debug and test. In C, such programs are referred to as
‘functions’.
Advantages:
 It facilitates top-down modular programming.

Main Program

Function A Function B Function C

B1 B2

Top-down modular programming using functions


 In this programming style, the high level logic of the overall problem is
solved first.
 The length of a source program can be reduced by using functions at
appropriate places.

86
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 It is easy to locate and isolate a faulty function for further
investigations.
 A function may be used by many other programs.
3.2.3 A Multi-Function Program
A function is a self-contained block of code that performs a particular
task. Once a function has been designed and packed, it can be treated as a
‘black box’ that takes some data from the main program and returns a value.

A function can be called more than once. Every C program can be


designed using a collection of these black boxes known as functions. The
functions can be placed in any order. A called function can be placed either
before or after the calling function. A multi function program is a program,
which contains more than one function in it.

87
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

main()

---------------

---------------

function1();

---------------

---------------

function1();

---------------

function2();

---------------

function3()

function3();

---------------

Flow of control in a multi-function program


3.2.4 Elements of user-defined functions
The elements of user-defined functions are:

 Function definition
 Function call
 Function declaration
3.2.5 Definition of functions
A function definition, also known as function implementation shall
include the following elements:

 function name

88
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 function type
 list of parameters
 local variable declarations
 function statements and
 a return statement.
All the six elements are grouped into two parts, namely,

 function header(first three elements) and


 function body(second three elements)
The general format is:

function_type function_name(parameter list)


{
local variable declarations;
executable statement1;
executable statement2;
-----------------
return(expression);
} Function End

where, type-specifier – data type of return value of the fuction.


function_name – name of the function
argument-list-declaration – variable declarations separated by commas
expression – valid arithmetic expression.
The rules of writing function_name are:
 It must begin with a letter
 It may be in uppercase or in lowercase.
 It should not be a keyword, library
Function Header:-

89
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The function header consists of three parts: the function type, the
function name and the formal parameter list. A semicolon is not used at the
end of the function header.
Name and Type:-
The function type specifies the type of value that the function is
expected to return to the program calling the function. If the return type is
not explicitly specified, C will assume that it is an integer type. If the function
is not returning anything, then we need to specify the return type as void.
The function name is any valid C identifier and therefore must follow
the same rules of formation as other variable names in C.
Formal Parameter List:-
The parameter list declares the variables that will receive the data sent
by the calling program. They serve as input data to the function to carry out
the specified task. Since they represent actual input values, they are often
referred to as formal parameters.
The parameters are also known a arguments.
Function Body:-
The function body contains the declarations and statements necessary
for performing the required task.
The body enclosed in races, contains three parts, in the order given
below:
 Local declarations that specify the variable needed by the
function.
 Function statements that perform of the task of the function.
 A return statement that returns the value evaluated by the
function.
If a function does not return any value (like the printline function) we
can omit the return statement.
Example:
float mul(float x, float y)
90
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
{
float result;
result=x*y;
return(result);
}
3.2.6 Return Values And Their Types
 A function may or may not sent back any value to the calling function.
If I does, it is done through the return statement.
 The return statement can take one of the following forms:
return;
or
return (expression);
 The first, the ‘plan’ return does not return any value; it acts much as
the closing brace of the function.
 An example of the use of simple return is as follows:
If (error)
return;
The second form of return with an expression returns the value of the
expression. For example, the function

91
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
int mul (int x, int y)
{
int p;
P=x*y;
return(p);
}
return the value of p which is the product of the values of x and y. The last
two statements can be combined into one statement as follows:

Return (x*y);

3.2.7 Function Calls


A function can be called by simply using the function name followed by
a list of actual parameters (or arguments), if any enclosed in parentheses.

Example;

main()
{
int y;
y = mul (10,5); /*function call */
printf(“%d/n”,y);
}
When the compiler encounters a function call, the control is transferred
to the function mul(). This function is then executed line by line as described
and a value is returned when a return statement is encountered. This value
is assigned to y.

There are many different ways to call a function. Some of the ways are
as below:

mul(10,5)
mul(m,5)
mul(10,n)
92
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
mul(m,n)
mul(m+5,10)
mul(10,mul(m,n))
mul(expression1,expression2)
3.2.8 Function Declaration
A function declaration consists of four parts. They are

 Function type(return type)


 Function name
 Parameter list
 Terminating semicolon
They are coded in the following format

Function-type function-name(parameter list);

A prototype declaration may be placed in two places in a program.

 Above all the functions(including main).


 Inside a function definition.
When we place the declaration above all the functions, the prototype is
referred as a global prototype. When we place it in a function definition, the
prototype is called a local prototype.

The place of declaration of a function defines a region in a program in


which the function may be used by other functions. This region is known as
the scope of the function.

3.2.9 All Category Of Functions


A function, depending on whether arguments are present or not and
whether a value is returned or not, may belong to one of the following
categories:

93
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Category 1: Functions with no arguments and no return values.
Category 2: Functions with arguments and no return values.
Category 3: Functions with arguments and one return value.
Category 4: Functions with no arguments but return a value.
Category 5: Functions that return multiple values.
Category 1: No arguments and No return values
When a function has no arguments, it does not receive any data from
the calling function. Similarly, when it does not return a value, the calling
function does not receive any data from the called function.
There is no data transfer between the calling function and the called
function. This is shown below:
No input
function1() function2()

{ {

-------------- No output --------------

-------------- --------------

function2() --------------
The dotted lines indicate that there is only a transfer of control but not data.
-------------- --------------
A function that does not return any value cannot be used in an expression. It
can only be used-------------- --------------
as an independent statement.

} }
Example:
#include <stdio.h>
#include <conio.h>
main()
{
void test1(); /*function declaration*/
clrscr();
test1(); /*function call*/
getch();
94
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
void test1() /*function definition*/
{
printf(“WELCOME TO SOWDESWARI COLLEGE”);
}
Output:
WELCOME TO SOWDESWARI COLLEGE
Category 2 : Arguments but No return values
The function with arguments will receive data from the calling function.
The actual arguments and formal arguments should match in number, data
type and order. The values of actual arguments are assigned to the formal
arguments on a one-to-one basis, starting with the first argument.
When the function call is made, only the copy of the actual arguments
is passed into the called function. So their values cannot be altered by the
function. When a function does not return a value, the calling function does
not receive any data from the called function. The nature of data
communication between the calling function and the called function with
arguments but no return value is shown below:

95
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Values of

function1()
argumentsfunction2()

{ {

-------------- --------------

-------------- No return --------------

function2() Value --------------


One-way data communication
-------------- --------------
Example:
-------------- --------------
#include <stdio.h>
} <conio.h>
#include }

main()
{
void print(int);
clrscr();
print(5);
getch();
}
void print(int a)
{
printf(“\nThe value is : %d”,a);
}
Output:
The value is : 5
Category 3 : Arguments with return values
The function with arguments will receive data from the calling function.
. The values of actual arguments are assigned to the formal arguments on a
one-to-one basis, starting with the first argument.
When the function call is made, only the copy of the actual arguments
is passed into the called function. So their values cannot be altered by the
96
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
function. When a function returns a value, the calling function will receive a
data from the called function.
The nature of data communication between the calling function and
the called function is two-way. It is shown below:
Values of

function1()
argumentsfunction2()

{ {

-------------- --------------
function
-------------- result --------------

Two-way data
function2(a) --------------

-------------- --------------
communication between functions
-------------- return(e)
Example:
}
#include<stdio.h> }

#include <math.h>
main()
{
int square(int);
int a,b;
clrscr();
printf(“\nEnter the numbers\n”);
scanf(“%d”,&a);
b=square(a);
printf(“Square is : %d”,b);
getch();
}
int square(int x)
{
int c;
97
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
c=sqrt(x);
return(c);
}
Output:
Enter the numbers
100
Square is :10
Category 4 : No arguments but returns a value
When a function has no arguments, it does not receive any data from
the calling function. When a function returns a value, the calling function will
receive a data from the called function.
The nature of communication between the calling function and the
called function is one-way. It is shown below:
No

void function1()
arguments int function2()

{ {

-------------- --------------
Return
-------------- value --------------
ans=function2()
--------------
--------------
--------------
-------------- One-way data communication
return(e)
}
}

98
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Example:
#include <stdio.h>
#include <conio.h>
main()
{
int s;
int add();
clrscr();
s=add();
printf(“Sum=%d\n”,s);
getch();
}
int add()
{
int a,b;
printf(“Enter two integers\n”);
scanf(“%d%d”,&a,&b);
return(a+b);
}
Output:
Enter two integers
2
3
Sum=5
Category 5 : Function that return multiple values
Normally a return statement can return only one value. Suppose we
want to get more information from a function, we can use the arguments not
only to receive information from a function but also to send back information
to the calling function. The arguments that are used to “send out”
information are called output parameters.
99
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The mechanism of sending back information through arguments is
achieved using what are known as the address operator (&) and indirection
operator (*).
Example:
#include <stdio.h>
#include <conio.h>
void mathoperation(int a,int b, int *sum, int *diff)
main()
{
int x=20,y=10,s,d;
mathoperation(x,y,&s,&d);
printf(“Sum=%d\n Difference=%d\n”, s,d);
getch();
}
void mathoperation(int a,int b, int *sum, int *diff)
{
*sum=a+b;
*diff=a-b;
}
Output:
Sum=30
Difference=10Rules for Pass by Pointers
 The types of the actual and formal arguments must be same.
 The actual arguments (in the function call) must be the addresses of
variables that are local to the calling function.
 The formal arguments in the function header must be prefixed by the
indirection operator *.
 In the prototype, the arguments must be prefixed by the symbol.

100
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 To access the value of an actual argument in the called function, we
must use the corresponding formal argument prefixed with the
indirection operator *.
3.2.10 Nesting of Functions
C permits nesting of functions freely. The main function can call
function1, which calls funciton2, which calls funciton3,……… and so on.

Example:
#include <stdio.h>
#include <conio.h>
main()
{
void add();
void diff();
add();
{
void add()
{
int a,b,c;
clrscr();
printf(“Enter the values\n”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum=%d”,c);
diff();
}
void diff();
{
int a,b,c;
printf(“Enter the values\n”);
scanf(“%d%d”,&a,&b);
101
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
c=a-b;
printf(“Difference=%d”,c);
add();
getch();
}
Output:
Enter the values
5
4
Sum=9
Enter the values
5
4
Difference=1
Enter the values
7
11
Sum=18
3.2.11 Recursion
When a called function in turn calls another function a process of
‘chaining’ occurs. Recursion is a special case of this process, where a
function calls itself.

102
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Example:
#include <stdio.h>
#include <conio.h>
main()
{
int n;
int fact(int f);
clrscr();
printf(“Enter the n value\n”);
scanf(“%d”,&n);
printf(“The factorial value of %d=%d”,n,fact(n));
getch();
}
int fact(int f)
{
if(f<=0)
return 1;
else
f=f*fact(f-1);
return(f);
}

Output:
Enter the n value
4
The factorial value of 4=24

3.2.12 Passing arrays to functions


(a) One-Dimensional Arrays

103
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
It is possible to pass the values of an array to a function. To pass an
one-dimensional array to a called function, it is sufficient to list the name of
the array, without any subscripts, and the size of the array as arguments.
In C, the name of the array represents the address of its first element.
By passing the array name, we are passing the address of the array to the
called function. The array in the called function now refers to the same array
stored in the memory. Therefore, any changes in the array in the called
function will be reflected in the original array.
Passing addresses of parameters to the functions is referred to as pass
by address.
Example:
#include <stdio.h>
#include <conio.h>
main()
{
float largest(float a[], int n);
float value[4]={2.5,-4.75,1.2,3.67};
clrscr();
printf(“The largest value is = %f\n”,largest(value,4));
getch();
}
float largest(float a[], int n)
{
int i;
float max;
max=a [0];
for(i=1;i<n;i++)
if(max<a[i])
max=a[i];
return(max);
104
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
Output:
The largest value is = 4.000000
Three Rules to Pass an Array to a Function
 The function must be called by passing only the name of the array.
 In the function definition, the formal parameter must be an array type;
the size of the array does not need to be specified.
 The function prototype must show that the argument is an array.
(b) Two-Dimensional Arrays
Like simple arrays, we can also pass multi-dimensional arrays to
functions. The rules for passing two dimensional arrays to functions are:
 The function must be called by passing only the array name.
 In the function definition, we must indicate that the array has two-
dimensions by including two sets of brackets.
 The size of the second dimension must be specified.
 The prototype declaration should be similar to the function header.
Example:
#include <stdio.h>
#include <conio.h>
#define m 3
#define n 4
main()
{
void display(int a[][n]);
int a[m][n]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
clrscr();
display(a);
}
void display(int a[][n])
{
105
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
int i,j;
printf(“Contents of the array\n”);
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
printf(“\t%d”,a[i][j]);
printf(“\n”);
} getch();
}
Output:
Contents of the array
1 2 3 4
5 6 7 8
9 10 11 12
3.2.13 Passing strings to functions
The strings are treated a character arrays in C and therefore the rules
for passing strings to functions are very similar to those for passing arrays to
functions. The rules for passing strings to functions are:

 The string to be passed must be declared as a formal arguments of the


function when it is defined.
 The function prototype must show that the argument is a string.
 A call to the function must have a string array name without subscripts
as its actual argument.

106
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Example:
#include <stdio.h>
#include <conio.h>
main()
{
char t[20];
int n,j;
void left(char t[],int n);
clrscr();
printf(“\n Enter the string : “);
gets(t);
printf(“\nEnter the no. of characters : “);
scanf(“%d”,&n);
left(t,n);
getch();
}
void left(char t[],int n)
{
int i;
printf(“%s”,t);
for(i=0;i<n,i++)
printf(“\n%c”,t[i]);
}
Output:
Enter the string : SOWDESWARI COLLEGE
Enter the no. of characters : 10
SOWDESWARI COLLEGE
S
O
W
107
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
D
E
S
W
A
R
I
a) Pass by Value and Pass by Pointers
The technique used to pass data from one function to another is known
as parameter passing. Parameter passing can be done in two ways:
 Pass by value (also known as call by value).
 Pass by pointers (also known as call by pointers).
In pass by value, values of actual parameters are copied to the variables
in the parameter list of the called function. The called function works on the
copy and not on the original values of the actual parameters. This ensures
that the original data in the calling function cannot be changed accidentally.
In pass by pointers (also known as pass by address), the memory
addresses of the variables rather than the copies of values are sent to the
called function. In this case, the called function directly works on the data in
the calling function and the changed values are available in the calling
function for its use.

108
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
UNIT- IV

4.1 STRUCTURES AND UNIONS


4.1.1 Introduction
 C Supports a constructed data type known as structures, a mechanism
for packing data of different types.
 A structure is a convenient tool for handling a group of logically related
data item.
4.1.2 Defining a Structure
A structure definition creates a format that may be used to declare
structure variables.
Syntax:
The general format for structure definition is:
struct tag_name
{
datatype member1;
datatype member2;
------------ --------------
------------- ---------------
};
In defining a structure you may note the following syntax:
 The template is terminated with a semicolon.
 While the entire definition is considered as a statement each member
is declared independently for its name and type in a separate
statement inside the template.
 The tag name can be used to declare structure variables of its type.

Here is an example structure definition.

Consider a book database consisting of book name, author, number of


pages, and price. Therefore, the structure is defined to hold this information
as follows:

109
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
struct book_ bank
{
char title[10];
char author[15];
int pages;
float price;
}
The keyword struct declares structures to hold the details four data
fields namely title, author, pages and price. These fields area called
structures elements or members. Each member may belong to a different
type of data book_ bank is the name of the structure and also called
structure tag. The tag may be used subsequently to declare variables that
have the tag’s structure.

Array of 20 title
characters
author
Array of 20
page
characters
price
Integer

Float
4.1.3 Declaration of Structure Variable

A structure variable definition is similar to the declaration of variable of


any other data types. It includes the following elements.

 struct keyword is used to declare structure.

 The struct tag name.

 Declaration of Structure reserves no space.

 It is nothing but the “Template / Map / Shape” of the


structure.
110
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 Memory is created, very first time when the variable is
created / Instance is created.

It is also allowed to combine both the template declaration and


variable in one struct.

i. e:

struct book_ bank


{
char title[10];
char author[15];
int pages;
float price;
};
struct book b1, b2, b3;  declares b1, b2, b3 as variables of type
struct book.

Another format:

struct book_ bank


{
char title[10];
char author[15];
int pages;
float price;
} book b1, b2, b3;  declares b1, b2, b3 as variables of type struct
book.

 The use of tag name is optional.


 The structure definition can appear at the beginning of the program file
before any variables or function are defined.
 They may also appear before the main
 In such cases, it is global and can be used by other functions too.

111
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
4.1.4 Accessing Structure Members
The members of a structure can be accessed by the following format,
Syntax:
variable. member
where variable  refers to the name of the structure- type variable;
member  refers to the name of the member within the
structure.
Notice, the period (. ) that separates the variables name from the
member name.
Example:
b1. price
is a variable representing the price of book1 and can rated like any
other ordinary variables.
Here is how we would assign values to the member of book1;
strcpy (b1. title, “BASIC”);
strcpy (b1. author, “Balagurusamy”);
b1. page = 255;
b1. price = 500.00;
we can also use scanf to give the values through the keyboard, such as
scanf (“%s \n”, b1. title);
scanf (“%d \n”,& b1. pages); are valid input statements.
4.1.5 Structure Initialization
 A structure must be declared as static if it is to be initialized
inside a function.
main ( )
{ static struct
{
int weight;
float height;
}

112
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
student= {60, 180, 75};
----------
----------
}
This assign the value 60 to student. weight and 180.75 to student.
height. Another method is to initialize a structure variable outside a function
is shown below,

struct student- record


{
int wt;
float ht;
} stu1= {60, 180.75};
C language does not permit the initialization of individual structure
members with in the template. The initialization must be done only in the
declaration of the actual variables. Compile time initialization of structure
variable must be have the following elements

 The keyword struct.


 The structure tag name
 The name of the variable to be declared.
 The assignment operator = .
 A set of values for the member of the structure variable,
separated by commas and enclosed in braces.
 A terminating semicolon.
[Link] Rule for Initializing Structure
 We cannot initializing individual members inside the structure
template.
 The order of values enclosed in braces must match the order of
members in the structure definition.
 It is permitted to have a partial initialization. We can initialize

113
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
only the first few members and leave the remaining block. The
uninitialized members should be only at the end of the list.
 The uninitialized members will be assigned default values as
follows;
 Zero for integer and floating point numbers.
 ‘\0’ for characters and strings.
4.1.6 Copying and Comparing Structure Variables
Two variables of the same structure type can be copied the same way
as ordinary variables. If person1 and person2 belong to the same structure,
then the following statements are valid.

person1 = person2;

person2 = person1;

However, the statements such as,

person1 = person2;

person1! = person1;

The above statements are not permitted. C does not permit any logical
operations on structure variables. In case, we need to compare them, e may
do so by comparing members individually.

[Link] Program to copy and compare structure variables


#include<stdio. h>
#include<conio. h>
void main( )
{
struct class
{
int number
char name[20];

114
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
sloat marks;
};
struct class student2= {222, “raj”, 67.00};
struct class student3;
int x;
clrscr( );
student3= student2;
x= ((student3. Number==student2. number)&&( student3.
marks==student2.
marks))?1:0
if(x==1)
{
printf(“\n student2 and student3 are same\n\n”);
printf(“%d%s%f\n”, [Link], student3. Name, student3.
marks);
}
else
printf(“\n student2 and student3 are not same\n\n”);
getch();
}

[Link] Operations on Individual Members


The individual members are identified using the member operator, the dot.
Example:
if(student1. Number = = 11)
student1. Marks += 10.00;
float sum = student2. Marks + student2. Marks;
student2. Marks * = 0.5
We can also apply increment and decrement operators to numeric type
members. For example,
115
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
student1. Number++;
++student1. Number;
The precedence of the number operator is higher than all arithmetic
and relational operators and therefore no parantheses are required.
4.1.7 Array of Structures
We use to describe the format of a number of related variables.

Example:

struct class student[100];

Defines an array is called student which contains 100 elements. Each


element is defined to be of the type struct class.

struct marks
{
int m1,
int m2;
int m3;
};
main( )
{
static struct marks student[3] = {{77, 85, 64}, {37, 67,
96}, {88, 48, 77}}
};
This declares the student as an array of 3 elements student[0],
student[1], student[2] and initializes their members as follows:

student[0]. m1= 77;

student[0]. m2= 85;

116
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Program:

#include<stdio.h>
#include<conio.h>
struct emp
{
int empno;
char name[20];
float salary;
};
void main( )
{
struct emp e[10];
int i, n;
float f, *fp;
clrscr( );
fp= & f;
printf(“enter no of employees[1-10]\n”);
scanf(“%d”, &n);
printf(“enter %d employees details\n”);
for(i=0;i<n;i++)
scanf(“%d%s%f”, &e[i].empno, e[i]. name, &e[i]. salary);
printf(“employees details\n”);
for(i=0;i<n;i++)
printf(“%d%s%f”, e[i].empno, e[i]. name, e[i]. salary);
getch( );
}

117
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
4.1.8 Array within Structures
Permits the use of array as structure members. Consider the following
structure declaration

Struct marks
{
int no;
float subject[3];
} student[2];
Here, the member sub contains 3 elements, subject[0], subject[1], and
subject[3]. These elements can be accessed using appropriate subscripts.
For example,

Student[1]. Student[2]; would refer to the marks obtained in the 3


subject by the second student.

4.1.9 Structures Within Structures


Nesting of structures is permitted in C. Let us consider the following
structure,

struct salary
{
char name[20];
char dept[20];
struct
{
int da;
int hra;
int ma;
}
allowance;
}
employee;
118
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The salary structure contains a member named allowance which itself
is a structure with in3 members. The members contained in the inner
structure namely da, hra, ma can be referred to as

 employee. allowance. da;


 employee. allowance. hra;
4.1.10 Structure and Functions
 C supports the passing of structure values as arguments to functions.
There are 3 arguments by which the values of a structure can be
transferred from one function to another.
 The first method is to pass each member of the structure as an actual
argument of the function call.
 The second method involves passing of a copy of the entire structure
to the called function.
 The third approach employs a concept called pointers ie, the address
location of the structure is passed to the called function. This method
is more efficient as compared to the second one.
Syntax:
function- name (structure_ variable_ name);
This called function takes the following form:

data-type fn-name (struct_type st_name)

{ ---------
---------
return (expression);
}
Description
 The called function must be declared for its type, appropriate to the
data type it is expected to return.
 The structure variable used as the actual argument and the
corresponding formal argument in the called function must be of the
119
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
same struct type.
 The return statement is necessary only when the function is returning
some data.
 When a function returns a structure, it must be assigned to a structure
of identical type in the calling function.
 The called function must be declared in the calling function for its type,
if it is placed after the calling function.
4.1.11 Unions
In structures, each member has its own storage location; whereas all the
members of unions use the same location. This implies that, although a
union may contain many members of different typed, it can handle only one
member at a time. Like structures, a union can be declared using the
keyboard union as follows.

union item
{
int m;
float x;
char c;
} code;
This declares a variable code of type union item. The union contains 3
members, each with a data type. However, we can use only one of them at a
time. This is due to fact that only one location is allocated for a union
variable, irrespective of its size.

1000 1001 1002 1003

Fig: storing a storage location by union members

To access the union members, we can use the same syntax that we use for
structure members, i.e,
120
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
code. m;
code. x;
code. c;
All the above are valid member variables. During accessing, we should
make sure that we are accessing the members whose value is currently
stored.

Therefore, a union creates a storage location that can be used by any


one of its members at a time. When a different member is assigned a new
value, the new value supercedes the previous member’s value.

4.1.12 Size of Structures


The actual size of these variables in terms of bytes may change from
machine to machine. We may use unary operator size of.

Format:

sizeof(Struct
x);

Example:

sizeof(y);

4.1.13 Bit Fields


We have been using integer fields of size 16 bits to store data. There
are occasions where data items require much less than 16 bits space.

C permits us to use small bits fields to hold data items and there by to
pack several data items in word of memory. A bit field allows direct
manipulation of string of a string of preselected bits as if it represented an
integral quantity.

121
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
A bit field is a set of adjacent bits whose size can be from 1 to 16 bit in
length. A word can divided into a number of bit fields. The name and size of
bit fields are defined using a structure.

Syntax;
struct tag- name
{
data_type name1: bit-length;
data_type name2: bit-length;
…………
…………
data_type namen: bit-length;
}
Example:
Struct ibsc
{
unsigned roll: 7
unsigned rollname: 10
unsigned strength: 100
} ib;
Points to observe:
The first field always starts with the first bit of the word
4.2 POINTERS
4.1.1 Introduction
A pointer is a variable that contains the address of the values. Pointer
can be used to access and manipulate data stored in memory.
Benefits:
 Pointers are more efficient in handling arrays and data tables.
 Pointers can be used to return multiple values from a function via
function arguments.
 Pointers permits references to functions and passing of functions as
122
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
arguments to other functions.
 Pointers allow C to support dynamic memory management.
 Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists, queues, stack, and trees.
 Pointers reduce length and complexity of programs.
 Pointers increases the execution speed and also reduce the program
execution times
4.1.2 Understanding Pointers
 The computer memory is a sequential collection of storage cells. Each
cell is known as a byte has number called address associated with it.
 The addresses are numbered starting from zero.
 The last address depends on the memory size.
 Whenever we declare a variable a system allocates memory spaces to
hold the value of the variable.
Consider the example:

int quantity = 179;

This statement instructs the system to find a location for the integer
variable quantity and puts the value 179 in that location. We may have
access to the value 179 by using either the variable name or the memory
address. Since memory addresses are assigned to some other variable
that can be stored in memory these variables are known as pointer
variable.

123
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Example:
Variable value address

Quantity  variable Quantity 5000

179
179  value

5000
4.1.3 Accessing the address of variables
 The address of variables memory location can be determined by the
& variable-name;
Where & is a unary operator, called the address operator, which
evaluates the address of its operand.
Example:
p= &quantity;
 Here the address of quantity can be assigned to another variable p;
this new variable is called a pointer to quantity, since it “points” to the
location where quantity is stored.
 Thus, P is referred to as a pointer variable.
 The data item represented by quantity can be accessed by the
expression * p, where * is a unary operator called the indirection
operator, that operates only on a pointer variable.
 Therefore, *p and quantity both are represent the same data item.

124
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Declaring pointer variables:-
When a pointer variable is declared, the variable must be preceded by
an asterisk (*). This identifies the fact that the variable is a pointer.
Syntax;
data-type * pointer variable;
Where pointer variable is the name of the pointer variable & data-type
refer to the data-type of the pointer’s object. Note that an asterisk must
precede pointer variable.
Example:
int *p;
The above declares the variable p as a pointer variable that points to
an int data type. Since the memory location have not been assigned any
values, these locations may contain some unknown values in them and
therefore they point to unknown locations.
Example:
int *p;
p -------------- ?

Contains garbage points to unknown


location
4.1.4 Initializing Of Pointer Variables
The process of assigning the address of a variable to a pointer variable
is known as initialization. It can be made to point to a variable using an
assignment statement such as

int rno;

int *a;

a = &rno;

125
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
which causes a to point to rno. P now contains the address of qty. This
is known as pointer initialization. Before a pointer is initialized, it should not
be used.

4.1.5 Chain Of Pointers


It is possible to make a pointer to point to another pointer, thus
creating a chain of pointers as shown below:
P2 P1
Variable

The pointer variable p2 contains the address of the pointer variable


p1,which points to the location that contains the desired value. This is known
as multiple indirections.
Example:
void main()
{
int x,*p1,**p2;
x=100;
p1 = &x;
p2 = &p1;
printf(“%d”,**p2);
}
4.1.6 Pointer Expressions
Pointer variable can be used in expression. For Example p1 and p2 are
properly declared and initialized pointers.
Example:

y = *p1 **p2; same as(*p1)* (*p2)

sum = sum+*p1;

126
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Z = 5*-*p2/*p1; same as (5*(-(*p2)))/(*p1)

*p2 = *p2+10;

4.1.7. Pointers And Arrays


 When an array is declared, the compiler allocates a base address and
sufficient amount of storage to contain all the elements of the array in
contiguous memory allocations.
 The base address is the location of the first element i.e., index 0 of the
address.
 The compiler also defines the array name as a constant pointer to the
first element.
Suppose we declared an array x as follows:
int x[5]={1,2,3,4,5};
 Suppose the base address of x is 1000 and assuming that each
integer requires 2 bytes then the 5 elements will be stored as follows:
Elements - x[0] x[1] x[2] x[3] x[4]

Value 1 2 3 4 5 
Address  1000 1002 1004 1006 1008
<--Base address
 The name x is defined as a constant pointer pointing to the first
element , x[0] and therefore the value of x is 1000,the location
where x[0] is stored. That is,
X = &x[0] = 1000
 If we declare p as an integer pointer, then we can make the pointer p
to point to the array and x by the following assignment.
p = x;
This is equivalent to p = & x [0];
Now we can access every value of x using p++ to move from
one element to another. It contains the two concepts,

127
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
1. Pointers and one-dimensional arrays
2. Pointers and two-dimensional arrays
Pointers and one-dimensional arrays:
It includes only one subscript (or) one index value
int a[10];

*a = *(a+0)=a[0]
*(a+0)=a[0]
*(a+1)=a[1]
*(a+2)=a[2]
*(a+3)=a[3]
…………………
…………………
*(a+i)=a[i]
In general , (a+i) gives the address of ith element in the array a and
*(a+i) is the element stored in the ith location of the array.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,I;
printf(“Enter no of elements \n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
printf(“The list of Element \n”);
for(i=0;i<n;i++)
printf(“%d”,*(a+1));
getch();
128
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}

Output:
Enter no of Elements
2
Enter 2 elements
10
20
The list of element
10
20
Pointer and two-dimensional arrays
It includes two subscripts (or) two index values
Example: int a[10][10];

(a+0) is the address of first 1-d array *(a+0) is the first 1-d array
(a+1) is the address of second 1-d array *(a+1) is the second 1-d
array
(a+2) is the address of third 1-d array *(a+2) is the third 1-d array
(a+3) is the address of fourth 1-d array *(a+3) is the fourth 1-d array
…………………………………………
…………………………………………
(a+n-1) is the address of first 1-d array *(a+n-1) is the nth 1-d array
In general,a[i][j] can be written as *(*(a+i)+j).
4.1.8 Pointers And Character Strings
129
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 A string is an array of characters terminated with a null character.
 We can use a pointer to access the individual characters in the string.
Initialization and declaration:
Char *cptr = name;
 Declares cptr as a pointer variable and address of name[10] is
assigned to cptr.
 The string is a sequence of characters terminated by a null
character ‘\0’
 The null character marks the end of the string
Example:
char s[20];
char *cp;
cp=s;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20],*cp;
printf(“Enter a string \n”);
scanf(“%s”,str);
cp = str;
printf(“string in str=%s \n”,cp);
cp = “abcd”;
printf(“%s \n”,cp);
getch( );
}
Output:
Enter a string
Program

130
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
String in str= Program
Abcd
4.1.9 Array Of Pointers
We can use an array of pointers to char type to represent the strings.
Example:
char *ptr[10];
ptr[0],ptr[1],ptr[2]………………ptr[9] are all pointers to char type.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char *name[3]={“hi”,”hi1”,”hi2”};
int I;
printf(“The list of three names \n”);
for(i=0;i<3;i++)
printf(“%s \n”,names[i]);
}
Output:
The list of three names
hi
hi1
hi2

131
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
4.1.10 Pointers As Function Arguments
When we pass addresses to a function, the parameters receiving the
addresses should be a pointer. The process of calling the function using
pointers to pass the addresses of variable is known as call by reference.
Example:
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp = *a;
a = *b;
*b = temp;
}
void main()
{
Int a = 10,=20;
Swap (&a,&b);
printf(“%d %d”,a,b);
}
Output:
20
10 (the values are changed)
It includes
 Passing pointers as arguments to function
 Returning a pointer from a function
 Pointer to a function

132
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Passing pointers as arguments to functions:
Syntax:
function-name(type *ptr);
Types:
 Call by value
 Call by reference
Call by value:
The mechanism of calling a function by passing values is called call by
value.
Call by reference:
The mechanism of calling a function by passing pointers is called call
by reference.
4.1.11 Function Returning Pointers
The function returns a pointer to data-type
Syntax:
data- type *function-name (arguments);
Example:
int *sum(int,int);
Program:
#include<stdio.h>
#include<conio.h>
void *sum(int,int);
void main()
{
Int a,b,*s;
clrscr();
printf(“Enter two numbers”);
scanf(“%d %d”,&a,&b);
printf(“a=%d b=%d”,a,b);
s=sum(a,b);
133
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(“sum=%d”,*s);
getch();
}
int *sum(int a,int b)
{
int s;
s=a+b;
return(&s);
}
Output:
Enter two numbers 4 5
a=4 b=5 s=9
4.1.12 Pointers To Functions
A pointer invokes a function before which the pointer has to be
declared appropriately and assigned the address of the function.

Syntax:
data-type (*variable-name) (argument-types);
Example:
int (*fnp)(int,int);
4.1.13 Pointers and Structures
The structure used by pointer otherwise called as variable points to
structure.
Example:
struct stu
{
int number(10);
char name(10);
int mark(4);
} stu1, *s;
Here stu1 is the object of the stu. *s also points to the stu structure.
134
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
stu1  number;
stu1  name;
stu1  mark;
the symbol  is called the arrow operator and is made up of a minus sign
and a greater than sign.
 In structure pointer could also use the notation (*s).number; to access
the member number.
 The parenthesis around *s are necessary therefore the member
operator “.” has a higher precedence than the operator *;
Program:
struct stu
{
int i;
int *ip;
};
void main()
{
struct temp t;
int a=10;
t.i=a;
[Link]=&a;
printf(“Value of a=%d \n ”,t.i);
printf(“Address of a=%u \n ”,[Link]);
getch( );}
Output:
Value of a =1 Address of a =500
UNIT - V
5.1 FILE MANAGEMENT
5.2.1 Introduction

135
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The functions scanf and printf to read and write data. These are console
oriented functions. The main problems of these functions are

 It becomes cumbersome and time consuming to handle large volume


of data through terminals.
 The entire data is lost when either the program is terminated or the
computer is turned off.
So the above problems are solved by file handling.

File: It is a place on the disk where a group of related data is stored.

Basic file operations are

 Naming a file
 Opening a file
 Reading a data from file
 Writing a data to file
 Closing a file
Two ways of performing file operation in C

 Low -level I/O


 High-level I/O(uses UNIX System calls)
Important file handling function in C library are given by the following table

Function Operation
Name

fopen() Create a new file for use (or)

136
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Opens an existing file for use

fclose() Closes a file which has been opened for


use

getc() Reads a character from file

putc() Writes a character to file

fprintf() Write a set of value to a file

fscanf() Reads a set of values from a file

getw() Read an integer from a file

putw() Write an integer to a file

fseek0 Set the position to the desired point in


the file

ftell() Gives the current position in the file

rewind() Set the position to the beginning of the


file

5.2.2 Defining and opening a file


We must specify the following details to the files

 File name
 Data structure
 Purpose

a.)File name

137
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 File name is a string of characters
 It should be a valid name
 File name consists of two parts namely i) Primary name ii) An optional
period with extension
Example for file name is given by

[Link]
Sample.c
b.)Data Structure
 It is defined as file in the library of standard I/O function definitions
 All the files should be declared as type FILE before they are uses
 FILE is defined as data type
General format for declaring and opening file
FILE *fp;
Fp=fopen(“filename”,”mode”)
 Fp-Pointer to the data type FILE
 FILE is a structure that is defined in the I/O library
 File name- Name of the file and it is assigned to fp. The file pointer is
used for communication link.
c.) Purpose

 The mode indicates the purpose of opening the file.


Mod Purpose
e

R Open the file for reading only

W Open the file for writing only

A Open the for appending data to it

r+ The existing file is opened to the beginning

138
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
for

both reading and writing

w+ Same as W except both for reading and


writing file

a+ Same as a except both for reading and


writing

Example
FILE *P1, *P2;
P1 =fopen (“data”,”r”);
P2=fopen (“results”,”w”);
In the above example the file data is opened for reading & the file result is
opened for writing.
When we trying to open a file, one of the following things can happen
 When the mode is writing, a file specified name is created if the file
does not exist. The contents are deleted, if the file already exists.
 When the purpose is appending, the file is opened with current
contents safe. A content with the specified name is created if the file
does not exist
 If the purpose is reading, if exists, then the file is opened with current
contents sage; otherwise an errors occurs
5.2.3 Closing a file
 A file must be closed as soon as all the operations have been
completed.
 It prevents the any accidental misuse of a file
 Closing a file also leads to open the same file in different mode.
 All files are closed automatically whenever the program terminates
Syntax of file closing

fclose(file_pointer) 139
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

Example
// statements above the file declaration
-------------------------
-------------------------
FILE *P1, *P2;
p1 =fopen (“data”,”r”);
p2=fopen (“results”,”w”);
// statement for processing file
--------------------------
--------------------------
Fclose(p1)
Fclose(p2)
---------------------------
5.2.4 Input/ Output Operations on Files
Once a file is opened, reading out of or writing to it is accomplished
using the standard I/O.

[Link] The getc and putc Functions


The simplest file I/O functions are getc and putc. These are analogous
to getchar and putchar the functions and handle one character at a time.
Assume that a file is opened with mode w and file pointer [Link], the
statement
putch(c,fp1);
write the character contained in the character variable c to the file
associated with FILE pointer fp1. Similarly, getc is used to read a character
from a file that has been opened in read mode.
For example, the statement
e=getc(fp2);
would read a character from the file whose file pointer is fp2.

140
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The file pointer moves by one character position for every operation of
getc or putc. The getc will return the input file and display it on the screen.
/* WRITING TO AND READING FROM A FILE */
#include<stdio.h>
main()
{
FILE *f1;
char c;
printf(“Data Input \n”);
f1=fopen(INPUT”,”w”);
while(c=getchar()) !=EOF)
putc(c,f1);
fclose(f1);
fclose(f1);
printf(“\n Data Output\n”);
f1=fopen(“INPUT”,”r”);
while((c=getc(f1)) != EOF)
printf(“c”,c);
fclose(f1);
}
Output:
Data Input
This is a program to test the file handling
Features on this system Z
Data Output
This is a program to test the file handling
Features on this system
The file INPUT is reopened for reading. The program then reads
its content character by character and displays it on the screen.
[Link] The getw and putw Functions
141
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The getw and putw are integer oriented functions. They are similar to
the getc and putc functions and are used to read and write integer values.
These functions would be useful when we deal with only integer data.
General format of the getw and putw function is given by

putw(integer,fp)

getw(fp)

/* Handling of integer Data Files */


#include<stdio.h>
main()
{
FILE *f1,f2,f3;
int number, I;
printf(“ contents of DATA file \n”);
f1=fopen(“DATA”,”W”);
for(i=1;i<=30;i++)
{
scanf(“%d”,&number);
if(number = = -1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while(number=getw(f1)) != EOF)
{

142
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
if (number % 2 = =0)
putw(number,f3);
else
putw(number,f2);
}
fclose(f1);
fclose(f2);
close(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n Contents of ODD file \n”);
while(number =getw(f2)) != EOF)
printf(“%4d”,number);
printf(“\n Contents of EVEN file \n”);
while((number=getw(f3)) !=EOF)
printf(“%4d”,number);
fclose(f2);
fclose(f3);
}
Output:
Contents of DATA file
111 222 333 444 555 666 777 888 999 000 121 232 343 454
565 -1
Contents of ODD file
111 333 555 777 999 121 343 565
Contents of DATA file
222 444 666 888 000 232 454
[Link] The fprintf and fscanf functions
 We have seen functions which can handle only one character or
integer at a time. Most compilers support two other functions, namely
143
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
fprintf and sscanf that can handle a group of mixed data
simultaneously.
 The functions sprintf and fscanf perform I/O operations that are
identical to the familiar printf and scanf functions, except of course
that they work on files.
The general format of printf is

fprintf (fp,”control string”,list);

 where fp is a file pointer associated with a file that has been opened
for writing . The control string contains output specifications for the
items in the list.
fprintf(f1,”%s %d %f”,name,age,7.5);
here, name is an array variable of type char and age is an int variable.
The general format of fscanf is
fscanff (fp,”control string”,list);

 Like scanf,fscanf also returns the number of items that are successfully
read. When the end of file is reached to the specifications contained in
the control string.
Example program
#include<stdio.h>
main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[10],filename[10];
printf(“Input file name “);
scanf(“%s”,filename);
fp=fopen(filename,”W”);
printf(“Input inventory data\n”);
144
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(“Item number price Quantity”);
for(i=1;i<=3;i++)
{
fscanf(stdin,”%s %d %f
%d”,item,&number,&price,&quatity);
fprint(fp,”%s %d %2f %d”,item,number,price,quatity);
}
fclose(fp);
fprint(stdout,”\n”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(i=1;i<=3;i++)
{
fscanf(fp,%s %d %f %d”,item,&number,&price,
&quantity);
value=price * quantiy;
fprintf(stdout,”%-8s %7d %8.2f %11.2f \n”);
value=price * quantity;
fprintf(stdout,”% -8s %td %8.2 %8d %11.2f”,
item,number,price,quantity,value);
}
fclose(fp);
}

145
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Output:
Input file name
INVENTORRY
Input inventory data
Item name number price quantity
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104

Item name number price quantity


AAA-1 111 17.50 115 2012.50
BBB-2 125 36.00 75 2700.00
C-3 247 31.75 104 3302.00
5.2.5 Error handling during I/O Operations
It is possible that an error may occur during I/O operation on a file. The
error situations include
 Trying to read beyond the end-of-file mark
 Device overflow
 Trying to use a file that has not been opened
 Trying to perform an operation on a file , when the file is opened for
another type of operation
 Opening a file with an invalid file name
 Attempting to write a write-protected file
The two important library function related to Error handling
during I/O operation is given by
 feof
 ferror

Function Use
name
146
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
feof It can be used to test for an end of file
condition
ferror It reports the status of the file
a) feof Function
 It can be used to test for an end of file condition
 It takes FILE pointer as argument and returns a non-zero integer
value if all of the data from the specified file has been read, and
returns non-zero otherwise.
 Example
If(feof(fp))

Printf(“End of data”);

 The above statement display the message “End of data”, on


reaching the end of the file condition.

Example program - EOF using files handling

#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c ;
char filename[40] ;
printf(“Enter file to be displayed: “);
gets( filename ) ;
fp = fopen( filename, “r”);
c = getc( fp ) ;
while ( c != EOF )
{
putchar(c);
c = getc ( fp );
}
147
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
fclose( fp );
}
In this program, we pass the name of the file to be opened which is stored in
the array called filename, to the fopen function. It reads the character from the file
and prints the characters until end of the file.

b.) ferror() function

 The function reports the status of the file indicated.


 It takes FILE pointer as its argument and return non-zero integer if an error
has been detected during processing. It returns non-zero otherwise.
If (ferror(fp))

printf(“An error has occured”);

5.2.6 Random access files


It is used to access only particular part of a file and not in reading
with other parts. This can be achieved by the following functions.
 ftell()
 rewind()
 fseek()
a) ftell function()
 It takes a file pointer as input and returns a number of bytes long, that
corresponds to the current position.
 The function is useful in saving the current position of the file.
Syntax of ftell() function is

n=ftell(fp)

n-indicates the relative offset of the current position.


b.)rewind() function
 It takes a file pointer and reset the position to the start of the file.
 The first byte in the file is numbered as 0, second as 1 and so on

148
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 This is useful in reading a file more than once, without having to close
and open the file
 A file is opened for reading or writing, a rewind is done implicitly
Example
rewind(fp);
c.) fseek() function
 It is used to move the file position to a desired location with in the file
 The syntax of fseek() is given by

fseek(file_ptr, offset, position)

 File ptr it is a pointer to the file concerned


 OffsetIt is a number or variable of type long. It specifies the number
of positions to be moved from the location specified by the position.
 The offset may be positive or negative. Positive means moves forwards
and negative means move backwards.
 PositionIt is an integer number must take the value given below
 When the operation sis successful, fseek returns a zero
 If we attempt to move the file pointer beyond the file boundaries, an
error occurs and fseek returns -1.

Offset Meaning
value
0 Beginning of the
file
1 Current position
2 End of the file

149
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The following example illustrate the operations of the fseek function
Statement Meaning
fseek(fp,0L, Go to Beginning
0)
fseek(fp,0L, Stay at the current position
1)
fseek(fp,0L, Go to the end of file, past the last character of
2) the file
fseek(fp,m, Move to (m+1) th byte in the file
0)
fseek(fp,m, Go forwards m bytes
1)
fseek(fp,- Go backward by m bytes from the current
m,1) position
fseek(fp,- Go backward by m bytes from the end
m,2)

Example program:-
Consider the file consists of the following contents with the name RANDOM
Position  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
21 22 23
CharacterA B C D E F G H I J K L M N O P Q R S T U
V W
Position 24 25 26
Character X Y Z
The following operations are performed by the below program
We read the file twice. First we read the contents every fifth position
and print its value along with its position on the screen. The second time, we
read the contents of the file from the end and print the same on the screen.

150
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
#include<stdio.h>
main()
{
FILE * fp;
long n;
char c;
fp =fopen(“RANDOM”,”w”);
while((c=getchar()!=EOF)
putc(c,fp);
printf(“Number of characters entered=%ld”,ftell(fp));
fclose(fp);
fp=fopen(“RANDOM”,”R”);
n=0L;
while(feof(fp)==0)
{
fseek(fp,n,0);
printf(“Position of %c is %ld”,getc(fp),ftell(fp));
n=n+5L;
}
putchar(‘ln’);
fseek(fp,-1L,2);
do
{
putchar(getc(fp));
}
while(!fseek(fp,-2L,1));
fclose(fp);
}

The output of the above program is given by


151
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
ABCDEFGHIJKLMNOPQRSTUWXYZ
Number of characters entered=26
Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
ZYXWVUTSRQPONMLKJIHGFEDCBA
5.2.7 Command line arguments
 It is a parameter supplied to a program when the program is invoked
 Accessing the command line arguments is a very useful facility.
 To access these arguments from within a C program, you pass parameters
to the function main().
The declaration of main looks like this:

int main (int argc, char *argv[]) int main (argc, argv)

{ int argc;

//statements char *argv[];


(or)
-------------- {

-------------- //statements

} --------------

--------------

}
This declaration states that
 main returns an integer value
 argc is an argument counter. It counts is the number of command line
arguments including the command itself i.e argc must be at least 1

152
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
 argv is an argument vector. It is an array of the command line arguments.
The size of this array will be equal to the value of argc.
The declaration of argv means that it is an array of pointers to strings . By the
normal rules about arguments whose type is array, what actually gets passed to
main is the address of the first element of the array.
int main (int argc, char **argv)
When the program starts, the following conditions hold true:
 argc is greater than 0.
 argv[argc] is a null pointer.
 argv[0], argv[1], ..., argv[argc-1] are pointers to strings with implementation
defined meanings.
 argv[0] is a string which contains the program’s name, or is an empty string
if the name is not available. Remaining members of argv are the program’s
arguments.
Example: print_args echoes its arguments to the standard output
/* Command_line_args.c */

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i = 0 ;
int num_args ;
num_args = argc ;
while( num_args > 0)
{
printf(“%s\n“, argv[i]);
i++ ;
num_args--;
}
153
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
If the name of this program is command_line_args, an output of its execution is as
follows:
C:\tc\bin> Command_line_arsgs salem sowdewswari college sfcw
Command_line_arsgs
salem
sowdewswari
college
sfcw
From the above program, it assign the following values to the arguments
argc=5
argv[0]=command_line_args
argv[1]=salem
argv[2]=sowdeswari
argv[3]=college
argv[4]=sfcw

154
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
MODEL QUESTION PAPER 1
(For the Candidates admitted from 2017-2018 onwards)
[Link](EC)., Degree Examinations
Third Semester
PROGRAMMING IN C

Time: 3 Hrs Maximum: 75


Marks
SECTION – A (10 x 2 = 20 Marks)
Answer all the questions
1. What is Tokens?
2. Define: Keywords and Identifiers.
3. Write a syntax of enum Data type.
4. write a syntax of while loop.
5. What is function?
6. Explain recursion?
7. What is pointer?
8. Difference between union and structure.
9. Explain any two file handling function?
10. List any three file mode in C?

SECTION – B (5 x 5 = 25 Marks)
Answer all the questions
11.a) Explain in brief structure of C programming?
(Or)
b) Differentiate between relational and logical operators used in C?
12.a) Explain syntax and use of Do-While statement
(Or)
b) Explain one dimensional array with an example

155
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
13.a) Explain any 4 string functions with suitable example?
(Or)
b) What is the difference between call by value and call by
reference
14.a) What is structure? Explain with suitable example
(Or)
b) Explain pointer to structure in detail

15.a) Explain about Input/output operation on files.


(Or)
b) Explain in detail about EOF and BOF.

SECTION – C (3 x 10 = 30 Marks)
Answer any Three out of Five questions
16. Explain in brief about Managing input and output operations.
17. Explain in detail about Control statements.
18. Write notes for String handling functions.
19. Explain in brief Pointers with Examples.
20. Explain in detail about Error handling during I/O operations

156
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
MODEL QUESTION PAPER 2
(For the Candidates admitted from 2017-2018 onwards)
[Link](EC)., Degree Examinations
Third Semester
PROGRAMMING IN C
Time: 3 Hrs Maximum: 75
Marks

SECTION – A (10 x 2 = 20 Marks)


Answer all the questions
1. Define constants.
2. What is known as type conversion?
3. Explain about if-else statement.
4. Define array.
5. What is character array
6. Define recursion.
7. Define structure.
8. Define bit fields with syntax.
9. Explain about file management.
10. Define preprocessor.

SECTION – B (5 x 5 = 25 Marks)
Answer all the questions
11. (a) Explain about C tokens.
(Or)
(b) Explain about declaration of storage class with example.
12. (a) Explain about if and if else statement.
(Or)
(b) Write short notes on declaration of array.

157
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
13. (a) Write short notes Character arrays and strings.
(Or)
(b) Explain about function call.
14. (a) Write a short note on pointers and arrays.
(Or)
(b) Explain about array of structures.
15. (a) Explain about error handling.
(Or)
(b) Write short notes on macros substitution.

SECTION – C (3 x 10 = 30 Marks)
Answer any Three out of Five questions
16. Explain about the different types of operators.
17. Explain about different types of array with example program.
18. Explain in detail about nesting of functions with example
program.
19. Explain in detail about the pointers.
20. Explain about the file management with example program.

158
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
MODEL QUESTION PAPER 3
(For the Candidates admitted from 2017-2018 onwards)
[Link](EC)., Degree Examinations
Third Semester
PROGRAMMING IN C
Time: 3 Hrs Maximum: 75
Marks

SECTION – A (10 x 2 = 20 Marks)


Answer all the questions
1. Define constants.
2. Define: Keywords and Identifiers.
3. Explain about if-else statement.
4. Write a syntax of while loop.
5. What is character array
6. What is function?
7. Define structure.
8. Define bit fields with syntax .
9. Explain any two file handling function?
10. Define preprocessor.
SECTION – B (5 x 5 = 25 Marks)
Answer all the questions
11. (a) Differentiate between relational and logical operators used in
C?

(Or)
(b) Explain about declaration of storage class with example.
12. (a) Explain about if and if else statement.
(Or)
(b) Explain syntax and use of Do-While statement

159
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
13. (a) Explain any 4 string functions with suitable example?
(Or)
(b) Explain about function call.
14. (a) Write a short note on pointers and arrays.
(Or)
(b) Explain pointer to structure in detail
15. (a) Explain about error handling.
(Or)
(b) Explain about Input/ Output operation on files.

SECTION – C (3 x 10 = 30 Marks)
Answer any Three out of Five questions
16. Explain about the different types of operators.
17. Explain in detail about Control statements
18. Explain in detail about nesting of functions with example
program.
19. Explain in brief Pointers with Examples.
20. Explain about the file management with example program.

160
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________

SALEM SOWDESWARI COLLEGE (SFCW), SALEM-10


DEPARTMENT OF COMPUTER-SCIENCE, CLASS: II [Link](EC).,
OBJECTIVE TEST
1. Literal means ------------
a) a String b) a String Constant c) a character d) a
Alphabetic
2. ‘C’ is often called a ------
a) Object oriented language b) High level language
c) Assembly language d) Machine level language
3. The loop in which the statements within the loop are executed at least
once is
called
a) do- while b)while c)for d)goto
4. Which bitwise operator is suitable for turning on a particular bit in a
number?
a) && operator b)& operator c) || operator d)| operator
5. By default a real number is treated as a
a) Float b) Double c) Long double d) Far double
6. Is the following statement a declaration or definition? extern int i;
a) Declaration b)Definition c) Function d)
Error
7. How will you free the allocated memory?
a) Remove (var_name) b)free(var-name)
c) delete(var-name) d)dalloc(var-name)
8. What is the similarity between a structure, union and enumeration?
a) all of them let define new values b) all of them let define new
data types
c) all of them let define new pointers d) all of them let define new
structure

161
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
9. In which stage the following code #include<stdio.h> gets replaced by the
contents
of the file stdio.h?
a) During editing b) During Linking
c) During Execution d)During reprocessing
10. To print out a and b given below, which of the following printf()
statement will
you use?
#include<stdio.h>
float a=3.14;
double b=3.14;
a) printf(“%f%lf”, a,b) b) printf(“%Lf%lf”, a,b)
c) printf(“%Lf%Lf”, a,b) d) printf(“%f%Lf”, a,b)

162

You might also like