II BSC EC - III SEM - Programming in C
II BSC EC - III SEM - Programming in C
Prepared By
SALEM – 10
1.2.2 C Tokens......................................................................................................................4
1.2.4 Constants....................................................................................................................5
1.2.5 Variables.....................................................................................................................7
UNIT – II..........................................................................................................................................41
2.2.2 Do Statement.........................................................................................................56
2.3 ARRAYS..............................................................................................................................58
UNIT - III.........................................................................................................................................68
3.1.1 Introduction.............................................................................................................68
3.2.1 Introduction.............................................................................................................83
3.2.11 Recursion...............................................................................................................99
UNIT- IV.........................................................................................................................................106
4.1.1 Introduction...........................................................................................................106
4.1.11 Unions....................................................................................................................117
4.2 POINTERS........................................................................................................................119
4.1.1 Introduction...........................................................................................................119
4.1.2 Understanding Pointers.................................................................................120
UNIT - V.........................................................................................................................................133
5.2.1 Introduction...........................................................................................................133
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
REFERENCE BOOKS
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.
1
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
DOCUMENTATION SECTION
LINK SECTION
DEFINITION SECTION
Subprogram section
Function1
Function2
----
----
Function
(User-defined functions)
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
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
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.
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:-
Data type
keyword
Character char
Unsigned character
unsigned char
Integer int
Double precision
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).
Integral type
Integer
Character
9
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Data type Range of values
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
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:
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:-
for example:
int *p;
p=&quantity;
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:
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.
units b1,b2;
marks f1[10],f2[10];
enum:-
Another user defined data type is enumerated data type. It is
defined as follows:
14
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Storage Meaning
e
Variable_name = constant
constant
bat = 78.84;
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.
16
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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
18
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
It could be used to tell explicitly the compiler that a variable value may
be changed at any time by external sources.
19
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
i. Binary operators
Numeric calculations between two constant values
+ 2+2=4
- 5-3=2
/ 10/2=5
% 11%3=2
* 2*3=6
Operat Description
or
- Minus
++ Increment
-- Decrement
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
X=6.0/7.0=0.8571
Y=1.0/3.0=0.3333
Z=-2.0/3.0=-0.666
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
22
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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;
< Less than operator a < b; True if a less than b else False
c. Logical Operators:
Operat Symb
Example
or ol
24
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
exp2
exp1 ||
OR ||
exp2
NOT ! ! exp1
Examples
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
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
___________________________________________________________________________
-
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
Example
int a,b,c;
Expression Result
Sizeof(char) 1
Sizeof(int) 2
Sizeof(float) 4
30
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Sizeof(double) 8
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
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
___________________________________________________________________________
If ( FALSE &&TRUE)
Function Meaning
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:
fmod(x,
Remainder of x/y
y)
Log(109
Base 10 log of x,x>0
x)
}
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
scanf(“%d %d %d”,&a,&b)
38
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
c. Inputting real numbers
scanf(“%f%f%f”,&x,&y,&z);
%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
%wc
Code Meaning
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.
Simple if statement
If…..else statement
Nested if..else statement
Else…..if ladder
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
?
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.
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;
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.
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;
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
switch (expression)
case value-1:
block-1;
break;
case value-2:
block-2;
……..
break;
default:
default-block;
break;
statement-x;
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;
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.
55
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Entry Entry
True
Test
Body of the condit
ion
loop
True False
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)
Syntax:
for(initialization; test-condition; increment)
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
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.
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];
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];
‘A’
‘‘
‘B’
62
‘C’
‘A’
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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
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’.
70
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
char string_name[size];
char city[10];
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
is permitted.
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();
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
B1 B2
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.
87
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
main()
---------------
---------------
function1();
---------------
---------------
function1();
---------------
function2();
---------------
function3()
function3();
---------------
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,
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);
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
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()
{ {
-------------- --------------
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()
{ {
-------------- --------------
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
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:
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
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
i. e:
Another format:
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,
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;
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.
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();
}
Example:
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:
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,
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
{ ---------
---------
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.
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.
Format:
sizeof(Struct
x);
Example:
sizeof(y);
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:
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
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 -------------- ?
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.
sum = sum+*p1;
126
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Z = 5*-*p2/*p1; same as (5*(-(*p2)))/(*p1)
*p2 = *p2+10;
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
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
Function Operation
Name
136
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Opens an existing file for use
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
138
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
for
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.
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)
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
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
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”);
#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.
n=ftell(fp)
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
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
CharacterA 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);
}
int main (int argc, char *argv[]) int main (argc, argv)
{ int argc;
-------------- //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
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
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 – 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
(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
___________________________________________________________________________
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