You are on page 1of 126

PROGRAMMING IN C

Staff Handled By : D.Mythili


PROGRAMMING IN C

SYLLABUS

Unit-I

Structure of a C program – C character set – Delimiters –


Keywords – identifiers – Constants – variables – rules for defining
Variables – data types – Declaring and initializing variables – type
Conversion. Operators and expressions

Unit-II

Formatted and Unformatted Input and output functions –


Decision Statements – loop Control Statements.

Unit-III

Arrays : Array initialization – definition – characteristics- one


– dimensional array, predefined streams- Two- dimensional array –
Three or multi dimensional arrays. Strings and Standard functions:-
Declaration and initialization of string- Display of string with different
formats – String standard functions – Application of strings. Pointers:
Features, Pointer declaration, Arithmetic Operations with pointers-
Pointers and Array – Pointers and Two-dimensional array – Array of
pointers – Pointers to pointers – Pointer and Strings –Void pointers.
Functions: Definition, Declaration, The return statement, Types of
functions, Call by value and Call by reference, Functions returning
more values, Functions as an argument. Functions with Arrays and
pointers – Recursion – Preprocessor Directives.

Unit-IV

Structure and Union: Features of structure, Declaration and


initialization of structure, Structure within structure, Array of structure,
Pointer to structure, Bit fields, Union.

Unit-V

Files: Streams and file types, Steps for file operation, File I/O,
Structures read and write, other file functions, Command line
arguments, I/O redirection
DEPARTMENT OF ELECTRONICS AND COMMUNICATION
SYSTEM

STUDY MATERIAL

COURSE : II YEAR A, B.Sc ECS


SEMESTER : III
UNIT : I
SUBJECT NAME : PROGRAMMING IN C
LECTURER NAME : D.MYTHILI
NUMBER OF PAGES : 18
DATE OF ISSUE :

Unit-I
Introduction to C programming - Structure of a C program – C character
set – Delimiters – Keywords – identifiers – Constants – variables – rules
for defining Variables – data types – Declaring and initializing variables
– type Conversion. Operators and expressions

Introduction to C programming
C was an offspring of ‘Basic Combined Programming
Language’(bcpl) called B, developed in the 1960’s at Cambridge
university. B language was modified by Dennis Ritchie and was
implemented at Bell Laboratories in 1972.The new language was
named as C. since it was developed along with UNIX operating
system, it is strongly associated with UNIX. It can run under
various operating systems including MSDOS.

Importance of C:
1. It is robust language.
2. Rich set of built-in functions and operators are available.
3. Easy to create complex programs.
4. Suitable to write both application software as well as system
software.
5. It is highly portable. Because C programs written for one
computer
can be run on another with little or no modification.
6. It is well suited for structured programming. So that it is easy to
debug,
test and maintain a module.
7. It can extend itself.

Basic structure of C programming:

Documentation section
link section
Definition section
Global declaration section
Main( ) function section
{
declaration part
executable part

Subprogram section
function 1
function 2
function 3
.
.
function n

a) Include header file section:


A C program depends upon some header files for function
definition that are used in the program. Each header file has .h
extension.
Eg. #include <stdio.h>
b) Global declaration:
This section declares some variables that are used in more
than one function. These variables are known as global variables. This
section must be declared outside of all the functions.

c) Function main ( ):
Every program in C must contain main ( ) function. Empty
parenthesis after main is necessary. The function main ( ) is a starting
point of every C program. The execution of the program always begins
with the function main ( ).
d) Declaration Part:
It declares the entire variables that are used in the
executable part. Initializations of variables are also done in this
section. Initialization means providing initial value to the variables.
e) Executable Part:
This part contains the statement following the declarations
of the variables. This part contains a set of statements or a single
statement. These statements are enclosed between braces.
f) User-defined function:
The functions defined by the user are called user-defined
functions. These functions are generally defined after the main ( )
function. They can be also be defined before main ( ) function. This
portion is not compulsory.
g) Comments:
It is not compulsory in a program. However to understand
the flow of a program, the programmer can include comments in the
program. Comments can be inserted by the programmer. These are
useful for documentation. The clarity of the program can be followed if
it is properly documented.
Example
/ * This is a single comment * /
/ * This is an example of / * nested comments * / * /
/ * This is an example of
comments with multiple lines * / / * It can be nested * /
C Character Set
The characters are used to form words, numbers and
expressions depending upon the computer on which the program runs.
The characters in C are classified into the following characteristics.
1. Letters 2. Digits 3. White Spaces 4. Special characters.

Character Set

1) Letters 2) Digits 3) White


Spaces
Capital A to All decimal digits 0 to 9 Blank Space
Z
Small a to z Horizontal Tab
Vertical Tab
New Line
Form Feed
4) Special Characters:
, Comma & Ampersand
. Period or dot ^ Caret
; Semi – colon * Asterisk
: Colon - Minus
` Apostrophe + Plus
“ Quotation < Less than
mark
! Exclamation > Greater than
mark
Vertical bar ( Parenthesis left /
) right
/ Slash [ Bracket left /
] right
\ Back slash { Braces left / right
}
~ Tilde % Percent
_ Under score # Number sign or
hash
$ Dollar = Equal to
? Question @ At the rate
mark
Delimiters:
Language pattern of C uses special kinds of symbols, which are
called as delimiters. They are given as under.
Delimiters Use
: Colon Useful for label
; Semi Colon Terminates statement
( ) Used in expression and
Parenthesis function
[ ] Square Used for array
bracket declaration
{ } Curly Scope of statement
brace
# Hash Preprocessor directive
, Comma Variable separator
The C keywords:
The C keywords are reserved words by a compiler. They are
assigned a fixed meaning. The keywords cannot be used as variable
names because they have been assigned fixed jobs. However, few
compilers allow to construct a variable name, which exactly coincides
with the keywords. For utilizing the keywords in a program no header
file is to be included. The description of the keywords is given below.
auto doub int struct
le
break else long switch
case enu regist typede
m er f
char exter retur union
n n
const float short unsign
ed
contin for signe void
ue d
defaul goto sizeof volatil
t e
do if static while
Additional keywords for
Borland C
asm if static while

Identifiers:
Identifiers are names of variables, functions and arrays. They
are user-defined names, consisting of sequence of letters and digits,
with the letter as the first character. Lower case letters are preferred.
However, the upper case letters also permitted. The underscore ( _ )
symbol can be used as an identifier.
Example: 1. #define N 10
2. #define a 15
Here “N” and “a” are user-defined identifiers.

Constants:
The constants in C are applicable to the values that do not
change during the execution of a program. There are several types of
constants in C. They are classified as follows.

A. Numerical constants:
1) Integer constants:
It refers to a sequence of digits from 0 to 9 without decimal
points or fractional part or other symbols. It requires minimum two
bytes and maximum 4 bytes. Integer constants can either be
positive, negative or maybe zero. The number without a sign is
assumed as positive.
Example: 10, 20, +30, -15
2) Real constants:
The numbers with fractional part is called real or floating-point
constants. Many parameters or quantities are defined not only in
integers but also in real numbers.
Example: 1) 54.98
2) 25.75
B. Character constants:
1. Single character constants:
A character constant is a single character. They are also
represented with a single digit or a single special symbol or white
space enclosed within a pair of single quote marks.
Examples: 1) ‘a’
2) ’#’
3) ’2’
4) ’ ’
2. String Constants:
They are a sequence of characters enclosed within a double
quote marks. The string may be a combination of all kinds of
symbols.
Example: “ Hello”, “India”, “444”, “a”.

Variables:
A variable is a data name that may be used to hold a data
value. A variable may take different values at different times
during the program execution.

Rules for forming a variable:


1. The starting character should be a letter. The first character may be
followed by a sequence of letters or digits.
2. The maximum number of characters in a variable may be 8
characters. The number of characters differs from compiler to
compiler.
3. Upper and lower case are significant. Example: TOTAL is not
same as total or Total.
4. The variable should not be a keyword.
5. White space is not allowed.
6. Special characters except _(underscore) symbol are not
allowed.

“C” Data Types:


Data is a collection of characters, digits, symbols etc., the
data are used to represent information. The data are classified in
various types. C data types are classified into the following
categories.
a. Basic data type
b. Derived data type
c. User-defined data type
d. Void data type
Basic Data types:
The basic data types supported by C are described with their size
in bytes and ranges.

Data Type Size in Range


Bytes
char 1 -128 to 127
unsigned 1 0 to 255
char
signed char 1 -128 to 127
Int 2 - 32768 to 32767
unsigned int 2 0 to 65535
signed int 2 - 32768 to 32767
short int 2 - 32768 to 32767
unsigned 2 0 to 65535
short int
signed short 2 - 32768 to 32767
int
long int 4 - 2147483648 to
2147483647
signed long 4 - 2147483648 to
int 2147483647
unsigned 4 0 to 4294967295
long int
float 4 3.4E- 38 to 3.4E+38
double 8 1.7E – 308 to 1.7E +
308
long double 10 3.4E – 4932 to 1.1E
+4932
enum 2 - 32768 to 32767

Derived Data type:


The derived data types are of the following types:
1. Pointers
2. Functions
3. Arrays
1. Pointers:
A pointer is a memory variable that stores a memory address.
Pointers can have any name that is legal for other variables and it
is declared in the same fashion like other variables but it is always
denoted by ‘*’ operator.
int *x;
float *f;
char *y;
In the first statement ‘x’ is an integer pointer that tells to
the compiler that it holds the address of any integer variable. In
the same way ‘f’ is a float pointer that stores the address of any
float variable and ‘y’ is a character pointer that stores the address
of any character variable.
2. Functions:
A function is a self-contained block or a sub-program of one or
more statements that perform a special task when called. In fig
funA( ) and funB( ) are two user-defined functions. These are
invoked from the body of main. After execution of funA( ) and
funB( ) the program control returns back to the calling function
main( ).

3. Arrays
An array is a collection of elements of similar data types in
which each element is located in separate memory location.
Eg. int b[4];
Variables:
A variable is a data name that may be used to hold a data
value. A variable may take different values at different times
during the program execution.
Rules for forming a variable:
1.The starting character should be a letter.
2.The maximum number of characters may be 8 characters. it
differs
3.Upper and lower case are significant. Example: TOTAL is not
same as total or Total.
4.The variable should not be a keyword.
5.White space is not allowed.
6.Special characters except _(underscore) symbol is not
allowed.

Valid examples:
1. john
2. value
3. tot_amt
4. a1

Invalid examples: Reason


1. 1868 1) The first letter should be a letter
2. (area) 2) Special characters not
allowed
3. 27th 3) Number should not be a
first character
4. % 4) Special characters not allowed

Data types:
1. Primary data types.
2. User- defined data type
3. Derived data type
4. empty data set

Primary data types:


1. Integral type:
a. Integer size
i. signed int 16 bits
ii.short signed int 8 bits
iii.long signed int 32 bits
iv.unsigned int 16 bits
v.unsigned short int 8 bits
vi.unsigned long int 32 bits

b. Character
i. signed char 8 bits
ii. unsigned char 8 bits

2. Floating-point type
i. float 32 bits
ii. double 64 bits
iii. long double 80 bits

Declaration of variables:
Purpose:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.

Syntax:

v1,v2,v3….vn- variables

Example:
1. int count;
2. int a,b;
3. float area,volume;
4. char array;
5. double a1;

data type keyword equivalent


character char
unsigned character unsigned char
signed character signed char
signed integer signed int to int
signed short integer signed short int
signed long integer signed ling int
unsigned integer unsigned int or unsigned int
unsigned short integer unsigned short int
unsigned long integer unsigned long int
floating point float
double precision double
extended double precision long double

User defined declaration:


Types:
1. type definition
2. enumerated data type

Type definition:
Purpose:
This allows the user to define the identifier that would represent
an existing data type. The user-defined type is later used to
declare variables.
General form:
Typedef - keyword
Type - exiting data type
Identifier –new name given to the data type
Typedef cannot create a new type. Using identifier the variables
can be declared using the following syntax:

Examples:
Typedef int units;
Units batch1,batch2;
Units name[10],name1[20];

Enumerated data type:


It is defined as follows

It is used to declare the variables that can have one of the values
enclosed within braces(known as enumerated constants).we can
declare variables to be of this ‘new’ type as below:

The enumerated variables v1,v2,…vn can have one of the


values value1,value2,…value n.
Examples:
1. enum day {monday,tuesday,…sunday};
enum day week_beg,week_end;
we can assign values like
2. week_beg=sunday;
week_end=saturday;
We can compare the values like
3.if (week_beg == friday)
week_end=thursday;
The compiler automatically assigns integer digits beginning
with 0 to all the enumeration constants. Thus the enumeration
constants assign value1 as 0,value2 as 1 and so on. However the
automatic assignments can be overridden by assigning values
explicitly to the enumeration constants.
Example:
enum day {monday=1,tuesday=5,….sunday};
In the above Wednesday will take the value of 6,Thursday will
take 7 and so on.
enum
month(Jan,Feb,Mar.Apr,May.Jun,Jul,Aug,Sep,Oct,Nov,Dec)
this statement creates user defined data type. the keyword enum is
followed by the tag name month. The enumerators are the identifiers
Jan,Feb,Mar.Apr,May.Jun,Jul,Aug,Sep,Oct,Nov,Dec. Their values are
constant unsigned integers and start from 0. the identifier jan refers to
0, feb to 1 and so on. The identifiers are not to be enclosed with in
quotation marks.
Write a program to create enumerated data type for 12
months. Display their values in integer constants.
#include <stdio.h>
#include <conio.h>
Void main()
{
enum month(Jan,Feb,Mar.Apr,May.Jun,Jul,Aug,Sep,Oct,Nov,Dec);
clrscr();
printf(“\nJan=%d”,Jan);
printf(“\nFeb=%d”,Feb);
printf(“\nJune=%d”,June);
printf(“\nDec=%d”,Dec);
}

OUTPUT:
Jan=0
Feb=1
June=5
Dec=11
Explanation: In the above program enumerated data type month is
declared with 12-month names within two curly braces. The compiler
assign 0 value to first identifier and 11 to last identifier. Using printf()
statement the constants are displayed for different identifier. By
default the compiler assign value from 0 onwards. Instead of 0 the
programmer can initialize his/her own constant to each identifier.

Global and local variables:


Global variable is visible to all functions in the file. It is necessary
to declare the variable before the main function. No need to
declare the global variables in all functions. It is also known
external variable. Local variable is visible and meaningful only
inside the function in which they are declared.
Example:
/*example of storage classes*/
int m;
main( )
{
int I;
float balance;
……..
……..
function1( );
}
function1( )
{
int i;
float sum;
……
……
}

Storage classes:
Purpose:
It provides the information about location and visibility of
variables.

Types meaning
1. auto local variable known only to the function
where it is declared
default is auto.
2.static local variable which exists and retains it ‘s
value even after
control is transferred to the calling function.
3.extern global variable known to all function sin the file
4.register local variable which is stored in the register.

Example:
auto int count;
register char ch;
static int x;
extern long total;

Assignment statement:
Purpose : values can be assigned to variables using the
assignment operator = as follows

Examples:
It is possible to assign the values during declaration time as
follows:

Example:

Declaring a variable as Constant :


Purpose :
To maintain the value of variable throughout the program
execution we are declaring the variable as constant.
Example:

Reading the data from the keyboard:


Another way of giving values to variables is to input data
through keyboard using the scanf function.
Syntax:

The control string contains the format of data being


received. The ampersand symbol & before the variable name is
an operator that specifies the variable name’s address
Example :

%d- represents integer value


%f- “ float number
%c- “ character
%lf - “ double
%u - “ unsigned int

Output using printf:


Purpose :
It is used to display the output as well as to create an
interactive program .
Syntax:
Operators :
Purpose :
It is used to tell the computer to manipulate data
and variables.
Types:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Arithmetic operators:
Arithmetic operators are used to perform arithmetic
operations like addition , subtraction, multiplication and division
and to find the remaindering division. The corresponding symbols
are +(addition or unary plus),- (subtraction or unary minus),*,/,%
(modulo division).C does not have an operator exponentiation.

Relational operators:
Purpose:
To relate any two or more quantities.
Operator Meaning
< is less than
> is greater than
> is greater than or
equal to
<= is lesser than or equal
to
== is equal to
!= is not equal to
Logical operators:
Purpose :
To combine two or more expressions.
Operator meaning
&& logical and
|| logical or
! logical not

Assignment operators:
= is used to assign value to a variable. In addition
to this c has
shorthand operators.
Syntax:

Statement with simple Statement


with short
Assignment operator. Hand
operator.
a=a+1 a+=1
a=a-1 a-=1
a=a*1 a*=1
a=a/1 a/=1
a=a%b a%=b

Advantages:
1. No need to repeat the operator again in the right
hand side.
2. The statement is more concise and clear.
3. The statement is more efficient.
4. It is easy to read.

Increment and Decrement operators:


Purpose:
To decrement the value of the variable by one or to
increment the value of the variable by one.
Operators:
++ - adds 1 to the operand
-- - subtracts 1 unary operators
Example:
++m; (++ used as prefix operator)
m++; (++ as postfix operator)
If they are used independently then meaning is same.
Consider the following
m=5;
y=++m;
In the above case m and y would be 6.
m=5;
y=m++;
In the above case m would be 6 and y would be 5.
Similarly for the --operator.

Conditional operator:
Purpose:
A ternary operator pair “?:” is used to construct
conditional expressions
Syntax:

Example :
x=(a>b)?a:b;
In the above the condition is evaluated first .if true
then a will be assigned to x or else b will be assigned to x. The
above syntax is equivalent to if …else statement.

Bitwise operators:
Purpose:
Manipulating the data at bit level.

Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise EXCLUSIVE OR
<< shift left
>> shift right
~ one’s complement

Special operators:
sizeof - to determine the size of the variable
,(comma) - to link the related expressions together
example : value=(x=10,y=17,x+y)
. and -> - member selection operator
& and * - pointer operator

Expressions:
Combination of both operand and operator.
Types:
1. Arithmetic
2. Relational
3. Logical

Arithmetic expression:
Operand combined with arithmetic operators called as
arithmetic expressions
Examples:
a+b
c-d
Types:
1. Integer arithmetic
2. Real arithmetic
3. Mixed arithmetic
Integer arithmetic:
Arithmetic operator combined with integer operands.
Example:
a + b; where a and b are of type integer.

Real arithmetic:
Arithmetic operator combined with real operands.
Example:
a + b where a and b are of type real.

Mixed mode arithmetic:


Expression consists of both integer and real operands.
Example:
a-b where a is of type integer and b is of type real.

Evaluation of expression:
Expression evaluation based on the priority of
operators.
High priority * / % left to right
Low priority + -

Logical expression:
Whenever the logical operators combine any two relational
expressions then it is called logical expression.
Example:
((a<b )&& (c>d))

Operator precedence:
1. Logical NOT
2. Logical AND
3. Logical OR

Type conversions in expressions:


If operands are of different types then the lower type
is automatically converted into higher type before the operation
proceeds. The result is of higher type.
1. All short and char to int.
2. If one of the operand is long double then other will be
converted into long double.
3. Else if one is double then other will be converted into double.
4. Else if one is float then other will be float.
5. Else if one is unsigned long int then other will be unsigned long
int.
6. If one is unsigned long int and other one is long int then
a. Unsigned long int will be converted into long int or
b. Long int will be converted into unsigned long int.

Casting a value:
If we need to force the type conversion explicitly then
it is called as coercion.
Example:
ratio=(float) number1/number2;
Where number 1 and number2 are of type integer type,
ratio is of type float.
General form of Casting:

Suggested Questions

3. What are unary operators?


4. Give an example for short hand assignment operator.
5. Where was C orginally developed and by whom?
6. What is the name for data type conversion?
7. Explain about mixed mode arithmetic operations
8. Write short notes on logical operators.
9. Explain about operators supported by C
10.Explain data types supported by C
11.Give the hierarchy of operator precendences covering all of the
operators in C
12.Explain arithmetic & relational operators?
13.Explain Structure of C Program with suitable examples.
14.What is variables. List out the rules to declare a variables.
15.What is Identifiers.
16.What is type casting.
17.Write a program Which combine all the operators.
STUDY MATERIAL

COURSE : II YEAR A, B.Sc ECS


SEMESTER : III
UNIT : II
SUBJECT NAME : PROGRAMMING IN C
LECTURER NAME : D.MYTHILI
NUMBER OF PAGES : 7
DATE OF ISSUE :

Unit-II

Decision Statements – loop Control Statements.

Control/Decision making statements:


1.If statement
2.Switch statement
3.Conditional operator statement
4.Goto statement

If statement:
Purpose:
It is a powerful decision making statement to control
the flow of execution. It is basically two-way decision statement
and is used in conjunction with and expression.
Syntax:

It allows the system to evaluate the expression first


and then, depending on whether the value is true or false it
transfers the Control to the particular statement.

entry

false

true

Different forms of IF statement:


1. Simple if statement
2. If …else statement
3. Nested if … else statement
4. Else if ladder

Simple if statement:
Syntax:

In the above statement if test expression is true then


statement block
will be executed else statement block will be skipped.

If …else statement:
Syntax:

Above statement if the test expression is true then true block


statement, immediately following by the If statement are
executed; otherwise the false block statement are executed. In
either case either true block will be executed or false block will be
executed but not both.

Nesting of if … else statement:


Syntax:
In the above statement if the condition 1 is true then the
second if condition 2 will be tested and if it is also true then the
statement 1 will be executed. if the second condition is false then
the statement 2 will be executed. If the first condition is false then
the statement 3 will be executed.

Else … if ladder:
Syntax:

The condition are evaluated from the top to bottom 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.

The Switch statement:


Purpose:
Using the value of any variable or expression uses it to select
one branch among several alternatives. The switch tests the value
of given variable (or) expression against a list of case values and
when a match is found, a block of statements associated with that
case is executed.
Syntax:
In the above syntax the expression is an integer expression
or characters the value-1,value-2,…. are constants or constant
expressions and are known as case labels.

Each of these values should be unique within a switch


statement. block-1, block-2,….. are statements contain zero or
more statements. There is no need to put braces around these
blocks. The case labels must end with a colon. When a switch is
executed, the value of expression is compared with case values, if
matches, then the block of statements that follows the case are
executed. The break statement is used to exit from the switch
statement.
Example:
----------
----------
switch(n)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
default: c=a/b;
break;
}
printf(“%d”,c);
----------------
------------------

Loop constructs:
Purpose:
It is used to repeat the block of statements for n number of
times.
Process involved in looping statement is as follows:-
1. Setting and initialization of counter.
2. Execution of the statements of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Incrementing the counter.
Types:
1. While statement
2. Do statement
3. For statement

1) While statement:
a. The while is an entry- controlled loop statement.
b. The test -condition is evaluated first and if the
condition is true, then the body of
loop is executed. Again the test-condition is tested and body
of the loop will be
repeated until the condition becomes false
c. If at the entry condition itself the test-condition is false then
body of loop will be
skipped.
Syntax:

Example:
#include < stdio.h>
void main()
{
int i=1;
while (i<1)
{
printf(“this is number %d\n”);
i++;
}
}

2) The do statement:
a. The do is an exit- controlled loop statement.
b. The body of loop will be executed once and the condition is
tested if the condition is true then body will be repeated or
else exit from the loop.
Syntax:

Example:
------------------
-----------------
do
{
printf(“well done!”);
}
while(number<=10);
---------------
---------------

3) For statement :
If we know the exact number of times for repetition of block
of statements, then for statement can be used. it is entry
controlled control loop.
Syntax:

Execution of ‘for’ statement as follows:


1. Initialization of the control variable is done first.
2. The value of the control variable is tested using the test
condition. If the test condition is true then the block is executed
otherwise the loop is terminated and the execution continues with
the statement immediately follows.
3. When the body of the loop is executed, then the control
is transferred back to the For loop. The control variable will be
incremented by using the increment and again tested using the
test condition. This will be repeated until the test condition
becomes false.
4. It allows negative increments. In that case the initial
value should be greater than the final value.
5. In normal situation initial value is lesser than the final
value.
6. It allows more than one variable initialization as well as
more than one variable incrementation.
Examples:
for (i=1; i<=10; i++) (positive increment)
for (i=10; i>0; i--) (negative increment)
for (i=0,j=8; i<=j; i++,j--)
7. For statement is not followed by semicolon(;).
8. Nested loop is also possible. (ie.,) loop within a loop.
Example :
----------------
----------------
for (i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
------------------
------------------
}
}
-------------------
9. Break statement is used to exit from the loop. It can be used a
part of If statement.
Example:
-----------
for(I=1;I<=10;I++)
{
if (a<b) break;
--------------
--------------
}
-------------
10. To skip a portion of statements in the for loop continue
statement
can be used in conjunction with if statement and
will goto the for
statement.
Example:
for(i=1;i<=10;i++)
{
if (a<b) continue;
--------------
--------------
}
-------------
11. Avoid using goto statements in for statements.

Suggested Questions

Objective answers:
18.What is the size of long int?
19.Name any two ascii types of constants.
20.Must all the variables appearing within a C program be
declared ?
21.What is meant by linking
22.When is the logical expression evaluated in a do..while
statement?
23.What symbol terminates each C statement/
24.What sre symbols used for logical operators AND & OR?
25.Give the conversion specifications used for printing octal & hexa
decimal values.
26.every line in c programming should end with a semi colon.- say
true or false
27.in c language , lowercase letters are significant- say true or false
28.every c program end with and END word.
29.main() is where the program begins its execution.
30.a line in c program may have more than oneline of output.
31.a printf() statement can generate only one line of output.
32.syntax error will be detected by the compiler.
33.what are trigraph characters? How are they useful?
34.what is variable.
35.what is initialization? Why it is important?
36.what are enumeration variables? How are they declared?
37.describe the purpose of the qualifiers const and volatile.
38.which of the following are invalid constant and why?
0.0001
5x1.5
99999
“12.342”
39.which of the following are invalid variable names and why?
Maximum
Last.rollno
Mn+me
Row total
40.which of the following arithmetic expressions are valid? If invalid,
give reason.
25/3%2
12.4%2
21 %(int)3.2
41.write the c assignment statements to evaluate the following
equations.
42.Area= IIr2+22/7rh
43.Torque=2m1m2

44.m1+m2
45.determine the valueof each of the following logical expressions if
a=10,b=25and c=-7
a>b&&a<c
a<b &&a>c
b>12&&c<0 ||c<0.0
46.state errors ,if any, in the following input statements
scanf(“%c %f %d”,city,&price);
scanf (“%s %d”,city,quan);
47.what is the use of conditional operator?
48.write the syntax of if.. statement . write the difference between
while statement and do…while statement

Suggested Questions:
49.Explain if statement with an example
50.Differentiate while & do...while statement
51.?
52.write a program to check whether the given year is a leap year
or not
53.write a program to find largest among three given numbers.
54.write a program to find reverse of the given digit
55.write a program to do arithmetic operations for any two given
numbers using switch case statement.
56.write important features of for statement.
57.write a program to convert the given farenheit temperature to
Celsius temperature.
58.write a program to generate fibanocci numbers
59.write a program to generate prime numbers.
60.write a program to calculate simple and compound interest

Essay Answers
61.Explain about looping statements with suitable examples
62.Write a program to print the fibonacci series
63.Write a program to print the prime numbers between 1 to 100
64.Write a program in c to solve a quadratic equation to check all
possibilities of their coefficients

STUDY MATERIAL

COURSE : II YEAR A, B.Sc ECS


SEMESTER : III
UNIT : III
SUBJECT NAME : PROGRAMMING IN C
LECTURER NAME : D.MYTHILI
NUMBER OF PAGES : 56
DATE OF ISSUE :

Unit-III
Arrays : Array initialization – definition – characteristics- one –
dimensional array, predefined streams- Two- dimensional array – Three
or multi dimensional arrays. Strings and Standard functions:-
Declaration and initialization of string- Display of string with different
formats – String standard functions – Application of strings. Pointers:
Features, Pointer declaration, Arithmetic Operations with pointers-
Pointers and Array – Pointers and Two-dimensional array – Array of
pointers – Pointers to pointers – Pointer and Strings –Void pointers.
Functions: Definition, Declaration, The return statement, Types of
functions, Call by value and Call by reference, Functions returning
more values, Functions as an argument. Functions with Arrays and
pointers – Recursion – Preprocessor Directives.

ARRAYS
Definition :
An array is a group of related data items that share a common name.
Example:
An array name salary can be used to represent a set of salaries of a
group of employees.
A particular value in an array is called an element and can be written
as follows

salary [10] represents the salary of the 10th person.

TYPES :
1. One dimensional arrays / Single subscripted array
2. Two dimensional array
3. Multi dimensional array

ONE DIMENSIONAL ARRAY:


Definition :
A list of related data items with one variable and only one subscript is
called single- subscripted array.

DECLARATION OF ARRAYS:
Syntax:

where
type - int, float ,double, longint,char
variable_name - valid c programming variable
size - no. of elements

Example:
1. int a[10];
2. float height[20];
3. char name[10];

Explanation:
1. In the first declaration we can store atmost 10 elements
of type integers.
2. The second declaration can hold 20 elements of real
numbers.
3. In third we can store atmost 9 characters. While
declaring character array the last character must be a null
character(‘\0’). This character is automatically included while assigning
values to these variables. While mentioning about the size we must
include one extra space with maximum number of characters.

INITIALIZATION OF ARRAYS:
Syntax:

We can initialize the array variable like ordinary variables


when they are declared. In the above list of values are separated by
comma. Suppose the value is not given then automatically it will be
assigned as zero.

Example:
a. static float total[5] = {0.5,15.63,-20};
In the above the first three elements are set to 0.5, 15.63, -20
and the remaining elements are set to
zero.
b. static int count[]= {1,1,1,1};
In the above the size is omitted. The compiler itself allocates
enough space for all initialized
elements.

DRAW BACKS IN INITIALIZATION OF ARRAYS:

1. There is no convenient way to initialize only selected


elements.
2. There is no shortcut method for initializing a large number
of array elements like the one available in FORTRAN.

TWO DIMENSIONAL ARRAYS:


Definition :
A list of related data items withone variable and subscripts
representing the row value and column value is called two dimensional
array.

DECLARATION OF ARRAYS:
Syntax:
where
type - int, float ,double, longint,char
variable_name - valid c programming
variable
size - no. of elements

Example:
1. int a[10][10];
2. float height[20][2];
3. char name[10][10];

Explanation:
1. In the first declaration we can store atmost 100 elements of
integers.
2. The second declaration can hold 40 elements of real numbers.
3. In third we can store almost 10 names of 9 characters. While
declaring character array the last character must be a null
character(‘\0’). This character is automatically included while assigning
values to these variables. While mentioning about the size we must
include on extra space with maximum number of characters.

INITIALIZATION OF ARRAYS:
Syntax:

We can initialize the array variable like ordinary variables when


they are declared. In the above list of values are separated by comma.
Suppose the value is not given then automatically it will be assigned as
zero.

Example:

a. static float mat[2][3] = {{0.5,15.63,-20},{10.2}};


In the above the first row elements are set to 0.5 , 15.63 , -20 and in
the second row the first element is 10.2 and the remaining elements
are set to zero.

MULTI DIMENSIONAL ARRAYS:


Definition :
A list of related data items with one variable and more than 2
two subscripts is called multi-dimensional array.

DECLARATION OF ARRAYS:
Syntax:
where
type -- int , float , double , longint , char
array_name -- valid c programming variable
si -- size of ith dimension where i =
1,2,3…n

SAMPLE PROGRAM USING ARRAY:(ascending order)

#include <stdio.h>
#include <string.h>
main()
{
int i, a[10], n, t;
/*INPUT THE NUMBER OF ELEMENTS*/
printf(“Enter the total no of elements \n”);
scanf(“%d”,&n);
/*ENTER THE VALUES TO BE SORTED*/
printf(“Enter elements \n”);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
/*BUBBLE SORT*/
for(i=1;i<=n-1;i++)
{
for(j=i;j<=n;j++)
{
if (a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
/*PRINT THE RESULT*/
printf(“ sorted elements \n”);
for(i=1;i<=n;i++)
printf(“%d”,a[i]);
getch();
return(0);
}

STRINGS AND CHARACTER ARRAYS:


Definition:
String is an array of characters. Any group of characters
enclosed between double quotes is a string constant.
Example:
“Where there is will there is way”

Operations performed on strings:


1. Reading and writing strings.
2. Combining strings together.
3. Copying one string to another.
4. Comparing strings for equality.
5. Extracting a portion of string.

DECLARATION AND INITIALIZATION OF STRING VARIABLES:


Syntax:

Example:
1. char city[10];
2. char name[30];
3. static char city[9]= “new york”;
4. static char city[9]={‘n’,’e’,’w’,’,’,’y’,’o’,’r’,’k’,’\o’};

In the above 3 and 4 initializations are same. In character array the


compiler automatically includes the null character at the end of the
string.
If the size is not mentioned then the compiler itself defines the size of
the array variable depending upon number of elements in the
initialization statement.

READING STRINGS FROM THE TERMINAL:


The scanf function can be used with the control string %s
to read in a string of characters.

Example:
char name[15];
scanf(“% s”,name);
In the above example & is not required before the variable name.

Drawback:
1. We cannot read a line of text from the terminal.

Reading a line of text:


We can read the entire line of text using the function getchar().
By using the above function it terminates the input process whenever
it receives the newline character.

Example:
/**************************************/
/* program to read a line of text from terminal*/
/**************************************/
#include <stdio.h>
main()
{
char line[81],character;
int c;
c=0;
printf(“enter text .press <enter> at end\n”);
do
{
character=getchar();
line[c]=character;
c++;
}
while (character!=’\n’);
c=c-1;
line[c]=’\0’;
printf(“\n%s\n”,line);
}

WRITING STRINGS TO THE SCREEN:


Printf statement with control string %s is used to display the
string value.
Example:
Printf(“%s”,name); (or) printf(“%Total columns.Total
characters s”,name);

EFFECT OF VARIOUS %S SPECIFICATION :


1. When the field width is less than the length of the string , the
entire string is printed.
2. The integer value on the right side of the decimal point
specifies the number of number of characters to be printed.
3. When the number of characters to be printed is specified as
zero, nothing is printed.
4. The minus sign in the specification causes the string to be
printed left- justified.

ARITHMETIC OPERATIONS ON CHARACTERS:


C allows us to manipulate the characters in the same way as numbers.
Whenever a character constant or character variable is used it is
automatically converted into integer value by the system. The integer
value depends on the local character set of the system.
Example:
X=’a’;
Printf(“%d\n”,x);

The output of the above statement will be 97.

Similarly it is also possible to perform all the arithmetic operations like


addition ,subtraction , multiplication , division etc. To convert integer
to ascii as well as ASCII to integer is done by using library functions
like itoa(integer),atoi(string).

PUTTING STRINGS TOGETHER:


Just as we cannot assign one string another directly, we cannot join
two strings together by the simple arithmetic addition like as follows:
Str3=str1+str2;
Str2=str1+”good”; invalid

The characters from str1 and str2 should be copied into the
str3 one after another. The size of the array str3 should be large
enough to hold the total characters.
Example:
PROGRAM FOR CONCATENATION OF TWO STRINGS:
#include <stdio.h>
#include <conio.h>
#include <string.h>
main( )
{
int i , j , k;
static char f_str[10]={“hello”};
static char s_str[10]={“world”};
char t_str[20];
for(i=0;f_str[i]!=’/0’;i++)
t_str[i]=f_str[i];
t_str=’ ‘;
for(j=0;s_str[j]!=’/0’;j++)
t_str[i+j+1]=s_str[j];
t_str[i+j+1]=’ ‘;
printf(“%s”,t_Str);
}
Output:
hello world

STRING HANDLING FUNCTIONS:


C library supports a large number of string-handling functions that can
be used to carry out many of string manipulations like concatenation ,
comparison , copy , finding length of the given string etc.

Functio Description
ns
srlen ( ) Determines length of a string
srcpy ( ) Copies a string from source to destination
srncpy( Copies character of a string to another string upto the
) specified length.
srcmp Compares characters of two strings
()
sricmp( Compares two strings
)
srncmp( Compares characters of two strings upto specified length
)
srnicmp Compares characters of two strings upto specified length.
() Ignores case.
srlwr( ) Converts uppercase characters of a string to lowercase
srupr( ) Converts lower characters of a string to upper`
srdup( ) Duplicates a string.
strchr( ) Determines first occurrence of a given character in a string
strrchr( Determines last occurrence of a given character in a string
)
strstr ( )Determines first occurrence of a given string in another
string
strcat( ) Appends source string to destination string.
strncat( Appends source string to destination string upto specified
) length.
strrev( ) Reverses all characters of a string.
strset Sets all characters of string with a given argument or
() symbol.
strnset ( Sets specified numbers of characters of string with a given
) argument or symbol.
strspn( ) Finds upto what length two strings are identical.
strpbrk( Searches the first occurrence of the character in a given
) string and then it displays the string starting from that
character.

STRCAT( ) FUNCTION:
Syntax:

Example:
Part1=”computer ”;
Strcat(part1,”science”);
In the given syntax string1,string2 are character arrays. When
the function is executed string2 is appended to string1 by removing
null characters at the end of string1. thus in the given example the
output should be “computer science”. Thus the resultant value is
stored in part1.

STRCMP( ) FUNCTION:
Syntax:

Example:
Part1=”computer ”;
Strcmp(part1,”computer ”);
The above function compares the two given strings string1 and string2
and return value 0 if both are equal .if not it will return the numerical
difference between the mismatching characters in the strings. In the
above example it return o as a value.

STRCPY( ) FUNCTION:
Syntax:

Example:
Strcpy(part1,”science”);
In the given syntax string1,string2 are character arrays.
When the function is executed string2 is copied to string1. Thus in the
given example the output should be “science”. Thus the resultant
value is stored in part1.

STRLEN( ) FUNCTION:
Syntax:

Example:
Part1=”computer”;
N = Strlen(part1);
In the given syntax string1 is character array. When the
function is executed it counts and returns number of characters in a
string. The counting ends at the first null character. Thus in the given
example the output should be 8. Thus the resultant value is stored in
N.

USER-DEFINED FUNCTIONS:

DEFINITION:
A function is a self-contained block of code that performs a particular
task. once a function is designed and blocked it is called as ‘black-box’
that takes some data from the main program and returns value.
Example:
Printline()
{
int a;
for(a=1;a<40;a++)
printf(“=”);
printf(“\n”);
}
This example defines a function called printline that prints a line of 40
characters. The function is used in main as follows.
Main()
{
printline();
printf(“Use of C functions”);
printline();
}

Need for functions:


65.To reduce the length of the program.
66.To reduce the complexity of program.
67.Easy to debug, test and maintain.
68.To call the function wherever it is needed.

Syntax:

Working of functions
main()
{
_______
_______
abc(x,y,z); Function call

Actual argument
_______
_______
}
abc(l,k,j) Function definition
{
Formal argument
________
________
return();
}
Actual argument
The arguments of calling function are actual arguments In the
above example, ‘x’ , ‘y’ and ‘z’ are actual arguments.
Formal arguments
The arguments of called function are formal arguments. In the
above example, ‘l’ , ‘k’ and ‘j’ are formal arguments.
Function name
Here, ‘abc’ is a function name.
Argument list
Variable names enclosed within parenthesis are
called argument list.
Function call
A function can be called by its name, terminated by
a semicolon.
Example
function fact (int n1)
{
int f1;
for(i =1;i<=n1;i++)
f1=f1*i;
return(f1);
}
Suppose if the return type is integer then there is no need to
mention about the
return type in the function definition as well as in the proto type. If
the function returns non integer value then there is need for
explicit specification about the return type. The return statement
is used to return a value to the calling function. It takes the
following form
Local and Global variables
There are 2 kinds of variables.
Local variables
The local variables are defined within the body of the
function. The variable defined is local to that function only. Other
functions can not access these variables.
Global variables
Global variables are defined outside the main( ) function.
Multiple functions can use them.
local variables: Global variables:

Can be accessed only in the Can be accessed by all the


function where it has been functions in the program.
declared.
Needs to be declared inside the Needs to be declared in the global
function where it is to be used. declaration section outside all
programs.
Variables are secure. Can be used by many functions
and so are not secure.
Stored in separate locations , so Stored in one location, so any
accessing will change the value function accessing can change
only in the function where it’s its value.
used.

Example:
int m;
main( )
{
int i;
float balance;
……..
……..
function1( );
}
function1( )
{
int i;
float sum;
……
……
}
In the above example, variable m is a global variable and
can be accessed anywhere in the program where as variable i is a
local variable and should be accessed only in the function in which
it is declared. The variables balance and sum are local variables
and can be accessed in the functions main and function1
respectively.7
The Return Statement
The user defined functions uses a return statement to return the
value to the calling function. Exit from the called function to the
calling function is done by the use of a return statement. When
the return statement is executed it always returns 1.
Eg. Write a program to use a return statement in different
ways.
#include<stdio.h>
#include<conio.h>
main( )
{
int pass(int);
int x,y;
clrscr( );
printf(“ enter the value of x:”);
scanf(“%d”,&x);
if(x= =1|| x<0)
return 0;
y=pass(x);
switch(y)
{
case 1:
printf(“ The value returned is %d”,y);
break;
default:
printf(“The cube of %d is : %d”, x,y);
}
return NULL;
}
pass(a)
{
if(a = = 0)
return;
else
return(a*a*a);
}
Output:
Enter the value of x: 5
The cube of 5 is: 125

Types Of Functions:
Depending on whether the argument is present or not and
whether a value is returned or not, may belong to one of the
following categories.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.

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. So there is only a transfer of control between the
calling and the called function, but not a data transfer.

Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
add ( );
}
/* function definition*/
add()
{
int a,b;
a=a+b;
printf(“%d”,a);
return(0);
}
With Arguments but no return values:
In the previous category there is no data communication between
the functions. So this approach is not better. To make it efficiently
we could make the calling function to read data from the terminal
and pass it on to the called function. The nature of data
communication between the calling function and the called
function is with arguments but no return values.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a=2,b=3;
add (a,b);
}

/* function definition*/
add(int a1,int b1)
{
a1=a1+b1;
printf(“%d”,a1);
return;
}
The arguments that we are using in the main function are called
actual arguments. The arguments that we are using in the
called function instead of the actual arguments are called as
formal arguments.
When a function call is made, only a copy of the values of actual
arguments is passed into the called function. Changes inside the
function will have no effect on variables used in the actual
argument list.
With Arguments and return values:
In the previous category the calling function sends some data to
the called function, but the called function does not return
anything to the calling function. So it is like one-way
communication. To make it more effective, both send and receive
data in this category. If there is any change of values in called
function, it has to be shown in the main function also.

Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a,b,c;
c=add (a,b);
printf(“%d”,c);
getch();
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1;
return(a1);
}
With no arguments and return values:

Eg. Program without passing any value through main( )


#include<stdio.h>
main( )
{
int sum( ), a,s;
clrscr( );
s=sum( );
printf(“Sum =%d”, s);
return 0;
}
sum( )
{
int x,y,z;
printf(“ Enter the values”);
scanf(%d%d%d”,&x,&,&z);
return(x+y+z);
}
Output:
Enter three values: 3 5 4
Sum = 13
Call by value and Reference
There are 2 ways in which we can pass arguments to the function.
Call by value
69.Values of actual arguments are passed to the formal
arguments and the operation is done on the formal arguments.
70.Any change made in the formal argument does not affect the
actual arguments.
71.Example
/* swapping of two numbers*/
#include<stdio.h>
main( )
{
int a=3,b=4;
swap(a, b);
printf(“In main”);
printf(“a=%d, b=%d”, a, b);
getch();
}
/* function definition*/
swap(int a, int b)
{
int t;
t=a;
a=b;
b=t;
printf(“In function swap”);
printf(“a=%d, b=%d”, a, b)
}
OUTPUT
In function swap
a=4, b=3
In main
a=3, b=4
Call by Reference
72.Instead of passing value, addresses are passed.
73.Function operates on addresses rather than values.
74.Any change made in the formal argument will affect the actual
arguments.
Example
/* swapping of two numbers*/
#include<stdio.h>
main( )
{
int a=3,b=4;
swap(&a, &b);
printf(“In main”);
printf(“a=%d, b=%d”, a, b);
getch();
}
/* function definition*/
swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf(“In function swap”);
printf(“a=%d, b=%d”, a, b)
}
OUTPUT
In function swap
a=4, b=3
In main
a=4, b=3
Function Returning More values:
Eg:Write a program to return more than onevalue from a
user-defined function.
#include<stdio.h>
#include<conio.h>
main( )
{
int x,y, add, sub, change(int *, int *, int *, int *);
clrscr( );
printf(“ Enter values of X and Y:)”);
scanf(“%d%d”, &x, &y);
change(&x,&y, &add, &sub);
printf(“Addition:%d”, add);
printf(“Subtraction: %d”, sub);
return 0;
}
change(int * a, int * b, int *c, int *d)
{
*c=*a+*b;
*d= *a-*b;
}
Output:
Enter values of X and Y: 5 4
Addition:9
Subtraction: 1

Function as an argument:
Eg: Write a program to pass a user-defined function as an
argument to another function:
main ( )
{
int y=2, x;
x= double(square(y));
printf(“x=%d”, x);
}
double(m)
{
return(m*2);
}
square(k)
{
return(k*k);
}
Output:
x=8

Functions with Array and pointers


a) Initialization of an array using a function::
Like the values of simple variables, it is also possible to pass
the values of an array to a function. To pass an array to a called
function, it is enough to list the name of the array, without any
subscripts and the size of the array as arguments.
Example:
Lar(a,n);

Array size of the array


Name
/* program to find smallest element among given set of
elements*/
#include<stdio.h>
main()
{
float smallest(float,int);
static float a[5]={1.0 , 4.0 , 50.34 , 60.3 , 1.0};
printf(“%f”,smallest(a,5));
}
/* function definition*/
float smallest (float a[], int m)
{
int i;
float small;
small=a[0];
for(i=1;i<m;i++)
if (a[i]<small)
small=a[i];
return(small);
}
b) Passing array elements to a function:
Eg:
Void main( )
{
int k, show(int, int);
int num[ ] ={ 12,13,14,15,16,17,18};
clrscr( );
for (k=0;k<7;k++)
show(k, num[]);
}
show(int m, int u)
{
printf(“num[%d] = %d”, m+1,u);
}
Output:
num[1] = 12
num[2] = 13
num[3] = 14
num[4] = 15
num[5] = 16
num[6] = 17
num[7] = 18
c) Passing reverse array to a function:
Eg:
Void main( )
{
int show(int *);
int num[ ] ={ 12,13,14,15,16,17,18};
clrscr( );
show(& num[6]);
}
show(int *n)
{
int m=6;
while(m!= -1)
{
printf(“num[%d] = %d”, m,*u);
u - -, m- -;
}
return (NULL);
}
OutpUt:
num[6] = 18
num[5] = 17
num[4] = 16
num[3] = 15
num[2] = 14
num[1] = 13
num[0] = 12
d) Copying an array:
Void main( )
{
int cpy(int *, int *), h;
int a1[ ] ={ 1,2,3,4,5};
clrscr( );
cpy(&a1[0], &a2[0]);
printf(:Source Target”);
for (h=0;h<5;h++)
printf(“%d %d”, a1[h],a2[h]);
}
cpy( int * p, int *m)
{
int j=0;
while(j!=5)
{
*m =*p;
p++;
m++
j++;
}
return (NULL);
}
Output:
Source Target
1 1
2 2
3 3
4 4
5 5
e) Reading a private array:
eg: void main( )
{
int k;
in tarry( );
clrscr( );
for (k=0;k<5;k++)
{
printf(“%d”, arr( );
}
}
arry( )
{
static int k;
int b[5]={1,2,3,4,5};
return(b[k++];
}
Output:
12345
Output:
12345

Recursion:
75.Recursion is the process where a function is called repetitively
by itself.
76.The recursion can be used directly or indirectly.
Direct recursion
A function calls itself till the condition is true.
Example 1:
//program to find the factorial of a number
#include<stdio.h>
main()
{
int n;
scanf(“%d”,&n);
printf(“%d”,factorial(n));
}

factorial(int n)
{
int fact;
if(n==1)
return 1;
else
fact=n*factorial(n-1);
return(fact);
}

Steps:
1.When n=3, fact=3*factorial(2)
2.When n=2, fact=2*factorial(1)
3.When n=1, 1 is returned & control goes to step 1
where fact = 2*1=2 & control is returned to step 1
where fact = 3*2=6 & value is given to the calling
function
Indirect Recursion
A function calls another function then the called function calls the
calling function.
Example.
Void main()
{
add();
}
add()
{
static int i=0;
while (i<5)
{
i++;
main();
}
}

STORAGE CLASSES:
Purpose:
Storage classes tell the compiler the information about location and
visibility of variables.
C has four storage classes
• Automatic variables
• External variables
• Static variables
• Register variables.

Scope: Scope of a variable determines over what parts of the program


a variable is active or actually
available for use.
Longevity: Longevity refers to the period during which a variable
retains its value.

Automatic variables:
• They are declared inside the function where they are used.
• They are created when a function is called and destroyed when the
function is exited.
• They are local to the function where they are declared and so are
called local or internal variables.
• A variable declared inside a function without any storage class
specification is treated as auto by default.
• The value of an auto variable cannot be changed accidentally, so
the same name can be used in different functions.
Syntax:
Int variable name;
Or
Auto int variable name;
Example:
main()
{
int a=1000;
function2();
printf(“%d\n”,a);
}
function2()
{
int a=10;
function1();
printf(“%d\n”,a);
}
function1()
{
int a=100;
printf(“%d\n”,a);
}
Output:
100
10
1000

EXTERNAL VARIABLES:
• Variables that are both alive and active throughout the program are
external or global variables.
• They can be accessed by any function within the program.
• They are declared outside a function.
• Once a variable is declared as global any function can change its
value. Therefore these are generally used when values are to be
shared between functions.
• A global variable is visible only from the point where it is declared.
main()
{
y=5;
……
}
int y;
f1()
{
y=y+1;
}
This will cause the compiler to generate an error message since y has
not been defined in the function main.
To avoid this we use the storage class extern.
main()
{
extern int y;
……
……
}
f1()
{
extern int y;
……
……
}
• The keyword extern informs the compiler that thevariable y has
been declared somewhere and asks to perform a lookup for the
variable. The extern declaration does not allocate storage space for
the variables.
• Multiple files can share a variable provided it is declared as en
external variable (i.e) it is declared as a global variable in one file
and specified as an extern in the other.
Example:
int a;
main()
{
a=10;
function2();
printf(“%d\n”,a);
}
function2()
{
a=a*10;
function1();
printf(“%d\n”,a);
}
function1()
{
a=a*10;
printf(“%d\n”,a);
}
Output:
1000
1000
1000

STATIC VARIABLES:
• The value of static variables persist until the end of the program.
• Can be of internal or external type depending on the place of
declaration.
• Internal static variables are those that are declared inside a
function.They are similar to auto variables but are alive throughout
the entire program. They are used to retain values between function
calls.
• External static variables are those that are declared outside
functions.
• A static external variable is available only within the file where it is
declared.
• A static variable is initialized only once.
Example:
/*Static variable example*/
main()
{
int i;
for( i = 0; i<=3; i++)
{
stat();
}
}
stat()
{
static int x=0;
x=x+1;
printf(“%d\n”,x);
}
Output:
x=1
x=2
x=3

REGISTER VARIABLES:
• Register variables tells the compiler to store the value of a variable
in a register instead of the memory.
• Register access is much faster than memory access.
• Frequently used variables can be placed in the register.
• Leads to faster execution of programs.
• Most compilers allow only int and char datatype to be placed in the
register.
• C automatically converts register variables into non register
variables once the limit is reached.
Syntax:
VISIBILITY AND LIFETIME OF VARIABLES:

Storage Place of Declaration Visibility Lifetime


class
None Before all functions Entire file + other files Entire
in a file where variable is Program(Glob
declared as extern. al)
Extern Before all functions Entire file + other files Global.
in a file where variable is
declared as extern and
the file where it is
originally declared as
global.
Static(exter Before all functions Global
nal) in a file Only in that file
None or Inside a function Only in that function Until end of
auto function
Register Inside a function Only in that function Until end of
function
Static(intern Inside a function Only in that function Global
al)

POINTERS:
A pointer is a variable that contains an address which is a
location of another variable in memory.

Advantages of using pointers:


1. A pointer enables us to access a variable that is defined outside
the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of
data storage space in memory.

REPRESENTATION OF A VARIABLE:
The computer’s memory is a sequential collection of ‘storage
cells’ called as a byte. Each byte has a unique address associated
with it. Whenever a variable is declared the value will be stored in a
memory location in the given name. Thus it may have some address
the above ‘quantity’ is a variable name with the content 100 stored in
the location 5000. If we use a pointer variable for indicating this
content then the pointer variable itself contains the address 5000 as its
value. Thus pointer variable is a variable which contains the address of
another variable. Using pointer variable p the memory representation
will be as like as follows

Accessing a variable using pointers:


The address of a variable can be accessed by using the
symbol ‘&’ which is called as ‘address of ‘ the variable. In our scanf
function we use this operator to indicate the address of a variable.
Thus to assign the address of a variable to the pointer variable we can
use this operator.
Example:
p = &quantity;
Thus in the above example p is a pointer variable which holds the
address of the variable quantity.

DECLARING AND INITIALIZING POINTERS:


In C , every variable must be declared for its type. Since
pointer variables contain the address of a variable , they must be
declared before we use them. The declaration of pointer variable takes
the following
form
Syntax:

The above tells the compiler three things about the variable pt_name.
1. The asterisk (*) tells that the variable pt_name is a pointer
variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
int *p;
declares the variable p as a pointer variable that points to an integer
data type. The type int refers to the data type of the variable being
pointed to by p and not the type of the value of the pointer. Similarly
the statement
float * x;
declares x as a pointer to a floating point variable. Once a pointer has
been declared , it can be made to point to a variable using an
assignment statement such as
p = &quantity;
Thus p now contains the address of the variable quantity. This as
called pointer initialization.

ACCESSING VALUE OF A VARIABLE THROUGH POINTERS:


Once a pointer has been assigned the address of a variable ,
we can access the content using the ‘indirection operator’ (*).
Example:
int quantity, *p, n;
quantity = 100;
p = &quantity;
n = *p;
Statements Quantity p
n
5000 5010 5020

int quantity, *p, n;

quantity = 100;

p = &quantity;

n = *p;

Thus in the above example the first statement declares the pointer
variable p ,which points to integer data type. In the second statement
100 is assigned to quantity. In the third statement the address is
assigned to the pointer variable p. In the fourth statement the content
is assigned to the variable n.

POINTER EXPRESSIONS:
Like other variables, pointer variables can be used in
expressions. For example , if p1 and p2 are properly declared and
initialized pointers, then the following statements are true.
y = *p1 * *p2;
sum =sum+ *p;
p1++;
y = *p1/ *p2;
In the above the first one is to perform multiplication of the content of
p1 and p2 and assign it to y. In the second statement the content of p
is added with sum. In the third statement the address p1 is
incremented by one. The fourth statement divides the p1 by p2. There
should be a blank space between / and the indirection operator *
otherwise it is treated as a comment.

POINTER INCREMENTS AND SCALE FACTOR:


Pointers can be incremented using any of the two ways

mentioned below.

p1 = p1+1;
p1++;
provided p1 has been declared and initialized properly. If p1 is a
integer pointer in the location 2000,then the above expression causes
the pointer to move to 2002 location.
Datatype Memory locations
2000 2001 2002 2003
2004 2005
Int

Char

Float
Where

- represents Initial value and -represents value


After increment
Thus when a pointer is incremented its value is increased by the length
of the datatype that it points to> This length is called the scale
factor.

POINTERS AND ARRAYS:


When an array is declared ,the compiler allocates a base address
and sufficient amount of storage to contain all the elements of the
array in contiguous memory locations. The base address is the
location of the first element (index 0) of the array.
Suppose we declare the array x as follows:
Static int x[5]= {1,4,3,6,2};
Suppose the base address of x is 1000 and assuming each integer
requires two bytes, the first element will be stored as follows.

elements x[0] x[1] x[2] x[3] x[4]


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 a pointer , then we can make the pointer p to the
array x by the following assignment:
p=x;
That is equivalent to
p=&x[0];
Suppose if we want to access the next element then we can
increment the address by p++ to move from one element to another.
The relationship between p and x is shown below:
P= &x[0] (=1000)
P+1=&x[1] (=1002)
P+2=&x[2] (=1004)
P+3=&x[3] (=1006)
P+4=&x[4] (=1008)

The formula for calculating the effective address of ith element if

Example:
/*Program to calculate the sum of numbers in an array using
pointers*/
#include<stdio.h>
Main()

{
int x[10], *p, i, sum=0;
printf(“Enter the elements\n”);
for(i=0;i<10;i++)
scanf(“%d”,&x[i]);
p=x;
for(i=0;i<10;i++)
{
sum = sum + *p;
p++;
}
printf(“Sum = %d”,sum);
}

Pointers to two dimensional array:


0 1 2

(1,1
)
(2,0
)
(3,0 (3,2
) )

p pointer to the first row


p+i pointer to the ith row
*(p+i) pointer to first element in the ith
row
*(p+i)+j pointer to jth element in the ith
row
*(*(p+i)+j) value stored in the cell(i,j)
Example:
/*Program to find the transpose of a matrix*/

#include<stdio.h>

main()

int a[5][3],i,j;

printf(“Enter the values of the 5*3 matrix\n”);

for(i=0;i<5;i++)

for(j=0;j<3;j++)

{
scanf(“%d”,&a[i][j]);

printf(“Original Matrix\n”);

for(i=0;i<5;i++)

for(j=0;j<3;j++)

printf(“%d\t”,a[i][j]);

printf(“\n”);
}

printf(“Transpose of the original matrix\n”);

for(j=0;j<3;j++)

for(i=0;i<5;i++)

printf(“%d\t”,*(*(a+i)+j));

printf(“\n”);
}

getch();

POINTERS AND CHARACTER STRINGS:


A string is an array of characters , terminated with null
character. Like in one dimensional arrays, we can use a pointer to
access the individual characters in a string.
Example:
#include<stdio.h>
Main( )
{
char*name;
int length;
char *cptr =name;
name=”delhi”;
while (*cptr!=’\0’)
{
printf(“%c is stored at address %u”,*cptr,cptr);
cptr++;
}
length=cptr-name;
printf(“length %d”,length);
}
Thus the above program finds the length of the given string.
Pointers can also be used to handle tables of strings.
Example: Static char *name[3]={“Delhi”,”Bombay”,”Chennai”}
Declares name to be an array of three pointers to characters as shown
below
Name[0]-delhi
Name[1]-Bombay
Name[2]-Chennai
*(name[I]+j) is used to access the jth character in the ith row .
Thus
*p[3] – denotes p as an array of three pointers.
(*p)[3] – denotes p as a pointer to an array of three elements.

POINTERS AND FUNCTIONS:


The address of a variable can be passed on to a function. When

we the address to a function the parameters should be declared as


pointers of the appropriate datatype.The process of calling a function

using pointers to pass the address of a variable is known as call by

reference. The function that can be called by reference van change the

value of the variable used in the call.

Example:

#include<stdio.h>

Main()
{
int x=100,y=200;
printf(“Before exchange : x = %d y = %d\n”,x,y);
exchange(&x,&y);
printf(“After exchange : x = %d y = %d\n”,x,y);
}
exchange(int *a, *b)
{
int t;
t=*a;
*a = *b;
*b = t;
}
Output:
Before exchange : x=100 y=200
After exchange : x=200 y=100
Thus, call by reference provides a mechanism by which the function
can change the stored values in the calling function.
Note:

• The function parameters are declared as pointers and are used in


the function body.
• When a function is called, the addresses are passed as actual
parameters.
Pointers to functions:
A function also has an address in the memory. So it is possible to

declare a pointer to a function.

Syntax:
Example:

/*Program to calculate 2*x*x*/

#include<stdio.h>

void Main()

int exp(),val(),I,v;

for(I=1;I<=5;I++)

v=val(exp,I);

printf(“%d”,v);

int val(f,I)

int (*f)(),I;

return (2 * (*f)(I));

int exp(int I)
{

return(I*I);

ARRAY OF POINTERS:

Similar to an array of integers or an array of characters, we can

have an array of pointers. Since a pointer variable contains the address

of an another variable, an array of pointers contains a collection of

addresses. The addresses of array elements can be the addresses of

isolated variables or the addresses of other array elements.

Example:

/*Array of pointers to isolated variable*/

#include<stdio.h>

main()

int *arr[3],i=10,j=20,k=30,m;

arr[0]=&I;

arr[1]=&j;
arr[2]=&k;

for(m=0;m<3;m++)

printf(“%d\n”,*(arr[m]));

Output:

10

20

30

The contents and arrangement of the variables and pointers in

memory is as follows.

I j k

4008 5000 5100

arr[0] arr[1] arr[2]


7000 7002 7004

A multidimensional array can be expressed in terms of array of

pointers. Thus a two dimensional array can be declared as a series of

one dimensional arrays as follows.

Datatype *array[expression1];

In general a n-dimensional array can be declared as follows

Syntax:

Example:

/*Array of pointers to one dimensional arrays*/

#include<stdio.h>

void main()

int *p[3],I,j;

int a[]={1,2,3},b[]={4,5,6},c[]={7,8,9};

p[0]=a;

p[1]=b;

p[2]=c;
printf(“the values are…\n”);

for(I=0;I<3;I++)

for(j=0;j<3;j++)

printf(“%d”,*(p[I]+j));

In the example p is a pointer to 3 arrays. Thus p[0] has the

address of the first array a. p[1] has the base address of the second

array b and so on. The expression (p[I]+j) denotes the jth value at the

ith row. Thus (p[2]+1)represents the first element in the third array

‘c’.*(p[I]+j) represents the value at the jth column in the ith row.
Preprocessor Directives :

Introduction of Preprocessor Directives:


The steps for execution of any program:
77.C program is written in the editor.
78.Compilation
79.Linking
80.The executable code is generated.
Ø In between these stages there also involves one stage i.e
Preprocessor. One of the most important features of C language is
to offer preprocessor directives.
Ø The preprocessor is a program that processes the source
program before it is passed on to the compiler.
Ø The program typed in the editor is the source code to the
preprocessor. The preprocessor then passes the source code to
the compiler.
Ø The preprocessor is a program that processes the source
code before it passes through the compiler.
81.It operates under the preprocessor directives or preprocessor
command lines. Preprocessor directives are placed before the
main() function.
Rules:
• Preprocessor directives begin with #.
• They are placed before the main() function.
• They do not require a semicolon at the end.

The #define Directive


The syntax of #define directive is as follows:
#define identifier <substitute text>
OR
#define identifier (argument 1….. argument N)
substitute text
Example:
# define PI 3.14
This statement defines macro templates. During
preprocessing the preprocessor replaces every occurrence of PI
with 3.14 . Here PI is the Macro template and 3.14 is its macro
expansion. The macro templates are generally declared in capital
letters.
The macro definition can be terminated with semi-colon and it is
optional. The words followed by # are not keywords and the
programmer can use these words for variable names.
Program:
#include<stdio.h>
#define M 5
#define AND &&
#define EQUALS ==
void main()
{
int a=5;
printf(“Value = %d”,M*5);
}
Output:
Value = 25
Program:
#include<stdio.h>
#define CUBE(x) x*x*x
void main()
{
int a,res;
printf(“Enter value”);
scanf(“%d”,&a);
res=CUBE(a);
printf(”Result = %d\n”,res);
}
Example:
Write a program to define macros for logical operators.
#include<stdio.h>
#include<conio.h>
# define equal = =
# define larger >
void main ()
{
int a,b,c;
clrscr();
printf(“Enter three Numbers:”);
scanf(“%d %d %d “,&a,&b,&c);
if (a larger b and a larger c)
printf(“%d is the larger number “,a);
else
if(b larger a and b larger c)
printf(“%d is the larger number”,b);
else
if(c larger a and c larger b)
printf(“%d is the larger number”,c);
else
if(a equals b and b equal c)
printf(“\n Numbers are same);
}
Output:
Enter three numbers: 5 4 8
8 is the larger number
Undefining a macro:
A defined macro can be undefined, using the statement
#undef identifer
Example:
Write a program to undefined a macro.
#include<stdio.h>
#include<conio.h>
#define wait getche()
void main()
{
int k;
# undef wait getche();
clrscr();
for(k=1;k<=5;k++)
printf(“%d \t “,k);
wait;
}
Explanation:
In the above program wait is defined in place of getche() . In the
above program #undef directive undefines the same macro.
Hence the compiler flags an error message as “undefined symbol
‘wait’ in function main.”
Token pasting and Stringizing operators
Stringizing Operation:
In this operation macro argument is converted to string.
The sign # carries the operation. It is placed before the argument.
Example:
Write a program to carry out stringizing operation.
#include<stdio.h>
#include<conio.h>
#define say(m) printf(#m)
void main()
{
clrscr();
say(“HELLO”);
}
Output:
HELLO

Explanation:
In the above program after conversion the statement
say(HELLO) is treated as printf(“HELLO”) . It is not essential to
enclose the text in quotation marks in the stringizing operator.
Example:
Write a program to find the larger of the two numbers using
macro with arguments.
#include<stdio.h>
#include<conio.h>
# define MAX(x,y) if (x>y) c=x; else c=y;
void main()
{
int x=5,y=8,c;
clrscr();
MAX(x,y);
printf(“\n Larger of two numbers = %d”,c);
}
Output:
Larger of two numbers = 8
Explanation:
In the above program macro MAX() is defined with two
arguments x and y. When a macro is called, its corresponding
expression is executed and result is displayed .The expression
contains if statement that determines the largest number and
assigns it to variable c.

The # include Directive


The # include directive loads specified file in the
current program. The macros and functions of loaded file can be
called in the current program. The included file is also compiled
with current program.
The syntax is
# include “file name”or #include <filename>
where # is a symbol used with directives.
1) The filename is included in the double quotation marks which
indicates that the search for the file is made in the current
directory and in the standard directories .
Example:
Write a program to call the function defined in “udf.c” file
#include<stdio.h>
#include<conio.h>
# include “udf.c”
void main()
{
clrscr();
display();
}
Output:
Function called
Contents of udf.c file
int display();
display()
{
printf(“\n Function called”);
return0;
}
Explanation:
In the first program the “udf.c” is included .It is a user-
defined function file .It is compiled before the main program is
compiled. The complete programs along with the included one are
executed. The output of the program “Function called” is
displayed.
Conditional Compilation
The most frequently used conditional directives are:
82.#if
83.#else
84.#endif etc.
These directives allow programmer to include the portions of the
codes based on the conditions. The compiler compiles selected
portion of the source codes based on the conditions.
Syntax of #ifdef
#ifdef<identifier>
{
statement1;
statement2;
}
#else
{
statement3;
statement4;
}
#endif
The #ifdef preprocessor tests whether the identifier has
defined substitute text or not. If the identifier is defined then #if
block is compiled and executed. The compiler ignores #else block
even if errors are intentionally made. Error messages will not be
displayed . if identifier is not defined then #else block is compiled
and executed.
Example:
Write a program with conditional compilation as to whether the
identifier is defined or not.
#include<stdio.h>
#include<conio.h>
#define E =
void main()
{
int a,b,c,d;
clrscr();
#ifdef E
{
a E2;
b E 3;
printf(“A=%d &B=%d”,a,b);
}
#else
{
c=2;
d=3;
printf(“C=%d & D=%d”,c,d);
}
#endif
getche();
}
Output:
A=2 &B=3
Explanation:
The compiler search for the identifier E . The compiler
searches for the identifier E. If it is found then execution of #if
block takes place otherwise #else block. The #endif statement
indicates the end of #if-#endif block.

The #ifndef Directive


The syntax of #ifndef directive is given below
#ifndef <identifier>
{
statement 1;
statement 2;
}
#else
{
statement 3;
statement 4;
}
#endif
The #ifndef works exactly opposite to that of #ifdef. The #ifndef
preprocessor tests whether the identifier has defined substitute
text or not. If the identifier is defined then #else block is compiled
and executed and the compiler ignores #If block even if errors
are intentionally made. Error messages will not be displayed. If
identifier is not defined then #if block is compiled and executed.
Example:
Write a program to check conditional compilation directives using
#ifndef .
#include<stdio.h>
#include<conio.h>
#define T 8
void main()
{
clrscr();
#ifndef T
printf(“\n Macro is defined ,”);
#else
printf(“\n Macro is defined”);
#endif
}
Output
Macro is defined.
Explanation:
In the above program #ifndef checks for the identifier
T. If it is defined the #else block is executed. On execution of the
block the output of the program is “Macro is defined”. In case the
identifier is undefined the #else block is executed and output is
“Macro is not defined”.
The #error directive
The # error is used to display user defined message
during compilation of the program. The syntax is
# if !defined (identifier)
# error <error message>
# endif
Example:
Write a program to display user-defined error message using
#error directive.
#include<stdio.h>
#include<conio.h>
#define B 1
void main()
{
clrscr();
#if !defined(A)
#error MACRO A IS NOT DEFINED
#else
printf(“Macro found”);
#endif
}
Explanation:
In the above program identifier ‘B’ is defined. In the
absence of identifier an error is generated and the #error
directive displays the error message. The error message is user
defined and displayed in the message box at the bottom of the
editor.
The # defined directrive will work opposite to the #!defined
directive. The syntax is
# if defined
{

}
#else
# error <error message>
# endif
The #line directive
The syntax is
#line <constant> [<identifier>]
This causes the compiler to imagine the line number of
the next source line is given by <constant> and <identifier>
gives the current input file. If <identifier > is absent , then the
cuurent file name remains unchanged.
Example : # line 15 add.c
The INLINE directive
Reports the compiler that the source code has in line
‘asm’ statements. The source code will contain the assembly
code.
The #pragma SAVEREGS
It guarantees that a huge function will not modify the
value of any of the registers when it is entered. Place this
directive immediately preceding the function definition.
The #pragma DIRECTIVE
The ANSI-C and TURBO-C provide pragma directives >
these # pragma directives are defined with #(hash) and these are
the preprocessor directives. It sets/resets certain warning and
errors during compilation of C program.
Syntax:
# pragma warn +xxx
# pragma warn –xxx
ANSI Violations and #pragma

# pragma name Warning On Warning off


Hexadecimal or +big -big
octal constant too
large
Redefinition not +dup -dup
identical
Both return and +ret -ret
return of a value
used
Not part of +str -str
structure
Undefined +stu -stu
structure
Suspicious pointer +sus -sus
conversion
Void functions +voi -voi
cannot return a
value
Zero length +zst -zst
structure
Common errors and #pragma
#pragma name Warning On Warning
off
Assigned a value but never +aus -aus
used
Possible use before definition +def -def
Code has no effect +eff -eff
Parameter never used +par -par
Possibly incorrect assignment +pia -pia
Unreachable code +rch -rch
Function should return a +rvl -rvl
value
Ambiguous operators need +amb -amb
parenthesis
Less Common Errors and #pragma
#pragma name Warning On Warning Off
Superfluous & +amp -amp
with function or
array
No declaration +nod -nod
for function
Call to function +pro -pro
with no
prototype
Structure passed +stu -stu
by value
Declared but +use -use
never used

Portability Warnings and #pragma


#Pragma name Warning On Warning Off
Nonportable +apt -apt
pointer
assignment
Constant is long +cln -cln
Non-portable +cpt -cpt
pointer
comparison
Constant out of +rng -rng
range in
comparison
Non-portable +rpt -rpt
pointer
conversion
Conversion can +sig -sig
lose significant
digits
Mixing pointers +ucp -ucp
to signed and
unsigned char

Example:
Write a program to set off certain errors shown by the program
using #pragma directive
#include<stdio.h>
#include<conio.h>
#pragma warn-aus
#pragma warn-def
#pragma warn-rvl
#pragma warn-use
main ()
{
int x=2,y,z;
printf (“\n y=%d”,y);
}

Explanation:
The above program contains following warnings
85.Possible use of ‘y’ before definition in function.
86.‘Z’ is declared but never used in function main.
87.‘x’ is assigned a value which is never used in function.
88.Function should return a value in function main.
The display of these errors can be made on/off by using
the pragma options.
Standard i/o predefined Streams in Stdio.h
The predefined streams automatically opens when the program
is started.

Standard i/o predefined macros in stdio.h


Macros Function Definition in stdio.h
Stdin Standard input device #define stdin
(&streams[0])
Stdout Standard output #define stdout
device (&streams[1])
Stderr Standard error output #define stderr
device (&streams[2])
Stdaux Standard auxiliary #define stdaux
device (&streams[3])
Stdprn Standard printer #define stdprn
(&streams[4])
Example:
Write a program to enter text and display it using macro
expansions.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch[12];
int i;
clrscr();
printf(“input a text:”);
for(i=0;i<11;i++)
ch[i]=getc(&-streams[0]);
printf(“text inputted”);
for(i=0;i<11;i++)
putc(ch[i],&_streams[1]);
}
Output:
Input a text: Programming
Text input: Programming
Explanation:
In the above program instead of using macros their
corresponding macro expansion is used. The first macro
expansion &streams[0] reads string thru the keyboard and the
second &streams[1] displays it.

Predefined macros in ctype.h


Macro Returns true value if

isalpha(d) d is a letter
isupper(d) d is a capital letter
islower(d) d is a small letter
isdigit(d) d is a digit
isalnum(d) d is a letter or digit
isxdigit(d) d is a hexa decimal digit
isspace(d) d is a space
ispunct(d) d is a punctuation
Isprint(d) d is a printable character
isgraph(d) d is a printable but not a space
iscntrl(d) d is a control character
isascii(d) d is an ascii code

DYNAMIC MEMORY ALLOCATION:

C requires the number of elements to be specified at the compile

time. Sometimes our initial judgement of the size of the arrays may be

wrong (i.e) space may be wasted or more space will be required . To

avoid such problems C allows the user to specify the size of the array

at run time. This is called dynamic memory management. Thus the

process of allocating memory at run time is known as dynamic memory

allocation.C uses four library functions to support dynamic memory

allocation. They are

• Malloc – allocates requested size of bytes and returns a pointer to


the first byte of the allocated space.
• Calloc – allocates space for an array, initializes them to zero and
then returns a pointer to the memory.
• Free – frees previously allocated memory.
• Realloc – modifies the size of the previously allocated array.

Storage of a C program

Stack

Heap
Permanent storage area

The global variables and the instructions are stored in the

permanent storage area. Local variables are stored in the stack. The

free region is called the heap and is used for dynamic memory

allocation. The heap keeps changing when the program is executed

when the variables are created and destroyed. Therefore memory

overflows can occur. In that case the memory allocation processes

returns a NULL pointer to denote a failure to allocate the requested

memory space.

Malloc():

A block of mamory can be allocated using malloc() function. This

allocates a block of the specified size and returns a void pointer.

Syntax:

Example:

X=(int *)malloc(100 * sizeof(int));

This statement allocates a memory space equivalent to 100 times the


size of an int and returns the address of the first byte to the pointer x.

If the function cannot allocate memory it returns a NULL pointer.

Calloc():

Calloc() allocates multiple blocks of storage each of the same

size and initializes them to 0.

Syntax:

Example:

……..

……..

struct student

char name[25];

float age;

long int id;

};

typedef struct student record;

record *st_ptr;
int class=30;

……..

……..

st_ptr=(record*)calloc(class,sizeof(record));

Free():

With dynamic allocation, the user has to release the memory

when it is not used. This is important when the storage space is

limited. The function Free() releases the memory.

Syntax:

Example:

Free(p);

Realloc():

There are 2 cases when we require to realter the memory

already allocated

1. When the previously allocated memory is not sufficient and the user
requires additional space.
2. When the memory allocated is larger and the user wishes to reduce
it.
In both the cases the memory size can be changed with the use of
realloc().

Syntax:

This function allocates a new memory space of size new-size to

the pointer variable ptr and returns a pointer to the first byte of the

new memory block if the memory allocation operation is successful.

The newsize may be smaller or larger than the original size. The

realloc() function does not modify the original contents. If the function

fails in allocating the required space, then it returns a NULL pointer

and the origunal block is lost.

Program:

/*Program to access a 2 dimensional array using malloc()*/

void main()

int *p[3], I, j,c;

printf(“Enter the no of cols\n”,&c);

p[0]=(int*)malloc(c*sizeof(int));

p[1]=(int*)malloc(c*sizeof(int)); allocates space for c

cols
p[2]=(int*)malloc(c*sizeof(int));

for(I=0;I<3;I++)

for(j=0;j<c;j++)

scanf(“%d”,(p[I]+j));

printf(“The elements are…..\n”);

for(I=0;I<3;I++)

for(j=0;j<c;j++)

printf(“%d”,*(p[I]+j));

Suggested Questions
Section A

89.How many values a function can return?


90.If white space characters are present within a control string ,
How they are treated?
91.Can the names of formal parameters coincide with actual
parameters?
92.Can multiple return statements be included in a function?
93.What is a null statement? Explain its usefulness.
94.Write the syntax of goto statement.
95.Write the purpose of break and continue statement.
96.Explain and give example for predefined functions.
97.Write the disadvantages of using goto statement.
98.Write the advantages of using user defined functions.
99.In what way ,a switch statement differ from an if statement?
100.Say true or false:
• when if statements are nested, the last else gets
associated with the nearest if without an else.
• One if can have more than one else clause.
• A switch statement can always be replaced by a series
of if..else statements.
• A switch expression can be of any type
• A program stops its execution when a break statement
is encountered.
101.How the end of the string is recognized?
102.Explain the need for array variables.
103.Declaration int a[10][10] creates how many elements.
104.What is the value returned by a strcmp() function?
105.Define array.
106.Identify errors,if any, in each of the following array declaration
statements.
• Float values [10,13]
• Char name[ROW],[COLUMN];
107.Identify errors ,if any ,in each of the following initialization
statements.
• Static int number[ ]={0,0,0,0,}
• Static char word[ ]={‘a’,’rr’,’r’,’y’};
108.Define string.
109.Write the common operations performed on character strings.
110.Write the purpose of getchar function.
111.Write the purpose of putchar function.
112.Write the function to convert the given string to integer .
113.Which function is used to convert the given integer value to
string?
114.Write any four string handling functions.
115.Describe the limitations of using getchar and scanf functions for
reading strings.
116.What is recursive function?
117.What happens when actual arguments are less than formal
arguments in a function?
118.What happens when data type of one of the actual arguments
does not match with the type of the function.
119.What happens when same variable is used in two different
functions?
120.Say true or false
• Function should be arranged in the order in which they
are called.
• We can pass any number of arguments to a function.
• A function in c should have atleast one argument.
121.What are the different storage classes?

Section –B
122.Write short notes on functions
123.Differentiate local and global variables
124.Write short notes on different types of arguments
125.Explain string handling functions in detail with examples.
126.Write a program which will read a text and count all
occurrences of a particular word.
127.Explain the usage of break & continue statement
128.Write short notes on conditional operatorWrite short notes
on multidimensional arrays
129.Write a program to search an element using linear search.
130.Write a program to sort the given set elements using
selection sort
131.Write a program to arrange the given set of element using
ascending order.
132.Write a program to arrange the given set numbers in
descending order.
133.Write a program to add two given matrices of order m x n
134.Explain about switch statement
135.Distinguish between local and global variables
136.Distinguish between formal and actual arguments.
137.Distinguish between automatic and static variables.
138.Distinguish between global and extern variables.
139.Is the main user defined function? If yes means how it differs
from the other user defined functions?
140.Write a program to calculate npr using user defined function.
141.Write a recursive program to generate fibonacci nubers
142.Write shorts notes on auto storage class
143.Explain about register & extern variables
144.Write a recursive program to calculate the factorial of a
given number.
145.Write a program to find if a string is a palindrome or not.

Section –C
146.Explain recursion with an example
147.Explain about user defined functions
148.Write a program to sort a set of numbers and to print
minimum & maximum
of the set
149.Explain multidimentional arrays.
150.Write a program to find sum of positive & negative real
numbers seperately
from a given set of real numbers using continue and while
statement
151.Explain any 4 string functions with examples
152.Discuss on different storage classes
8. Write a program to print the set of names in alphabetical
order
9. Write a program to count the number of palindromes in a
given text.
153.Write a program to sort a list of names in alphabetical order.
154.Write notes on one dimensional array with relevant example.
155.Write notes on two dimensional arrays with examples.
156.Write a program to multiply 2 matrices.
157.Write a program to find the transpose of a matrix

Section D
1. Explain functions with suitable example and write a program
for NCR using
Functions
2. Explain arrays with relevant examples.
3. Explain strings with relevant examples.
4. Explain the various storage classes
5. Write notes on two dimensional arrays. How will you multiply
2 matrices.
6. Write a program to sort out a list of n names in bith ascending
and descending order.

STUDY MATERIAL

COURSE : II YEAR A, B.Sc ECS


SEMESTER : III
UNIT : IV
SUBJECT NAME : PROGRAMMING IN C
LECTURER NAME : D.MYTHILI
NUMBER OF PAGES : 18
DATE OF ISSUE :

Unit-IV
Structure and Union: Features of structure, Declaration and
initialization of structure, Structure within structure, Array of structure,
Pointer to structure, Bit fields, Union.

STRUCTURES AND UNIONS:


Structure is a constructed data type for packing data of different

types. It is a convenient tool for handling a group of logically related

data items.

Advantages:
1. Structures enable the user to group together a collection of different

data items of different data types using a single name.

2. Structures help to organize complex data in a more meaningful way.


Example:
A structure can be used to represent a student’s details such as

student_name, rollno, marks etc as follows

Struct student
{
char stud_name[20];
char stud_rollno[10];
float stud_mark1;
float stud_mark2;
float stud_mark3;
};

STRUCTURE DEFINITION:
A structure definition creates a format that may be used to
declare structure variables.
General format for structure definition is as follows:

Example:
Struct book_bank name of the structure
or structure tag
{
char title[20];
char author[15]; structure elements or members
int pages;
float price;
};
struct book_bank b1,b2,b3; structure variables
In the above example book_bank is a tag-name which is optional

one. If you give the tag-name then later in the program you can

declare the variables using the given tag-name otherwise it is not

possible. The title, author, pages and price are members of the

structure. While defining the structure memory is not allocated for its

members. Only during the declaration the memory is allocated for the

members. Thus the structure definition creates a template to represent

a group of logically related information. In the structure definition you

should follow the rules stated below

1. The template is terminated with semicolon.


2.While the entire declaration is considered as a statement, each
member is
declared independently for its name and type in a separate
statement inside
the template.
3. The tag name such as book_bank can be used to declare structure
variables of
its type later in the program.
There are 2 ways in which we can declare a structure.
1.The user can combine the template declaration and the variable
declaration in a single statement as follows
Struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}book1,book2,book3;
2.The use of tag name is optional as follows
Struct
{
char title[20];
char author[15];
int pages;
float price;
}book1,book2,book3;

GIVING VALUES TO MEMBERS:


We can assign values to members of a structure. The structure
members themselves are not variables. They should be linked to the
structure variables in order to make them meaningful members. For
example the word title, has no meaning when it appears alone. The
same structure member when it appears with the structure variable
book1 as book1’s title has a meaning. The link between a structure
member and a structure variable is established using the member
operator ‘.’, which is also called as “dot operator” or “period operator”.
Thus we can assign a value to the member using dot operator like as
follows
b1.price=150.00;
b2.title=”c programming”;
The same dot operator can be used to assign values to the

structure members through the keyboard as follows

Scanf(“%s”,book1.title);
Example:
/*Program to illustrate the dot operator*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}student1;
void main()
{
printf(“Enter student details\n”);
printf(“\nStudent Name : “);
scanf(“%s”,student1.stud_name);
printf(“\nRoll no : “);
scanf(“%s”,student1.stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&student.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&student.mark2);
printf(“\nMark3 : “);
scanf(“%f”,&student.mark3);
student1.tot = student1.mark1 + student1.mark2 +
student1.mark3;
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,student1.stud_name);
printf(“Roll no : %s\n”,student1.stud_rollno);
printf(“Marks : %f %f
%f\n”,student1.mark1,student1.mark2,student1.mark3);
printf(“Total : %f\n”,student1.tot);
}

STRUCTURE INITIALIZATION:
Like any other type, a structure variable can be initialized.
However, a structure must be declared as static if it is to be initialized
inside a function.
Example:
main( )
static struct
{
int weight;
float height;
}student={100,150.45};
……………………..
……………………..
}
Thus in the above the value 100 to student.weight and 150.45 to
student.height. There is a one- to-one correspondence between the
members and their initializing values.
A variation in initializing a structure is as follows:
Main( )
{
struct st_record
{
int weight;
float weight;
};
static struct st_record stu1={30,70.56};
static struct st_record stu2={45,65.73};
……………
……………
}
Another variation in initializing structure variable outside the function
is as follows:
struct stu
{
int weight;
float height;
}stu1={56,170.56};
main()
{
static struct stu student2 = {23,150.5};
………………..
………………..
}

COMPARISON OF STRUCTURES:
Two variables of same structure type can be compared in the
same way as ordinary variables. If book1 and book2 are of same type
then it is possible to compare two variables as book1== book2.
similarly we can assign book2 to book1 as book1=book2.etc.
Example:
/*Program to illustrate comparison and copying of structure
variables*/
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}
void main()
{
static struct student s1={“aaa”,”00CS0001”,50,50,50};
static struct student s2,s3={“bbb”,”00CS002”,20,90,30};
s2=s1; //assigns structure s1’s contents to structure
s2
if(s2 = = s1) //compares structure s2 and s1

printf(“Both the persons are the same\n”);


if(s2 = = s3)
printf(“Both the persons are the same”);
else
printf(“Both he persons are different”);
if(s2.mark1 = = s3.mark1) //compares structure
elements
printf(“Student 1 and 2’s marks are the same\n”);
else
printf(“Marks are different\n”);
}

ARRAYS OF STRUCTURES:
We use structures to describe the format of a number of related
variables. For example if we want to analyse the marks obtained by a
class of students then we can use array of structures.
Example:
/*Program to illustrate arrays of structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
};
void main()
{
static struct student s[3];
int I;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&s[I].mark1);
printf(“\nMark2 : “);
scanf(“%f”,&s[I].mark2);
printf(“\nMark3 : “);
scanf(“%f”,&s[I].mark3);
s[I].tot = s[I].mark1 + s[I].mark2 + s[I].mark3;
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Marks : %f %f
%f\n”,s[I].mark1,s[I].mark2,s[I].mark3);
printf(“Total : %f\n”,s[I].tot);
}
}
The above example declares a structure with 6 members. Also
we have declared s to be an array consisting of 3 members of type

struct student. Each individual element is accessed using the dot

operator. Thus the details of the first student can be represented as

follows

S[1].stud_name

S[1].stud_rollno etc.

ARRAYS WITHIN STRUCTURES:


C permits the use of arrays as structure members. In the
previous example we have declared three variables
mark1,mark2,mark3. We can eliminate this by using an array to hold
the 3 marks. Thus the declaration will be as like as follows.
struct student
{
char stud_name[25];
char stud_rollno[10];
float marks[3];
}s[3];
Thus in the above example student contains 3 elements -
stud_name, stud_rollno, and an array of 3 marks. The marks can be
accessed as stu[2].marks[1]. Thus it refers to the mark obtained in the
first subject by the second student.
Example:
/*Arrays within structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float marks[3],tot;
};
void main()
{
static struct student s[3];
int I,j;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
s[I].tot=0;
for(j=0;j<3;j++)
{
printf(“\nMark%d : “,j);
scanf(“%f”,&s[I].marks[j]);
s[I].tot = s[I].marks[j];
}
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
for(j=0;j<3;j++)
{
printf(“Mark%d : %f \n”,j,s[I].marks[j]);
}
printf(“Total : %f\n”,s[I].tot);
}
}

STRUCTURES WITHIN STRUCTURES:


Structures within the structure means nesting of structures.
Nesting of structures is permitted in c. Let us consider the following
structure definition to store the information about the student.
Struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3;
float tot;
};
The above structure defines student name, rollno,and the maks
of the student. We can group the marks into one sub structure as
follows:
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
}s[3];
The individual marks of the second student are referred as
s[2].m.mark1.
Example:
/*Structures within structures*/
#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
};
void main()
{
static struct student s[3];
int I,j;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
s[I].tot=0;
printf(“\nMark1 : “);
scanf(“%f”,&s[I].m.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&s[I].m.mark2);
printf(“\nMark3 : “);
scanf(“%f”,&s[I].m.mark3);
s[I].tot = s[I].m.mark1+s[I].m.mark2+s[I].m.mark3;
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Mark1 : %f \n”,s[I].m.mark1);
printf(“Mark2 : %f\n”,s[I].m.mark2);
printf(“Mark3 : %f\n”,s[I].m.mark3);
printf(“Total : %f\n”,s[I].tot);
}
}

STRUCTURES AND FUNCTIONS:


C supports passing structure values as arguments to a function.
There are three methods by which the values of the structure are
passed to a function.
1.Each member of the structure is passed as an actual argument.
2.A copy of the entire structure is passed.
3.Pointers are used to pass the structure as an argument to a function.
1.Passing each member of the structure:
In this method each member of the structure is passed as actual

arguments to the function. This method treats the structure members

as ordinary variables. This is the most simplest method and is efficient

when the size of the structure is small.

Disadvantages:
1.The method becomes unmanageable when the structure size is

large.

Example:

/*passing structure members to a function*/

#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
};
void main()
{
float total(float,float,float);
static struct student s[3]={{“aaa”,”00CS001”,40,50,60},
{“bbb”,”00CS002”,20,30,40},
{“ccc”,”00CS003”,10,70,50}}
for(I=0;I<3;I++)
{
s[I].tot =
total(s[I].m.mark1,s[I].m.mark2,s[I].m.mark3);
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Mark1 : %f \n”,s[I].m.mark1);
printf(“Mark2 : %f\n”,s[I].m.mark2);
printf(“Mark3 : %f\n”,s[I].m.mark3);
printf(“Total : %f\n”,s[I].tot);
}
}

float total(float a,b,c)

return(a+b+c);

2.Passing a copy of the entire structure to the function:

This method passes the entire structure as an argument to the

function. So the formal arguments in the function should be declared

as a structure type variable.


Disadvantage:

1.This method works on the copy of the structure. So any changes

made to the original structure is not reflected. Therefore it is necessary

to return the structure.

Example:

/*passing entire structure to a function*/

#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1,mark2,mark3;
}m;
float tot;
};
void main() (struct student is the return type)
{
struct student total(struct student);
static struct student s[3]={{“aaa”,”00CS001”,40,50,60},
{“bbb”,”00CS002”,20,30,40},
{“ccc”,”00CS003”,10,70,50}}
static struct student s1[3];
for(I=0;I<3;I++)
{
s1[I] = total(s[I]); passing the structure as a
parameter
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s1[I].stud_name);
printf(“Roll no : %s\n”,s1[I].stud_rollno);
printf(“Mark1 : %f \n”,s1[I].m.mark1);
printf(“Mark2 : %f\n”,s1[I].m.mark2);
printf(“Mark3 : %f\n”,s1[I].m.mark3);
printf(“Total : %f\n”,s1[I].tot);
}
}

struct student total(struct student a)

a.tot = a.m.mark1 + a.m.mark2 + a.m.mark3;

return(a);

3.Using pointers to pass a structure as an argument:

This method uses the concept of pointers to pass the structure

as an argument to a function.(ie) the address location of the pointer is

passes to the function. The function can access indirectly the entire

structure and can work on it.

Advantages:

1.If is more efficient because any changes is reflected in the original

structure.

The members of the structure can be accessed through 2 ways.

• Arrow operator.(->)
• Member operator.(.)
Example:

/*use of pointers to pass a structure as an argument to a

function*/
#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
};
void main()
{
void total(struct student *p);
static struct student s={“aaa”,”00CS001”,40,50,60},*ptr;
ptr=&s;
total(ptr);
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,ptr->stud_name);
printf(“Roll no : %s\n”,(*ptr).stud_rollno);
printf(“Mark1 : %f \n”,ptr->m->mark1);
printf(“Mark2 : %f\n”,ptr->m->mark2);
printf(“Mark3 : %f\n”,ptr->m->mark3);
printf(“Total : %f\n”,(*ptr).tot);
}

void total(struct student *a)

a->tot = a->m->mark1 + a->m->mark2 + a->m->mark3;

Rules:

• The called function must be declared for its type, appropriate to the
data type it must return. For example if the function is returning a
copy of the entire structure, then it must be declared as struct with
an appropriate tag name.
• The structure variable used as the actual argument and the formal
argument 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.

UNIONS:
Unions are the concept derived from structure . So the definition
of union is same as structure except with the keyword union. The main
difference between the structure and the union is in the memory
allocation only. In structure the memory is allocated for all the
members included within the structure and all can be accessed
simultaneously. In union the memory is allocated for the longest
member in the union. So that all the members in the union can share
the allocated memory one at a time.
Example:
Union product
{
int quantity;
float price;
char code;
}p1;
In the above the memory is allocated based on the longest data

type float. Thus 4 bytes will be allocated and that memory is shared by

all members in the union.

Example:
/unions example*/
void main()
{
union samp
{
char color;
int size;
}shirt;
shirt.color=’r’;
printf(“%c\n”,shirt.color);
shirt.size=12;
printf(“%d\n”,shirt.size);
}
Thus at a time only one member can be accessed. If we have a
statement as follows
shirt.size=12;
printf(“%d %c\n”, shirt.size, shirt.color);
Then the output will be
158.garbage character

BIT FIELDS:
There are occasions where data items require much less space
than the allocated space. C allows the user to use small bit fields to
hold data items and thereby to pack several data items in a word of
memory. A bit field is a set of adjacent bits whose size can be from 1 to
16 bits in length. The name and size of bit fields are defined using a
structure.
159.Bi t field provides exact amount of bits required for storage of
values. If a variable value is 1 or 0 we need a single bit to store it.
160.The variable is expressed between 0 and 3, then the two bits are
sufficient for storing these values.
161.Similarly if a variable assumes value between 0 and 7 then three
bits will be sufficient to hold the variable and so on.
162.The number of bits required for a variable is specified by non-
negative integer followed by colon.
163.To hold the information we use the variable. The variables occupy
a minimum of one byte for char and two bytes for integer.
164.The information about the vehicle, following information has to
be stored in the memory.
165.Petrol vehicle
166.Diesel vehicle
167.Two wheeler vehicle
168.Four wheeler vehicle
169.Old model
170.New model
In order to store the status of the above information we may need two
bits for types of rules as to whether the vehicle is of petrol or diesel
type.
Three bits for its type as to whether the vehicle is two or four wheeler.
There are restricted on bit fields when array are used. Array of bit
fields are not permitted.
The pointer cannot be used for addressing the bit field directly,
although the use of the member access operator (à) is acceptable.
The structure for the above problem would be as follows

Struct vehicle
{
Unsigned type:3;
Unsigned fuel:2;
Unsigned model:3;
};
The colon (;) in the above declaration tells to the compiler that bit
fields are used in the structure and the number after it indicates how
many bits are required to allot to the field.
Example:
Write a program to store the information of vehicle. Use bit
fields to store the status of information.
#include <stdio.h>
#include <conio.h>
#define PETROL 1
#define DIESEL 2
#define TWO_WE 3
#define FOUR_WE 4
#define OLD 5
#define NEW 6
Void main()
{
Struct vehicle
{
Unsigned type:3;
Unsigned fuel:2;
Unsigned model:3;
};
Struct vehicle v;
v.type=FOUR_WE;
v.fuel=DIESEL;
v.model=OLD;
clrscr();
printf(“\ntype of vehicle:%d”,v.type);
printf(“\nfuel:%d”,v.fuel);
printf(“\nmodel:%d”,v.model);
}
OUTPUT:
Type of vehicle:4
Fuel: 2
Model:5
Explanation: In the above program using #define macros are
declared. The information about the vehicle is indicated between
integer 1 to 6. The structure vehicle is declared with bit field. The
number of bits required for each member is initialized. As per the
program for type of vehicle requires 3bit, fuel requires 2 bits and
model requires 3 bits. An object v is declared. Using the object bit
fields are initialized with data.

Format:
Thedatetype can either be signed or unsigned int and the bit_length

specifies the number of bits.

Rules:

• The first field always starts with the first bit of the word.
• The sum of all the fields in the structure should not be more than
the size of a word.
• There can be unnamed fields declared with size
Example: unsigned :2;

Such fields provide padding within word.

• There can be unused bits in a word.


• We cannot take address of a bit field variable(ie)we cannot read
values into bit field variables nor can we use pointers to access
them.
• Bit fields cannot be arrayed.
• Bit fields should be assigned values within their range.
Example:

Main()

struct num

unsigned a:1;

unsigned b:2;
unsigned c:3;

unsigned d:6;

}n;

n.a=0;

n.b=2;

n.c=4;

n.d=14;

printf(“%d %d %d %d\n”,n.a,n.b,n.c,n.d);

Output:

0 2 4 14

Suggested Questions :

171.What is structure and Union. What is the difference

between Them.

172. Explain structure with pointers.

173.Describe structure with suitable examples.

174.Explain union with suitable examples.

175.Explain Bit fields.


STUDY MATERIAL

COURSE : II YEAR A, B.Sc ECS


SEMESTER : III
UNIT : V
SUBJECT NAME : PROGRAMMING IN C
LECTURER NAME : D.MYTHILI
NUMBER OF PAGES : 16
DATE OF ISSUE :

Unit-V

Files: Streams and file types, Steps for file operation, File I/O,
Structures read and write, other file functions, Command line
arguments, I/O redirection

CONSOLE ORIENTED I/O:


Console oriented I/o functions are the functions that use the
terminal as the target place.
Example: printf(),scanf()
Problems in console oriented i/o operations:
1. It becomes difficult and time consuming to handle large
volumes of data through terminals.
2. The entire data is lost when either the program is
terminated or the computer is turned off.

FILE:
A file is a place on disk where a group of related data is
stored.

BASIC FILE OPERATIONS:


1. naming a file
2. opening a file
3. reading data from a file
4. writing data to a file
5. closing a file.

There are 2 ways to perform operations on a file


a. low level i/o use UNIX system calls
b. high level i/o use C’s standard library functions.

HIGH LEVEL I/O FUNCTIONS:


Function Operation
name
fopen( ) creates a new file or opens an existing
file for use
fclose( ) closes a file which has been opened for
use
getc( ) reads a character from a file
putc ( ) writes a character to a file
fprintf( ) writes a set of data values to a file
fscanf( ) reads a set of data values to a file
getw( ) reads an integer from a file
putw( ) writes an integer to a file
fseek( ) sets the position to a desired point in
the file
ftell( ) gives the current position in the file
rewind( ) sets the position to the beginning of the
file
DEFINING AND OPENING A FILE:
While opening a file we should include the following :
176.filename
177.data structure
178.purpose
The filename is a string of characters and should be a valid one. It
has 2 parts
1. a primary name
2. an optional period with the extension.

Example: input.data
Data structure is defined as FILE in the standard I/O library. So all
files should be declared as type FILE (defined data type).
Purpose may any one of the following .
• read ( r )
• write ( w )
• append ( a )

GENERAL FORMAT FOR DEFINING A FILE :

The mode is any one of the below type


“r” - open the file for reading only
“w” - open the file for writing only
“a” - open the file for appending (or adding ) data to it.
When trying to open a file , one of the following things should be
noted:
a. when the mode is ‘writing ‘, a file with the specified name is
created if the file does not exist. The contents are deleted, if they
already exist.
b. when the purpose is ‘appending’ , the file is opened with the
current content safe . a file with specified name is created if the
file does not exist.
c. if the purpose is ‘reading’, and if it exists, then the file is
opened with the
current contents safe; otherwise an error occurs.
Many recent compilers include additional modes of operation:
R+ - the existing file is opened for both reading and
writing.
W+ - same as w except both for reading and writing.
A+ - same as a except for both reading and writing.

CLOSING A FILE:
A file must be closed as soon as all operations on it have
been completed. This ensures that all outstanding information
associated with the file is flushed out from buffers and all links to
the files are broken. It also prevents any accidental misuse of the
file. Another instance where we have to close a file is when we
want to reopen the same file in a different mode.

SYNTAX:

Example:
FILE * p1, * p2;
p1=fopen(“input”,”w”);
p2=fopen(“output”,”w”);
---------------------------
fclose(p1);
fclose(p2);
---------------------------

INPUT OUTPUT OPERATIONS ON FILES:

Function Operation
name
fopen( creates a new file or opens an existing
) file for use
fclose( closes a file which has been opened for
) use
getc( ) reads a character from a file
putc ( ) writes a character to a file
fprintf( writes a set of data values to a file
)
fscanf( reads a set of data values to a file
)
getw( ) reads an integer from a file
putw( ) writes an integer to a file
fseek( ) sets the position to a desired point in
the file
ftell( ) gives the current position in the file
rewind( sets the position to the beginning of the
) file

To manipulate on character data we use getc() and putc()


functions.

SYNTAX:

getc( ):
To read a character from a file.
putc( ):
To write a character to a file.

Example:
char a,b=’b’;
FILE *f1, *f2;
……
a=getc(f1);
…….
Putc(b,f2);

Program :
# include <stdio.h>
main ( )
{
FILE *f1;
char c;
printf(“data input \n”);
f1=fopen(“input”,”w”); /* open the file input*/
while ((c=getchar( ))!=EOF) /*get a character from keyboard */
putc (c, f1); /*write a character to input */
fclose(f1); /*close the file input */
printf(“\n data output \n\n”);
f1=fopen(“input”,”r”); /*reopen the file input */
while ((c=getc(f1))!=EOF) /*read a character from input */
printf(“%c”,c); /*display a character on screen */
fclose(f1); /*close the file input */
}

To manipulate an integer value we can use getw and putw


functions.

SYNTAX:

getw( ):
To read an integer from a file.
putw( ):
To write an integer to a file.
Example:
int a,b=10;
FILE *f1, *f2;
……
a=getw(f1);
…….
Putw(b,f2);
Program :
# include <stdio.h>
main ( )
{
FILE *f1;
Int i,c;
printf(“data input \n”);
F1=fopen(“input”,”w”); /* open the file input*/
For (i=1;i<=10;i++)
Scanf(“%d”,&c)
If (c==-1) break;
putw (c, f1); /*write a number to input */
fclose(f1); /*close the file input */
printf(“\n data output \n\n”);
f1=fopen(“input”,”r”); /*reopen the file input */
while ((c=getw(f1))!=EOF) /*read a number from input */
printf(“%d”,c); /*display the number on screen
*/
fclose(f1); /*close the file input */
}

To handle a group of mixed data simultaneously we can use


fprintf and fscanf functions.
SYNTAX:

fscanf( ):
To read a group of data from a file.
fprintf( ):
To write a group of data to a file.
Example:
char a,b=’b’;
int c,d=10;
FILE *f1, *f2;
……
fscanf(f1,“%d %c”,&c,&a);
…….
fprintf(f2,”%d %c”,d,b);

Program:
# include <stdio.h>
main ( )
{
FILE *f1;
char name[10];
int roll;
printf(“data input \n”);
f1=fopen(“input”,”w”); /* open the file input*/
scanf(“%s %d”,name,&roll); /*get a group of data from
keyboard */
fprintf(f1,”%s %d”,name,roll); /*write a character to input */
fclose(f1); /*close the file input */
printf(“\n data output \n\n”);
f1=fopen(“input”,”r”); /*reopen the file input */
fscanf (f1,”%s %d”,name,&roll); /*read data from input */
printf(“%s %d”,name,roll); /*display data on screen
*/
fclose(f1); /*close the file input */
}

ERROR HANDLING DURING I/O OPERATIONS:


It is possible that an error may occur during i/o operations on a file.
Typical error situations include:
1. trying to read beyond the end –of-file.
2. device overflow.
3. trying to use a file that has not been opened.
4. trying to perform an operation on a file, when the file is
opened for another type of operation.
5. opening the file with an invalid name.
6. attempting to write to a write-protected file.
If we fail to check such read and write errors, a program may behave
abnormally when an error occurs. Two different types of library
functions for error handling are feof( ) and ferror( ).

SYNTAX:

feof( ):
It is used to test for end of file condition. It takes the file pointer
as the only argument and returns a nonzero integer value if all of the
data from specified file has been read, and returns zero otherwise.

Example:
If (feof(fp))
Printf(“end of data”);

ferror( ):
This function reports the status of the file indicated. It takes a file
pointer as its argument and returns nonzero integer if an error
has been detected or returns a zero otherwise.
Example:
If ( ferror(fp)!=0)
Printf(“an error has occurred”);

Program:
#include<stdio.h>
void main()
{
FILE *f1;
Char filename[10];
Int a,b,i;
F1=fopen(“TEST”,”w”);
For(I=0;I<10;I++)
{
scanf(“%d”,&a);
putw(a,f1);
}
fclose(f1);
x: printf(“Enter the filename);
Scanf(“%s”,filename);
If((f1=fopen(filename,”r”))==NULL)
{
printf(“Invalid file name\n”);
goto x;
}
else
{
while(feof(f1)==0)
{
b=getw(f1);
printf(“%d\n”,b+10);
}
}
fclose(f1);
}

RANDOM ACCESS TO FILES:


Sometimes we might want to access only particular parts of
a file rather than the whole file. In that case we use the 3
functions fseek(),ftell(),rewind() in the C I/O library.

ftell():
The function ftell() gives the current position of a file. It
takes a file pointer as an argument and returns a type long that
corresponds to the current position.
SYNTAX:

rewind():
The function rewind() moves the pointer to the start of the
file. It takes a file pointer as an argument and moves the pointer
to the start of the file.
SYNTAX:

Example:
FILE *f1;
……
rewind(f1);
n=ftell(f1);
Now n will have a value of 0 ( the start of the file).

Advantages of rewind():
Helps to read a file more than once without having to open and
close it.

fseek():
This function is used to move to the desired position in the
file. It takes 3 arguments.
1. file pointer – pointer to the concerned
file.
2. Offset – specifies the number of
positions(bytes) to be moved.
3. Position – position takes one of the 3
values
179.0 – start of file.
180.1 – current position
181.2 – end of file.
Example:
fseek(fp,0L,0) – go to the beginning of the file.
fseek(fp,0L,2) – go to the end of the file.
fseek(fp,0L,1) – stay in the current position.
fseek(fp,m,0) – move to m+1th byte.
fseek(fp,m,1) – go forward by m bytes.
fseek(fp,-m,1) – go backwards by m bytes.

Program:
#include<stdio.h>
void main()
{
FILE *f1;
Long n;
F1=fopen(“test”,”w”);
While((c=getchar())!=EOF)
Putc(c,f1); //writes characters
into the file.
Printf(“No of characters %ld\n”,ftell(f1); //gives the current
position of the //pointer in the file
Fclose(f1);
Fp=fopen(“test”,”r”);
N=0L;
While(feof(f1)==0) //moves the
position by 5 bytes.
{
fseek(f1,n,0);
printf(“Current position %ld current character
%c\n”,ftell(f1),getc(f1));
n=n+5L;
}
fseek(f1,-1L,2) //moves to the last
character
do //prints the file in
reverse
{
printf(“%c”,getc(f1));
}while(!fseek(f1,-2L,1);
fclose(f1);
}

C PREPROCESSOR DIRECTIVES:
The preprocessor is a program that processes the source
code before it passes through the compiler. It operates under the
preprocessor directives or preprocessor command lines.
Preprocessor directives are placed before the main() function.
Rules:
• Preprocessor directives begin with #.
• They are placed before the main() function.
• They do not require a semicolon at the end.
Categories:
1. Macro substitution directives
2. File inclusion directives
3. Compiler control directives

Macro substitution:
Macro substitution is a process where an identifier in a
program is replaced by a predefined string composed of one or
more tokens. The processor accomplishes this task by using
#define statement. This statement is known as a macro definition.
SYNTAX:

There is no space in between the # and define. Identifier should


be in capital letters. String value may be a constant , expression
or another macro call.

Different forms of macro substitution are as follows:


1. Simple macro substitution
2. Argumented macro substitution
3. Nested macro substitution

SIMPLE MACRO SUBSTITUTION:


Simple string is commonly used to define constants.
Example:
#define COUNT 100 /* 100 is assigned to
COUNT*/
#define CAPITAL “delhi” /* “delhi “ is assigned
toCAPITAL*/
#define AREA 5*2.1 /*5*2.1 IS ASSIGNED
TO AREA*/
Program:
#include<stdio.h>
#define M 5
#define AND &&
#define EQUALS ==
void main()
{
int a=5;
printf(“Value = %d”,M*5);
if(a EQUALS M) //the statement is translated
as if(a == 5)
printf(“a and M are equal”);
}
Output: Value = 25

MACROS WITH ARGUMENTS:


The preprocessor permits us to define more complex
and more useful forms of replacements. It takes the form

The basic difference between the previous and the


current one is the replacement of macro with arguments.
Subsequent occurrence of a macro with arguments is known as a
macro call. When a macro is called, the preprocessor substitutes
the string, replacing the formal parameters with the actual
parameters. Here the string behaves like a template.
Program:
#include<stdio.h>
#define CUBE(x) x*x*x
void main()
{
int a,res;
printf(“Enter value”);
scanf(“%d”,&a);
res=CUBE(a);
printf(”Result = %d\n”,res);
}
NESTED MACRO SUBSTITUTIONS:
The macro definition can be nested. That is one macro
definition can be paced inside another macro.
Example:
#define SQUARE(x) ((x)*(x))
#define CUBE(x) ((x)*SQUARE(x))
If we call CUBE(side) then it call SQUARE(side) and
calculate side*side*side.

UNDEFINING A MACRO:
A defined macro can be undefined ,using the statement
#undef identifer

Example:
#undef SQUARE
The above will undefine the macro definition SQUARE

FILE INCLUSION:
An external file containing functions or macro
definitions can be included as a part of a program. So that we
need not rewrite those functions or macro definitions. This is
achieved by the preprocessor directive
#include <stdio.h> /* include the predefined header file in to
our program*/
#include “define.h” /* include the user defined header file to the
program*/
Example:
#include “test.c”
#define M 100
void main()
{
……
……
}

COMPILER CONTROL DIRECTIVES:


1. If suppose you want to test whether the particular macro is
defined in the given header file or not by using the directive
#ifndef.
Example:
#include “DEFINE.H”
#ifndef TEST
#define TEST 1
#endif
…….
The above checks if TEST is defined in the header file
“DEFINE.H” or not if it is included then TEST will be set to 1.
2. If suppose the programmer has to design a large program with
different requirements made by different user then depending
upon the user he may activate some of the additional features.
For that he may use the directive #ifdef.
Example:
…………..
#ifdef IBM_PC
code for IBM_PC
#else
code for other machines.
#endif
In the above module if we want to run the program on the
IBM machine we include the directive #define IBM_PC.

TYPE DEFINITION:
This allows the user to define the identifier that representS an
existing data type. The user-defined type is later used to declare
variables.
General form:

Typedef - keyword
Type - exiSting data type
Identifier –new name given to the data type
Typedef cannot create a new type. Using identifier the
variables can be declared using the following syntax:

Examples:
Typedef int units;
Units batch1,batch2;
Units name[10],name1[20];

BITWISE OPERATORS:
Purpose:
Bitwise operators are required to manipulate
individual bits in memory.
Categories:
• Bitwise logical operators
• Bitwise shift operators
• One’s complement operator.
One’s complement operator:
This is a unary operator that causes the bits of its operand to be
inverted such that 0’s become 1’s and 1’s become 0’s.The symbol
used is ~.
Example:
~011 = 100

Bitwise logical operators:


There are 3 logical operators.
Operator Meaning
& bitwise AND(returns a 1 if both bits have a value of 1.
Else 0 is returned.)
| bitwise OR(returns a 1 if atleast one of the bits has a
value of 1. Else returns a 0)
^ bitwise EXCLUSIVE OR(returns 1 if one of the bits is 1
and the other is 0.)
Program:
#include<stdio.h>
void main()
{
int a=3; //011
int b=2; //010
int c,d,e;
printf(“Bitwise and = %d”,a&b);
printf(“Bitwise or = %d”,a|b);
printf(“Bitwise exclusive or = %d”,a^b);
}
Output:
Bitwise and = 2
Bitwise or = 3
Bitwise exclusive or = 1
Masking:
Masking is the process in which a bit pattern is transformed into
another pattern by means of a logical bitwise operator.
Example:
B = a & 0x3f;
A = 0110 1101 1011 0111
Mask = 0000 0000 0011 1111
------------------------------------------
b = 0000 0000 0011 0111

Bitwise shift operators:


There are 2 shift operators.
<< shift left
>> shift right
Example:
B = a << 6;
If a = 0110 1101 1011 0111
Then a is shifted 6 positions to the left.
So b = 0110 1101 1100 0000

B = a >>6;
B = 0000 0001 1011 0110

BITFIELDS:
Refer IV unit.

COMMAND LINE ARGUMENTS:


It is a parameter supplied to the program when the program
is invoked. The parameters are passed to the main function
through 2 arguments argc and argv
Argc – argument counter – counts the number of arguments.
Argv – argument vector – has an array of character pointers to the
command line arguments.
Example:
C>PROGRAM X_FILE Y_FILE

Program to be invoked command line arguments

So argv[0]=program
Argv[1]=x_file
Argv[2[=y_file
Program:
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
Int I;
Char word[15];
Fp=fopen(argv[1],”w”);
Printf(“No of command line arguments = %d\n”,argc);
For(I=1;I<argc;I++)
Fprintf(fp,”%s”,argv[I]); //writes arguments into
file
Fclose(fp);
Fp=fopen(fp,”r”);
For(I=1;I<argc;I++)
{
fscanf(fp,”%s”,word); // reads and prints
the arguments
printf(“Command line argument[%d] is
%s\n”,I,word]);
}
fclose(fp);
}

Suggested Questions
Objective Questions

182.Write the syntax of the function fprintf()


183.Which functions are used to write the integer values into
file?
184.What is EOF?
185.# Define is used to _____________
186.Which operator is used for right shift?
187.Write the syntax of fopen()

Short answers:
188.Write short notes on bitwise operators
189.Explain how strings may be written into file.
190.Write short notes on preprocessor directives
191.Explain command line arguments.
192.Explain about register & extern variables
193.Explain about conditional compilation

Long answers
194.Write short notes on file handling commands
195.Explain about macro preprocessor directives
196.Write a program to copy the contents of one file to another
using command Line arguments
4. Compare fread & fwrite , fscanf & fprintf with suitable
examples.