II BSC EC_IIISEM_ Programming in c
II BSC EC_IIISEM_ Programming in c
Prepared By
SALEM – 10
UNIT - I........................................................................................................................................... 1
1.2.2 C Tokens......................................................................................................................... 4
1.2.5 Variables......................................................................................................................... 7
UNIT – II....................................................................................................................................... 41
2.3 ARRAYS.............................................................................................................................. 58
UNIT - III...................................................................................................................................... 68
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. Herbert Schildt, “C: The complete Reference”, 4 Edition, McGraw Hill, 2003. st
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)
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details which the programmer would like to use
later. The link section provides instructions to the compiler to link functions from the
system library. The definition section defines all symbolic constants.
2
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Global section which is outside of all functions used to declare variables used in
more than one function.
Every C program must have main() function section. The section contains two
parts namely declaration part and executable part. The declaration part declares all the
variables used in the executable part. There should be one statement in the executable
part.
The two parts must appear between opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing brace of
the main function section is the logical end of the program. All statements in the
declaration and executable parts end with a semicolon.
The subprogram section contains all the user-defined functions that are called in
the main function. All section except the main function section may be absent when
they are not required.
1.2 CONSTANTS, VARIABLES AND DATA TYPES
1.2.1 Character Set
The characters can be used to form words, numbers and expressions. The
character set in C are:
letters A – Z (Uppercase) , a – z (Lowercase)
Digits 0-9
Special characters ( , comma ; semicolon etc. )
White spaces,
Blank space , horizontal tab, carriage return, new line, form feed.
3
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Trigraph Characters:-
Each trigraph sequence consists of three characters i.e, two question marks
followed by another character.
??= # number sign ??( left bracket [ ??) right bracket[
??< { left brace ??> } right brace ??! vertical bar
??/ \ back slash ??‟ ^ caret ??_ ~ tilde
1.2.2 C Tokens
The smallest individual units are known as tokens. C has six types of
tokens as shown in figure:
C TOKENS
STRINGS
KEYWORDS OPERATORS
CONSTANTS IDENTIFIERS
SPECIAL SYMBOLS
Special symbols [ ] {}
Keywords - float, while
Constants - 15.0, 100
Identifiers - main, amount
Strings - “ABC”, “YEAR”
Operators - +, - , *
4
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
1.2.3 Keywords and Identifiers
All keywords have fixed meanings and these meanings cannot be changed.
All keywords must be written in lower case.
Ex: auto, int, float, for, if , struct, do, char, long
Identifiers:-
Identifiers refer to the name of variables, functions and arrays. They are user
defined names.
Rules for Identifiers:-
It consists of sequence of letters, digits with a letter as a first character.
Both uppercase and lower case letters are permitted, underscore is also
permitted.
Only first 31 characters are significant.
Cannot use a keyword.
Must not contain white space.
1.2.4 Constants
It refers to fixed values that do not change during the execution of a program. C
supports several types of constants as shown in fig:
CONSTANTS
NUMERIC CHARACTER
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
6
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Mantissa e exponent
1.2.5 Variables
Variable is a data name used to store a data value. It may take different
values at different times during execution.
Rules used to denote the variables:-
It must begin with a letter.
ANSI recognizes a length of 31 characters.
The length should not be more than 8 characters.
Uppercase and lowercase are significant.
Variables should not be a keyword. White space is not allowed.
Ex: value t_raise > valid
123 % 25th > invalid
7
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Declaration of variables:-
It tells the compiler what the variable name is. It specifies what type of data
the variable will hold. The declaration of variable must be done before they are
used in the program.
Primary type declaration:-
A variable can be used to store a value of any data type.
Data type v1, v2, v3……vn;
v1, v2, v3…….vn are the names of variables. Variables are separated by
commas.
All declaration statement must end with a semicolon.
Ex: int c1;
double ratio;
int no, total;
Data types used in declaration is:
Character 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
8 -128 - 128
char
16 0 - 65535
unsigned int
32 -32768 to 32767
long int
32 -2147,483,648 - 2,147,483,647
float
10
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
b) Floating Point Type
Floating point type (or real) number is stored in 32 bits with 6 digits of precision.
Floating point numbers are defined in C by the keyword float. A double data type
number uses 64 bits giving a precision of 14 digits. To extend the precision we may use
long double which uses 80 bit.
float
double
long double
c) Void Type
The void type has no values. This is usually used to specify the type of functions
when they are not return any values.
d) Character Type:
A single character can be defined as a char type data. Characters are usually
stored in 8 bits. The qualifier signed or unsigned may be applied to char. While
unsigned chars have values between 0 and 255. Signed chars have values from -128 to
127.
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:
13
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
1.2.6 Declaration of Storage Class
Storage class provides information about the location and visibility. The storage
class decides the portion of the program with in which the variables are recognized.
/*Example of storage classes*/
int m;
main ()
{
int i;
float bal;
……
function1 ();
}
function1 ()
{
int i;
float sum;
}
The variable m which has been declared before the main is called global variable.
It can be used in all the functions in the program. A global variable is known as external
variable.
The variables i, sum are called local variable because they are declared inside a
function. Local variables are visible and meaningful only inside the functions. They are
not known to other functions.
14
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Storage Meaning
e Variable_name = constant
constant
bat = 78.84;
i=0, j=10;
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;
15
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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
___________________________________________________________________________
Ex:
# define STRENGTH 100
# define PASS MARK 50
#define MAY 200
#define PI 3.14159
Symbolic name are sometimes called constant identifier.
I .Rules
Symbolic names have the same form as variable name (written in capital)
No blank space between the bound sign „#‟ and the word define is permitted.
„#‟ must be the first character in line.
A blank space is required between # define and symbolic name and between the
symbolic name and constant.
#define statement is must
Symbolic names are NOT declared for data types its data type depends on type
of constant.
#define statements may appear anywhere in the program but before it is
referenced in the program.
17
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.
18
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
Unary operators are increment operator (++), decrement operator(--) and minus(-)
Operator Description
- Minus
++ Increment
-- Decrement
19
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);
}
20
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
The arithmetic operators are used for performing basic arithmetic operations on
numerals and characters. The following table lists arithmetic operator
21
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.
22
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
< Less than operator a < b; True if a less than b else False
> Greater than operator a > b; True if a greater than b else False
c. Logical Operators:
OR || exp1 || exp2
NOT ! ! exp1
23
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Operators, which are used to combine two or more relational expressions, are
called as logical operators. These operators are used to test more than one condition at a
time. The table shows the various logical operators and their meaning:
d. Assignment Operators
Assignment operator is the most common operator almost used with all
programming languages. It is represented by “=” symbol in C which is used to assign a
value to a variable lying to the left side of the assignment operator.
But if the value already exists in that variable then it will be overwritten by the
assignment operator(=)
Syntax: <variable> = <expression>;
Example:
X = y = z = 2;
X = (y + z);
e. Increment and decrement operators
C allows 2 very useful operators not generally found in other languages. These
are the increment and decrement operators: ++ and -- The operator ++ adds 1 to the
operand, while – subtracts 1. Both are unary operators and take the following form:
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
24
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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
The “?: operator evaluates an expression which may also be an operand and
returns operand1 if the expression is true; otherwise returns operand2, if the expression
is false. We can understand this thing with the help of a diagram shown as:
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 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 1100.The following table lists bitwise operators.
26
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
27
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
28
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
29
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Step 2= 5+6-1
Step 3= 10
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
30
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,
31
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
We get finally as;
If ( FALSE &&TRUE)
Function Meaning
cos(x) Cosine of x
sin(x) Sine of x
tan(x) Tangent of x
32
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Other function:
Variable-name = getchar();
33
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
When this statement is encountered, the computer waits unit a key is pressed and
then assigns this character as a value to getchar functions
Ex: char name;
name= getchar();
Example:
#include<stdio.h>
main()
{
char answer;
printf(“would you like my name ?\n”);
printf(“type y for yes and n for no:”);
answer=getchar();
if(answer= =‟y‟ || answer = =‟y‟)
printf(“\n My name is Busy BEE \n”);
else
}
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
34
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
35
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Enter an alphabet
q
q
scanf(“%d %d %d”,&a,&b)
36
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
37
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
%g read a floating point value
%h read a short integer
%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
38
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
39
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
40
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;
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;
42
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-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);
43
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;
45
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;
This construction is known as the else..if ladder. The conditions are evaluated from
the top downwards. As soon as a true condition is found, the statement associated with
it is executed and the control is transferred to the statement-x. When all the n conditions
become false, then the final else containing the default –statement will be executed.
46
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
47
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.1.5 The switch statement
C has a built-in-multi way decision statement known as a switch. The switch
statement tests the value of a given variable against a list of case values and when a
match is found, a block of statement associated with that case is executed. The general
form of the switch statement is as shown below:
switch (expression)
case value-1:
block-1;
break;
case value-2:
block-2;
…….. break;
………
default:
default-block;
break;
statement-x;
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;
default:
printff(“\n error”)
break;
49
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
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 conditional expression. Otherwise,
expression2 is evaluated and its value is returned. for example
if(x>0)
flag = 0;
else
flag = 1;
50
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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 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()
51
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
{
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
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.
52
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Exit-controlled Loop:-
In this loop, the test is performed at end of the loop and therefore the body is
executed Unconditionally for the first time. Another name for exit controlled loop is
post-test loop.
A looping process includes the following four steps:
Setting and initialization of a condition variable.
Execution of the statements in the loop.
Test for a specified values of the condition variable for execution of the
loop.
53
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Entry Entry
Body of the
Test False
condition
loop
True
Test
Body of the conditi
on
loop
True False
54
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();
}
55
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.2.2 Do Statement
Syntax:
Do
Statements;
While(condition)
56
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(“the no of lines entered are:%d\n”,count);
Syntax:
for(initialization; test-condition; increment)
57
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
2.2.4 Jumps In Loops
Break statements(Jumping out of a loop):
The break is used inside a loop or conditional statement.
It causes the remainder of the statement to be skipped and execution to proceed
to the next statement.
With a loop, this means that no further iterations are executed.
Skipping a part of a loop:-
The continue is used inside a loop, it causes the remainder of the current iteration
to be skipped and the next iteration to be started.
Difference between break statements and continue statements.
Break Statement Continue Statement
It causes premature exit of the loop It causes skipping of the statements following
enclosing it. it in the body of the loop.
The control is transferred to the The control is transferred back to the loop.
statement following the loop.
The loop may not complete the The loop completes the intended number of
intended number of iterations. 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.
58
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
59
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Declaration of one dimensional array:-
Syntax:
type variable name[size]
The type specifies the type of element that will be contained in the array, such as
int , float ,or char and the size indicates the maximum number of elements that can be
stored inside the array.
Example:
int value[20];
It declares the value to be an array of integers containing 20 integer elements.
The C language treats character strings as array of characters. Thus the size in
this case will indicate the maximum number of characters the string variable can hold.
Example: char address[50];
It declares the address as a character array variable that can hold a maximum of
50 characters.
The last element position is always occupied by a null character like‟\0‟, so the
size should be chosen one more than the actual string being stored.
Example:
float height[50];
int group[10];
char name[7];
It declares the name as a character array (string) variable that can hold a maximum
7characters“MCA BCA”.
„M‟
„C‟
„A‟
60
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
„„
„B‟
„C‟
„A‟
Each character of the string is treated as an element of the array name and is
stored in the memory as follows:
61
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();
}
62
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 1-------- 100 200
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};
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
63
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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”);
for(j=1;j<=2;j++)
scanf(“%d”,&b[i][j]);
64
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
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++)
65
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
66
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.
67
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‟.
char string_name[size];
The size determines the number of characters in the string_name. Some examples
are:
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.
69
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!
70
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:
71
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
char ch;
ch=getchar();
72
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);
73
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);
}
74
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);
75
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
scanf(“%s”,s2);
printf(“Concatenate function\n %s”,strcat(s1,s2));
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>
76
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
main()
{
char string1[]=”Jerry:;
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);
77
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
Output:
Source string=sayonara
Target string=sayonara
(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.
78
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
79
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
S2=Compse
(ii) strncmp function
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);
80
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
Output:
S1=Pooja
S2=Pooja reena
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)
}
81
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Output:
S1=Sowdeswari
S2=College
S1=SowdeswariCollege
(iv) strstr function
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
82
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 functions. printf and scanf
83
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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
A function can be called more than once. Every C program can be designed using
a collection of these black boxes known as functions. The functions can be placed in any
order. A called function can be placed either before or after the calling function. A multi
function program is a program, which contains more than one function in it.
main()
---------------
---------------
function1();
---------------
---------------
function2();
function1();
---------------
---------------
---------------
---------------
function2();
function1();
---------------
---------------
function3()
---------------
function3();
---------------
---------------
Flow of control in a multi-function program
85
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
3.2.4 Elements of user-defined functions
The elements of user-defined functions are:
Function definition
Function call
Function declaration
3.2.5 Definition of functions
A function definition, also known as function implementation shall include the
following elements:
function name
function type
list of parameters
local variable declarations
function statements and
a return statement.
All the six elements are grouped into two parts, namely,
86
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
where, type-specifier – data type of return value of the fuction.
function_name – name of the function
argument-list-declaration – variable declarations separated by commas
expression – valid arithmetic expression.
The rules of writing function_name are:
It must begin with a letter
It may be in uppercase or in lowercase.
It should not be a keyword, library
Function Header:-
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.
87
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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)
{
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
88
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)
89
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
90
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();
91
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
test1(); /*function call*/
getch();
}
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:
92
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Values of
{ {
-------------- --------------
-------------- --------------
No return
function2() --------------
Value
--------------One-way data communication
--------------
93
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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 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
{ {
-------------- --------------
function
-------------- --------------
result
function2(a) --------------
Two-way data
-------------- --------------
94
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
int square(int x)
{
int c;
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
{ {
-------------- --------------
Return
-------------- --------------
ans=function2()
value
--------------
--------------
--------------
--------------
One-way data communication
return(e)
}
}
95
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
96
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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.
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 *.
97
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
In the prototype, the arguments must be prefixed by the symbol.
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;
98
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(“Enter the values\n”);
scanf(“%d%d”,&a,&b);
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.
99
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
100
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
3.2.12 Passing arrays to functions
(a) One-Dimensional Arrays
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])
101
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
max=a[i];
return(max);
}
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();
102
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
display(a);
}
void display(int a[][n])
{
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:
103
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
104
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
O
W
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.
105
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
UNIT- IV
Consider a book database consisting of book name, author, number of pages, and
price. Therefore, the structure is defined to hold this information as follows:
106
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.
page Integer
Float price
107
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Memory is created, very first time when the variable is created /
Instance is created.
It is also allowed to combine both the template declaration and variable in one
struct.
i. e:
Another format:
108
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;
}
student= {60, 180, 75};
109
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
----------
----------
}
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,
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.
112
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The precedence of the number operator is higher than all arithmetic and
relational operators and therefore no parantheses are required.
4.1.7 Array of Structures
We use to describe the format of a number of related variables.
Example:
Defines an array is called student which contains 100 elements. Each element is defined
to be of the type struct class.
struct marks
{
int m1,
int m2;
int m3;
};
main( )
{
static struct marks student[3] = {{77, 85, 64}, {37, 67, 96}, {88, 48, 77}}
};
This declares the student as an array of 3 elements student[0], student[1],
student[2] and initializes their members as follows:
113
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( );
}
114
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
4.1.8 Array within Structures
Permits the use of array as structure members. Consider the following structure
declaration
Struct marks
{
int no;
float subject[3];
} student[2];
Here, the member sub contains 3 elements, subject[0], subject[1], and subject[3]. These
elements can be accessed using appropriate subscripts. For example,
Student[1]. Student[2]; would refer to the marks obtained in the 3 subject by the
second student.
struct salary
{
char name[20];
char dept[20];
struct
{
int da;
int hra;
int ma;
}
allowance;
}
employee;
115
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.
116
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The structure variable used as the actual argument and the corresponding formal
argument in the called function must be of the 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,
117
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
code. m;
code. x;
code. c;
All the above are valid member variables. During accessing, we should make
sure that we are accessing the members whose value is currently stored.
Therefore, a union creates a storage location that can be used by any one of its
members at a time. When a different member is assigned a new value, the new value
supercedes the previous member‟s value.
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.
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.
118
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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 arguments to
other functions.
119
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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.
120
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Example:
Variable value address
Quantity 5000
Quantity variable
179
179 value
P 5048
5000 Address 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.
121
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;
122
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.
The pointer variable p2 contains the address of the pointer variable p1,which
points to the location that contains the desired value. This is known as multiple
indirections.
Example:
void main()
{
int x,*p1,**p2;
x=100;
p1 = &x;
p2 = &p1;
printf(“%d”,**p2);
}
4.1.6 Pointer Expressions
Pointer variable can be used in expression. For Example p1 and p2 are properly
declared and initialized pointers.
Example:
sum = sum+*p1;
123
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Z = 5*-*p2/*p1; same as (5*(-(*p2)))/(*p1)
*p2 = *p2+10;
1 2 3 4 5
Value
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,
124
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++)
125
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
printf(“%d”,*(a+1));
getch();
}
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
…………………………………………
…………………………………………
126
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
(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
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( );
127
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
}
Output:
Enter a string
Program
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
128
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
129
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);
130
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
s=sum(a,b);
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);
131
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
} stu1, *s;
Here stu1 is the object of the stu. *s also points to the stu structure.
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;
t.ip=&a;
printf(“Value of a=%d \n ”,t.i);
printf(“Address of a=%u \n ”,t.ip);
getch( );}
Output:
Value of a =1 Address of a =500
132
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
UNIT - V
5.1 FILE MANAGEMENT
5.2.1 Introduction
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
133
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Function Name Operation
File name
Data structure
Purpose
134
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
a.)File name
Sowdeswari.txt
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
135
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
r+ The existing file is opened to the beginning 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)
136
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.
138
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The file INPUT is reopened for reading. The program then reads its
content character by character and displays it on the screen.
5.2.4.2 The getw and putw Functions
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)
140
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
111 333 555 777 999 121 343 565
Contents of DATA file
222 444 666 888 000 232 454
5.2.4.3 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 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;
141
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
char item[10],filename[10];
printf(“Input file name “);
scanf(“%s”,filename);
fp=fopen(filename,”W”);
printf(“Input inventory data\n”);
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);
}
142
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
143
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Function name Use
feof It can be used to test for an end of file condition
ferror It reports the status of the file
a) feof Function
It can be used to test for an end of file condition
It takes FILE pointer as argument and returns a non-zero integer value if all
of the data from the specified file has been read, and returns non-zero
otherwise.
Example
If(feof(fp))
Printf(“End of data”);
The above statement display the message “End of data”, on reaching the end
of the file condition.
#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);
144
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
c = getc ( fp );
}
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)
146
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
The following example illustrate the operations of the fseek function
Statement Meaning
fseek(fp,0L,0) Go to Beginning
fseek(fp,0L,1) Stay at the current position
fseek(fp,0L,2) Go to the end of file, past the last character of the file
fseek(fp,m,0) Move to (m+1) th byte in the file
fseek(fp,m,1) Go forwards m bytes
fseek(fp,-m,1) Go backward by m bytes from the current position
fseek(fp,-m,2) Go backward by m bytes from the end
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.
#include<stdio.h>
main()
{
FILE * fp;
long n;
char c;
fp =fopen(“RANDOM”,”w”);
147
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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);
}
148
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
Position of P is 15
Position of U is 20
Position of Z is 25
ZYXWVUTSRQPONMLKJIHGFEDCBA
5.2.7 Command line arguments
It is a parameter supplied to a program when the program is invoked
Accessing the command line arguments is a very useful facility.
To access these arguments from within a C program, you pass parameters to the
function main().
The declaration of main looks like this:
int main (int argc, char *argv[]) int main (argc, argv)
{ int argc;
-------------- //statements
} --------------
--------------
149
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
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--;
}
}
150
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
151
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
MODEL QUESTION PAPER 1
(For the Candidates admitted from 2017-2018 onwards)
B.Sc(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
152
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
153
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
MODEL QUESTION PAPER 2
(For the Candidates admitted from 2017-2018 onwards)
B.Sc(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.
154
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.
155
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
MODEL QUESTION PAPER 3
(For the Candidates admitted from 2017-2018 onwards)
B.Sc(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
156
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.
157
Salem Sowdeswari College, Self-Financing Courses Wing
___________________________________________________________________________
158
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)
159