0% found this document useful (0 votes)
488 views

C Explore

1) C is a general purpose, structured programming language that uses terms resembling algebraic expressions fragmented by English keywords. 2) There are different types of C compilers and interpreters such as Turbo C, Microsoft C, and RunC. 3) C was first developed in the 1970s by Dennis Ritchie at Bell Labs and was used for the Unix operating system.

Uploaded by

siba_sagar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
488 views

C Explore

1) C is a general purpose, structured programming language that uses terms resembling algebraic expressions fragmented by English keywords. 2) There are different types of C compilers and interpreters such as Turbo C, Microsoft C, and RunC. 3) C was first developed in the 1970s by Dennis Ritchie at Bell Labs and was used for the Unix operating system.

Uploaded by

siba_sagar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 117

1

‘C’ FUNDAMENTALS:-

‘C’ is a general purpose , structured programming language .


Its instructions consists of terms that resemble algebraic expressions ,
fragmented by certain English keywords such as if, else , for ,do and while
C also contains additional features , however ,that allow it to be used at a
lower level , thus is used as high level and low level language . This
language is understandable both by the user and the machine.

DIFFERENT TYPE OF ‘C’:-

RC : RunC :- INTERPRETER

MC : MicrosoftC:-compiler

TC : Turbo C :- compiler

HISTORY OF ‘C’:-

Before 1970 , Martin Richards developed the language ( Basic


combined programming language) . Ken Thompson from BELL lab did some
modification in the language and for the modified version he gave the
name as “B” , the first character of BCPL . In 1970 , Dennis Ritchie invented
and first implemented the programming language C that used the UNIX
operating system.

ADVANTAGES OF USING ‘C’:

C was first used for system programming. System programming


refers to a class of programs that are either are part of or works closely with
the operating system of the computer system programs make capable of
performing useful work.

1) ‘C’ is a function oriented language .


2) ‘C’ is a structured language .
3) ‘C’ has got powerful pointer operations .
4) ‘C’ allow you to write operating system.
5) ‘C’ runs faster than other compiler.

These are examples of system programs that are often written in C.

Operating system Language compiler

Assemblers Text editors

Print spader Network drivers


2

Modern programs Data base

Language Tnterpreters Utilities

FEATURES / IMPORTANCE OF C:-

1. General purpose , structured language.


2. Rich in library function and operators.
3. Highly portable.
4. Function oriented.
5. Case sensitive.
6. Ability to extend itself.

GENERAL PROCEDURE TO WRITE A PROGRAM:-

1. Declaration ( if any)
2. Accepting datas.
3. Manipulating datas/ making decessions.
4. Printing the output.
GENERAL STRUCTURE OF A C PROGRAM:-

Global variable declaration;

Global function declaration;

Main ( )

Variable declaration block;

Program statements;

Function calls;

Function – name (argument list)

Declaration arguments;

Local variable declarations;

Body of the function;


3

Note:- The main ( ) is considered as a building block of the program. It is a system defined
function . The only component that is required in every C program is the main() function. In its
simplest form, the main() function consists of the name main followed by a pair of empty
parentheses (()) and a pair of braces ({}). Within the braces are statements that make up the
main body of the program. Under normal circumstances, program execution starts at the first
statement in main() and terminates at the last statement in main().

THE C CHARACTER SET:-

C uses the uppercase letters A to Z , the lowercase letters a to z , the


digits 0 to 9 and certain special characters .

The special characters are listed below :

! * + \ “ <

# ( = | { >

% ) [ ; } /

^ - ] ‘ ?

& _ : , (blank)

C uses certain combinations of these characters such as \b,\n and \t to


represent special conditions such as blank space , newline and horizontal tab
respectively . The character combination are known as escape sequences.
Escape sequences represents a single character , even though it is written
as two or more characters.

IDENTIFIERS AND KEYWORDS:-

Identifiers are names given to various programs elements , such as


variables, functions and arrays . Identifiers consists of letters and digits , in
any order , except that the first character must be letter. Both uppercase
and lowercase letters are permitted, uppercase and lowercase letters are
not inter changeable.

The underscore character ( _ ) can also be included.

Valid identifiers not valid


4

X 4th

Y12 “x”

Sum_ order-no

_temp error flag

TABLE

There are certain reserve words , called keywords that have standard
predefined meaning mc. These keywords can be used only for their
intended

Purpose, they cannot be used as programmer-defined identifiers.

The standard keywords are:-

auto extern sizeof

break float static

case for struct

char goto switch

const if typedef

continue int union

default long unsigned

do register void

double return volatile

else short
while enum

signed

DATA TYPES:-

C supports several different types of data , each of which may


represented differently with in the computers memory.

Variable Type Keyword Bytes Range


5

Required

Character Char 1 -128 to 127

Integer Int 2 -32768 to 32767

Short integer Short 2 -32768 to 32767

Long integer Long 4 -2,147,483,648 to


2,147,438,647

Unsigned unsigned 1 0 to 255


character char

Unsigned integer unsigned 2 0 to 65535


int

Unsigned short unsigned 2 0 to 65535


integer short

Unsigned long unsigned 4 0 to 4,294,967,295


integer long

Single-precision Float 4 1.2E-38 to

floating-point 3.4E381

Double-precision double 8 2.2E-308 to

floating-point 1.8E3082

Constants

Constants are data items whose values are not changed during proram
execution time.

Constants:-

A constant is a value that cannot be changed during execution of


the program. There are three types of constants:-
6

Constant

Numeric constant Character constant


string constant

Integer constant Real constant

Decimal Octal Hexadecimal

Numeric constants:-

Numeric constants consists of numeric digits, they may or may not have
decimal point(.). These are the rules for defining numeric constants:-

1. Numeric constant should have at least one digit.

2. No comma or space is allowed within the numeric constants.

3. Numeric constants can either be positive or negative but


default sign is always positive.

There are two types of numeric constants:-

Integer constants:-

Integer constants are whole numbers which have no decimal point(.).


There are three types of integer constants based on different number
systems. These constants are:-

Decimal constants - 0,1,2,3,4,5,6,7,8,9


(base 10)

Octal constants- 0,1,2,3,4,5,6,7


(base 8)

Hex decimal constants :- 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F


(base 16)

Valid integer constant Invalid integer


constant
0 2.5
7

123 3#5

3705 98 5

Real constants:-

Floating point constants are numeric constants that contain decimal point.
Some valid floating point constants are:-
0.5,5.3,4000.0,0.0073,39.0807,5597.

Character constants:-

A character constant is a single character that is enclosed within single


quotes.

Valid character constants Invalid character constants

‘9’ ‘four’

‘D’ “d”

‘ ‘ ‘’

‘#’ y

Every character constant has a unique integer value associated with


it . This integer is the numeric value of the character in the machine’s character
code. If the machine is using ASCII (American standard code for information
interchange ) , then the character ‘G’ represents integer value 71.

Some ASCII values are:-

A-Z ASCII value(65-90)

a-z ASCII value(97-122)

0-9 ASCII value(48-57)

; ASCII value(59)

String constants:-

A string constant has zero , one or more than one character. A string
constant is enclosed within double quotes(“ “) . At the end of string , \0 is
automatically places b the compiler.
8

Some examples of string constants are:- “kumar” ,”593” ,


”8” ,” “, ” A”

Symbolic constant:-

A symbolic constant is a name that substitutes for a sequence of characters.


The character may represent a numeric constant, a character or named
constant.

Note:- A symbolic constant is required if we want to use a constant several


times .

For example:- If we have to use the constant 3.14159265 at many places


in our program ,then we can give it a name PI and use this name instead of
writing the constant value everywhere.

These constants are generally defined at the begini9ng of the program as:-

# define name value

Note:- Here ‘name’:- is the symbolic name for the constant , and is
generally written in uppercase letters

‘value’:- can be numeric , character and string constant .

Some examples of symbolic constants are:-

# define MAX 100

# define PI 3.14159625

# define Ch ‘Y’

# define NAME “suresh”

Variables:-

Variable is a name that can be used to store values. Variable


can take different values but one at a same time . These values can be
changed during execution of the program. A data type is associated with
each variable. The data type of the variable decides decides what value it
can take. The rules for naming variable are same as that for naming
identifier.
9

Declaration of variable:-

It is must to declare a variable before it is used in the program. Declaration


of a variable specifies name and datatype.

Note:-The type and range of values that a variable can store depends upon
its datatype.

The syntax of declaration of a variable is :-

Datatype variablename;

Here datatype may be float,int,char and double .

Some example of declaration of variable are:-

int x; // here x is a variable of type int

float salary;// here salary is a variable of type float

char grade; // here grade is a variable of type char

we can also declare more than one variable in a single declaration:-

For example:- int x, y, z, total; //here x,y,z,total are all variable of


type int

Initialization of variable:-

When a variable is declared it contains undefined value


commonly known as garbage value. If we want we can assign some initial
value to the variable during the declaration itself , this is called initialization
of the variable.

For example:-

int a=5;

float x=8.9,y=10.5;

char ch=’y’;

double num=0.15197e-7;

int l,m,n,total=0; //here only variable total has been initialized

Expressions:-
10

An expression is a combination of perators, constants, variables


and function calls. The expression can be arithmetic, logical or relational.

Some examples are as:-

X+Y --Arithmatic operation

A=b+c --Uses two operators (=) and (+)

a>b --relational expression

a==b --logical expression

func(a,b) --function call

Statements:-

In a c program , instructions are written in the form of


statements. A statement is an executable part of the program and causes
the computer to carry out some action.

Statements can be categorized as :-

(i) Expression statements

(ii) Compound statements

(iii) Selection statement(if, if…else, switch)

(iv) Iterative statements(for, while, do…while)

(v) Jump statements(goto, continue, break,return)

(vi) Label statements(case, default, label statement used in


goto)

Expression statement:-

Expression statement consists of an expression followed by a


semicolon.

For example:-

X=5;

X=y-z;

Func(a,b);
11

Note:- A statement that has only a semilcolon is also known as null


statement

For example:- ; //null statement

Compound statement:-

A compound v consists of several statements enclosed within a pair of


curly braces

{ } . compound statement is also known as block of statement. Note that


there is no semicolon after the closing brace. For example:-

Int l=4,b=2,h=3;

Int area , volume;

Area = 2*(1*b+b*h+h*1); volume=1*b*h;

Note:-The variables that are declared inside a block can be used only inside
that block.

Comments:-

Comments are used for increasing readability of the program.


They explain the purpose of the program and are helpful in understanding
the program. Comments are written inside / * and */. There can be single
line comment or multiple line comments.

Note:-We can write comments anywhere in a program except inside a


string constant or a character constant.comments can’t be nested i.e. we
can’t write a comment inside another comment.

Some examples of comments are:-

/* variable b represents basic salary */

/* this is a c program to calculate

Simple program */

Input –Output in C
12

There are three main functions of any program – it takes data as input
,process this data and gives the output . The input operation involves
movement of data from an input device(generally keyboard) to computer
memory, while in output operation the data moves from computer memory
to the output device(generally screen).

C-language does not provide any facility for input-output


operations. The

Input –output is performed through a library function that are supplied with
every C-compiler. These functions considered standard for all input-output
operations in C.The set of library functions that performs input-output
operation is known as standard I/O library. The most commonly used input-
output function in C is printf( ) and scanf( ).

Header files :- It is always declared at the beginning of the program


because it contains the definition of the system defined functions used
inside the program. There are several header files that provide necessary
information in support of the various library functions .

Syntax of the header file:- #include directive

For example:- If a program uses any function from the standard I/O library,
then it should include the header files stdio.h which contains the definition of
the printf( ) and scanf( ) function that should be declared as:-

#include<stdio.h>

Similarly there are several other header files like math.h ,string.h
alloc.h etc.

Conversion specification:-

The functions scanf( ) and printf( ) make use of conversion


specification to specify the type and size of data . Each conversion
specification must begin with a percent sign(%).

Some conversion specification are as given below:-

%c A single character
%d A decimal integer
%f A floating point number
%ld Long range of decimal
13

integer (long int data type)


%h A short integer
%lf Long range of floating point
number(for double data
type)
%s A string
%o An octal integer
%i A octal,decimal or
hexadecimal integer
%u An unsigned decimal integer
%e A floating point number
%g A floating point number
%x A hexadecimal integer

Reading input data:-

Input data can be entered into the memory from a standard


input device(keyboard).C provides the scanf( ) library function for entering
input data. This function can take all types of values
(numeric,character,string) as input.

The scanf( ) function can be written as :-

Scanf(“control string”, adress1,address2, …………);

This function should have at least two parameter .

First parameter is a control string , which contains conversion


specification character such as %d,%c etc according to their type of
variable. It should be within double quotes . The conversion specification
characters may be one or more ; it depends on the no of variable because
one conversion specification used for only one variable.

The other parameters are addresses of variables . In the scanf( )


function at least one address should be present . The address of a variable
is found by preceding the variable name by an ampersand (&) sign. This sign
is called the address operator and it gives the starting address of the
variable name in memory .

Note:- A string variable is not preceded by & sign to get the address.

For example:-

#include<stdio.h>
14

main()
{
int basic;
float hra;
char grade;
-------------
scanf(“ %d %f
%c”,&basic,&hra,&grade); --------
------- }

Here the control string has three conversion specifications characters %d,%f
and %c , means that one integer value , one floating point value and one
single character can be entered as input . These values are stored in the
variables basic, hra and grade. The input data can be entered as:-

1500 200.50 A

1500 will be stored inside basic variable.

200.50 will be stored inside hra variable.

A will be stored inside grade variable.

Writing output data:-

Output data can be written from computer memory to the


standard output device(monitor) using printf( ) library function . With this all
type of values (numeric, character or string) can be written as output.

The printf( ) function can be written as :-

printf(“ control string”, variable 1, variable 2, -------);

In this function the control string contains conversion specification


characters and text. It should be enclosed within double quotes . The name
of variables should not be preceded by an ampersand (&) sign. If the control
string does contain any conversion specification , then the variable names
are not specified .

Some examples of printf( ) function are as:-

Example 1:- #include<stdio.h>


15

main( )
{
printf(“ C is excellent \n “);

Output:-

C is excellent

Example 2:-#include<stdio.h>

main( )
{

int roll_no;
char grade;
float perc;

scanf(“%d%c%f”,&roll_no,&grade,&perc);

printf(“Roll_no:- %d, Grade:-%c, Percentage:-%f


“,roll_no,grade,perc);

Input data:- 123, A,65.43

Output:- Roll_no:- 123, Grade:-A, Percentage:-65.43

Formatted Input and Output:-

Formatted input and output means that data is entered and displayed
in a particular format. Through format specifications, better presentation of
result can be obtained.

Format for different specification are as:-

Format for integer input:-

%wd:- Here ‘d’ is the conversion specification character


for integer value and ‘w’ is an integer number specifying the maximum field
width of input data.
16

NOTE:-If the length of input is more than this maximum field width then
the values are not stored correctly.

For example:-

Scanf(“%2d%3d”,&a,&b);

(i) When input data length is less than the given field width
, then the input values are unaltered and stored in given
variable.

Input:- 6 39

Result:-6 is stored in a and 39 is stored in b.

(ii) When input data length is equal to the given field


width , then the input values are unaltered and stored in
given variables.

Input:- 26 394

Result:- 26 is stored in a and 394 is stored in b

(iii) When input data length is more than the given field
width , then the input values are altered and stored in
the variable.

Input:- 269 3845

Result:- 26 is stored in a and 9 is stored in b and the


rest of input ignored.

Format for integer output:-

%wd:- Here w is the integer number specifying the


minimum field width of the output data. If the length of the variable is less
than the specified field width, then the variable is right justified with leading
blanks.

For example:-

Printf(“a=%3d,b=%4d”,a,b);

(i) When the length of the variable is less than the width specifies.
17

Value of variable:- 78 9

Output:-

a = 7 8 , b = 9
The width specifies of first data is 3 while there are only 2 digit in it , so
there is one leading blank. The width specifies

of second data is 4 while there is only 1 digit , so there are 3 leading


blanks.

(ii) When the length of the variable is equal to the width specifies.

Value of variable:- 263 1941

Result a = 2 6 3 , b = 1 9 4 1
:-

(iii) When length of variable is more than the width specifies , then
also the output is printed correctly.

Value of variables:- 2691 19412

Result :- a = 2 6 9 1 , B = 1 9 4 1 2

Format for floating point numeric input:-

%wf:- Here ‘w’ is the integer number specifying the total width
of the input data(including the digits before and after decimal and the
decimal itself).

For example:-

scanf(“%3f %4f”, &x,&y);

(i) When input data length is less than the given width ,
values are unaltered and stored in the variable.

Input:- 5 5.9
18

Result:- 5.0 is stored in x and 5.90 is stored in y

(ii) When input data length is equal to the given width ,


values are unaltered and stored in the given variable.

Input:- 5.3 5.92

Result:- 5.3 is stored in x and 5.92 is stored in y

(iii) When input data length is greater than the given width ,
values are altered and stored in the given variable.

Input:- 5.93 65.87

Result:- 5.9 is stored in x and 3.00 is stored in y

Format for floating point numeric output:-

Here w is the integer number specifying the total width of


the input data and n is the number of digits to be printed after decimal
point. By default 6 digits are printed after the decimal.

For example:-

printf(“x=%4. 1f, y=%7.2f”,x,y);

Note:- If the total length of the variable is less than the specified width ‘w’ ,
then the value is right justified with leading blanks . If the number of digits
after decimal is more than ‘n’ then the digits are rounded off.

Value of variables :- 8 5.9

Output:-

x = 8 . 0 , y = 5 . 9 0

Value of variables :- 25.3 1635.92

Output:-

x = 2 5 . 3 , y = 1 6 3 5 . 9 2

Value of variables :- 15.231 65.875948


19

Output:-

x = 1 5 . 2 , y = 6 5 . 8 8

Format for string input:-

%ws:- Here w specifies the total number of characters that will be


stored in the string .

char str[8];

scanf(“%3s”,str);

If the input is :- Srivastav

Only first three characters of this input will be stored in the string . so the
characters in the string will be :- ‘s’ , ‘r’ ,’i’, ‘\0’

The null character (‘\0’) is automatically stored at the end .

Format for string output:-

%w.ns :-Here w is the specified field width. Decimal point and ‘n’
are optional. If present then ‘n’ specified that only first n characters
of the string will be displayed and (w-n) leading blanks are displayed
before string.

(i) printf(“%3s”,”sureskumar”);
result:-

S u r e s k u m a R

(ii) printf(“%10s”,”reeta”);

result:-

r e e t a
20

(iii) printf(“%.3s”,”sureshkumar”);

result:-

S u r

(iv) printf(“%8.3s”,”sureshkumar”);

result:-

s u R

Character I/O:-

getchar( ) and putchar( ):-

These macros getchar() and putchar( ) can be used for


character I/O . getchar( ):- It reads a single character from the standard
input.

Putchar( ):- It gives outputs one character at a time to the standard


output.

#include<stdio.h>

Main( )

char ch;

printf(“enter a character :”);

ch=getchar( );

printf(“ The entered character is :”);

putchar(ch);

}
21

Operators and expressions :-

Operator:- An operator specifies an operation to be performed that yield a


value.

Expression:- The variables , constants can be joined by various operator


to form an expression.

Operand:- An operand is a data item on which an operator acts .

Operators can be divided into three types:-

1) Unary Arithmatic Operator

2) Binary Arithmatic Operator

3) Terinary Arithmatic Operator

Unary Arithmatic Operator:- unary Operator which requires only


one operand.

For example:- +x -y

Binary Arithmatic Operator:- Binary Operator which requires


two operand

or example:- x+y A-B


Terynary operator:- terynary operator which requires three
expression asoperand.

For example:-

Conditional Operator:-

This is a terynary operator( ? and :)

Synatax:-

TestExpression ? expression 1 : expression 2;


22

Firstly the expression is evaluated

(i) If TestExpression is true (nonzero), then expression 1 is


evaluated and it becomes the value of the overall conditional
expression.

(ii) If TestExpression is false (zero), then expression2 is evaluated


and it becomes the value of overall conditional expression.

For example consider this conditional expression:-

a>b ? a : b ;

Here first the expression a>b is evaluated , if the value is true then
the value of variable a becomes the value of conditional expressional
otherwise the value of b becomes the value of overall conditional expression.

Suppose a=5 and b=8

Max=a>b ? a : b;

First the expression a>b is evaluated , since it is false so the value of b


becomes the value of conditional expression and it is assigned to variable
max.

a<b ? printf(“ a is smaller “) : printf(“ b is smaller”);

since the expression a<b is true , so the first printf function is executed .

C includes a large number of operators that fall under several different


catagories ,

which are:-

1. Arithmatic operator

2. Assignment operator

3. Increment and decrement operator

4. Relational operator

5. Logical operator

6. Comma operator
23

7. Sizeof operator

8. Bitwise operator

Arithmatic operator:-

Operator purpose
+ Addition
- Substaction
* Multiplication
/ Division
% Gives the reminder in integer division

For example:-

Consider a=17 and b=4

Expression Result
a+b 21
a-b 13
a*b 68
a/b 4
a%b 1

Assignment operators:-

A value can be stored in a variable with the use of assignment


operator. This assignment operator “ = “ is used in assignment
expressions and assignment statement.

Note :- The operand on the left hand side should be a variable ,


while the operand on the right hand side can be any variable,
constant or expression. The value of right hand operand is assigned to
the left hand operand . \

Here are some examples of assignment expressions:-


24

X=8 // 8 is assigned to X

Y=X // The value of X is assigned to y

S=X+Y-2 //value of expression X+Y+2 is assigned


to s

X=Y=Z=20 // Here all the three variables X,Y,Z


will be assigned value 20, and the
value of whole expression will be
20.

When the variable on the left hand side of assignment operator also occurs
on right hand side then we can avoid writing the variable twice by using
compound statement operator.

X+=5 is equivalent to X=X+5

X-=5 is equivalent to X=X-5

Y*=5 is equivalent to Y=Y*5

Sum /=5 is equivalent to sum=sum/5

K%=5 is equivalent to k=k%5

Increment and Decrement Operators:-

C has two useful operators increment (++) and decrement (- -) .


These are unary operators because they operate on a single operand .

(++ ) :- The increment operator increments the value of the variable by 1.

(- -) :- The decrement operator decrements the value of the variable by 1.

For example:- ++x is equivalent to x=x+1

--x is equivalent to x=x-1

Note:- These operators should be used only with variables, they can’t be
used with constants or expressions .

For example the expression ++5 or ++(x+y+z) are invalid.


25

These operators are of two types:-

1. Prefix increment / decrement - operator is written before the operand


( e.g. ++x or --y)

2. Postfix increment / decrement – operator is written after the operand(e.g


x++ or x--)

Prefix increment / decrement:-

Here first the value of variable is incremented / decremented


then the new value is used in the operation .

For example:- Let us take a variable x whose value is 3 .

The statement y=++x , means first increment the value of x by 1 then


assign the value of x to y . This single statement is equivalent to these two
statement:-

x=x+1

y=x

hence now value of x is 4 and value of y is 4.

The statement y=--x , means first decrement the value of x by 1 then


assign the value of x to y . This single statement is equivalent to these two
statement:-

x=x+1

y=x

hence now value of x is 3 and value of y is 3.

Postfix increment / decrement:-

Here first the value of variable is used in the operation then


incremented / decremented is performed.

For example:- Let us take a variable x whose value is 3 .

The statement y=x++ , means first the value of x is assigned to y


and then x is incremented .This single statement is equivalent to these two
statement:-

y=x
26

x=x+1

hence now value of x is 4 and value of y is 3.

The statement y=x-- , means first the value of x is assigned to y and


then x is decrement . This statement is equivalent to these two statement:-

y=x

x=x-1 hence now value of x is 3 and value of y


is 4.

Relatioanl operator:-

The operators are used to compare values of two expressions


depending on their relations. An expression that contains relational
operators is called relational expression. If the relation is true then the value
of relational expression is 1 and if the relation is false then the value of
expression is 0.

The relational operators are:-

Operator Meaning
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to

Let us take two variables a=9 and b=5 , and form simple relational
expressions with them

Expression Relation Value of Expression


a<b False 0
a<=b False 0
a= =b False 0
a!=b True 1
a>b True 1
a>=b True 1
a==0 False 0
b!=0 True 1
a>8 True 1
2>4 False 0
27

Note:- The relational operator are generally used in if…..else construct


and loops.

Logical operator:-

An expression that combines two or more expressions is


termed as a logical expression . For combining these expressions we use
logical operators. These operator return 0 for false and 1 for true . The
operand may be constants , variables or expressions .

C has three logical operator:-

Operator Meaning
&& AND
|| OR
! NOT

Note:- Here logical NOT is a unary operator while the other two are binary
operators.

In C any non-zero value is regarded as true and zero is regarded as


false.

AND(&& ) Operator:-

This operator gives the net result true if both the conditions are true ,
otherwise the result is false.

Boolean Table

Condition1 Condition2 Result


False False False
False True False
True False False
True True True

Let us take three variable a=10,b=5,c=0

Suppose we have a logical expression:-

(a= =10) && (b<a)


28

Here both the conditions a==10 and b<a are true , and hence this whole
expression is true .Since the logical operators return 1 for true hence the the
value of this expression is 1.

Expression Result Value of


expression
(a==10) && True && false False 0
(b>a) False && true False 0
(b>=a) && True && true True 1
(b==3) True && false False 0
a && b
a && c

OR( || ) operator:-

This operator gives the net result false, if both the conditions have the
value false , otherwise the result is true .

Boolean Table

Condition1 Condition2 Result


False False False
False True True
True False True
True True True

Let us take three variables a=10,b=5,c=0

Consider the logical expression :-

(a>=b) || (b>15)

This gives the result true because one condition is true .

Expression Result Value of


expression
29

a||b True | | true true 1


a ||c True | | false true 1
(a<9) | | (b>10) False | | false false 0
(b!=7) | | c True && false true 1

Not ( ! ) operator:-

This is unary operator and it negates the value of the condition .


If the value of the condition is false then it gives the result true. If the value
of the condition is true then it gives the result false.

Condition Result
False True
True False

Let us take three variables a=10,b=5,c=0

Suppose we have this logical expression :-

! (a = = 10)

The value of the condition (a==10) is true . NOT operator negates the value
of the condition . hence the result is false.

Expression Result Value of


expression
!a !true False 0
!c !false True 1
!(b>c) !true False 0
!(a && c) !false True 1

Bitwise Operator:-

we know that inside the computer , data is represented in bits


(0 and 1) .Till now we are able to access and manipulate bytes only . But
some applications ,such as system programming require manipulation of
individual bits within a byte. In most high level language this facility is not
available, but C has the ability to manipulate individual bits of byte. This
30

feature is implemented through bitwise operators that support bitwise


operations. C has the ability to support the manipulation of data at bit level.
Bitwise operators are used for operations on individual bits.

Note:- Bitwise operator operate on integer only.

The bitwise operators are as:-

Bitwise operator Meaning


& Bitwise AND
| Bitwise OR
~ One’s
<< complement
>> Left shift
^ Right shift
Bitwise XOR

Bitwise AND(&):-

It is binary operator and requires two operand . These


operands are compared bitwise i.e. all the corresponding bits in both
operands are compared . The resulting bit is 1, only when the bits in both
operands are 1, otherwise it is 0.

Boolean Table

Bit of operand1 Bit of operand2 Resulting bit


0 0 0
0 1 0
1 0 0
1 1 1

Let us take a=0x293B and b=0x1A2F are two integer variables. The binary
representation of these variables and the result after performing bitwise
AND operation :-

a 0010 1001 0011 1011 (0x293B)

b 0001 1010 0010 1111 (0x1A2F)

a&b 0000 1000 0010 1011 (0x082B)

Bitwiswe OR:-
31

The corresponding bits in both operands are compared . The


resulting bit is 0, only when the bits in both operands are 0, otherwise it is 1.

Boolean Table

Bit of operand1 Bit of operand2 Resulting bit


0 0 0
0 1 1
1 0 1
1 1 1

Let us take a=0x293B and b=0x1A2F are two integer


variables. The binary representation of these variables and the result after
performing bitwise OR operation :-

a 0010 1001 0011 1011 (0x293B)

b 0001 1010 0010 1111 (0x1A2F)

a | b 0011 1011 0011 1111 (0x082B)

Bitwise XOR(^):-

The corresponding bits in both operands are compared . The


resulting bit is 1, if bits of both operands are different value, otherwise it is 0.

Boolean Table

Bit of operand1 Bit of operand2 Resulting bit


0 0 0
0 1 1
1 0 1
1 1 0

Let us take a=0x293B and b=0x1A2F are two integer


variables. The binary representation of these variables and the result after
performing bitwise OR operation :-

a 0010 1001 0011 1011 (0x293B)

b 0001 1010 0010 1111 (0x1A2F)


32

a | b 0011 0011 0001 0100 (0x082B)

One’s complement ( ~ ):-

One’s complement operator is a unary operator and requires


only one operand . It negates the value of the bit. If the bit of the operand is
1 then the resulting bit is 0 and if the bit of the operand is 0 then the
resulting bit is 1.

Boolean Table

Bit of operand Resulting Bit


0 1
1 0

a 0010 1001 0011 1011

~a 1101 0110 1100 0100

Bitwise left shift ( << ):-

This operator is used for shifting the bits left. It requires two
operands. The left operand whose bits are shifted and the right operand
indicates the number of bits to be shifted and the right operand indicates
the number of bits to be shifted . On shifting the bits left, an equal number of
bit positions on the right are vacated . These positions are filled in with 0 bits
. Let us take an integer variable a =0x1346 .

The binary representation of x is:-

0010 0010 0100 0110

Now we will find out a<<4

Initial bit pattern Bit pattern after left shifting

0010 0010 0100 0110 0000


0010 0011 0100 0110
lost Bits
bits shift
33

On shifting all bits to the left by 4 , the leftmost 4 bits are lost
while the rightmost 4 bit positions become empty which are filled with 0
bits.

Bitwise Right shift ( >> ):-

This operator is used for shifting the bits right. It requires two
operands. The right operand whose bits are shifted and the left operand
indicates the number of bits to be shifted and the left operand indicates the
number of bits to be shifted. On shifting the bits right, an equal number of
bit positions on the left are vacated . These positions are filled in with 0 bits .
Let us take an integer variable a =0x1346 .

The binary representation of x is:-

0010 0010 0100 0110

Now we will find out a>>4

Initial bit pattern Bit pattern after left shifting

0110 0000 0100 0110 0100


0010 0011 0100 0110
lost Bits bits
filled

CONTROL STATEMENTS

The C language provides facilities for controlling the order of


execution of the statement , which are referred to as flow control
statement .

The various flow control statements are :-

1. Decision Making Statement---------

 if statement

 if –else statement

 else if statement

 switch statement
34

2. Looping statement----------------

 for statement

 while statement

 do----while statement

3. jumping statement----------------

 break statement

 continue statement

 goto statement

Decision Making Statements:-

These statements allow the execution of selective statements


based on certain decision criteria.

The if Statement:-

This is a single way selection statement i.e. it executes set


of statement if the condition is true .

The syntax of if statement:-

If ( condition ) conditi
{ on

……………………….. true
Statement-block
35

Statement-block
………………………..
}

false

/* program to print a message if negative number is entered*/

#include<stdio.h>

Main( )

int num;

printf(“enter a number: ”);

scanf(“%d”,&num);

if( num<0 )

printf(“number entered is negative\n”);

printf(“value of num is : %d \n”,num);

The if----else statement:-

This is a bi-directional conditional conditional control


statement.This statement is used to test a condition and take one of the two
possible actions. If the condition is true then a single statement or a block of
statements is executed (one part of the program), otherwise another single
statement or a block of statement is executed (other part of the program).
The syntax of if-----else statement:-

If (condition)
conditi
{ on
................
Statement-block- Statement-block-
Statement-block-12 1
36

. ...............

else

. .................

Statement-block-2
. ................. }

If condition is true then the statement-block-1 is executed, if


the condition is false then the statement–block-2 is executed.

/* program to print the larger and smaller of the two numbers */

#include<stdio.h>

main( )

Int a,b;

Printf(“enter two number”);

Scanf(“%d %d”,&a,&b);

if( a>b )

printf(“larger number =%d and smaller number=


%d\n”,a,b);

else

printf(“larger number =%d and smaller number=


%d\n”,b,a);

The else-if statement:-This is a type of nesting in which there is an if……


else statement in every else part except the last else part. This type of
nesting is frequently used in programs and is also known as else if ladder.

if (condition 1)

statement A; True
37
False
Conditio
n1
else if (condition 2)

statement B;
Stat A
True False
else if(condition 3) Conditio
n2
statement C;
Fals
else Stat B True e
Conditio
statement D; n3

Stat C Stat D

Next statement

Here each condition is checked , and when a condition is found to be true ,


the statements corresponding to that are executed , and the control comes
out of the nested structure without checking remaining conditions. If none of
the condition s is true then the last else part is executed.

/* program to find out the grade of a student when the marks of 4 subjects
are given .The method of assigning garde is as:-

per>=85 grade=A

per<85 and per>=70 garde=B

per<70 and per>=55 grade =C

Per<55 and per>=40 grade =D

per<40 grade=E

here per is percentage */

#include<stdio.h>

main ( )

{
38

float m1,m2,m3,m4,total,per;

char grade;

printf(“enter marks of 4 subjects : “);

scanf(“%d%d%d%d”,&m1,&m2,&m3,&m4);

total=m1+m2+m3+m4;

per=total/4;

if( per>=85 )

grade=’A’;

else if( per >=70 )

grade=’B’;

else if(per >=55)

grade=’C’;

else if(per >=40)

grade=’D’;

else

grade=’E’;

printf(“percentage is %f \n grade is %c \n “, per, garde);

Nested if statement:-

If the if statement becomes a part of another statement then


that statement is called nested if statement.

if( condition1 )

{ true false
Conditio
n1
if( condition2 )

statement 1; Statement 3
true false
Conditio
n2

Statement 1 Statement 2
39

else

statement 2;

else

statement 3;

/* Input three numbrs and print the greatest number*/

#include<stdio.h>

main ( )

int a,b,c;

printf(“enter three number”);

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

if ( a > b )

if ( a > c )

printrf(“ 1st no is greater “);

else

printf(“3rd no is greater”);

else if ( b > c )

printf(“ 2nd no is greater”);

else

printf(“3rd no is greater”);
40

Switch statement:-

This is a multi-directional conditional control statement i.e a


single switch value is mapped with number of case value and it executes set
of statement if any one case value is matched with switch value otherwise it
executes default statement.

The syntax is:-

switch ( expression )

case val-1 : statement- block-1

break;

case val-2 : statement-block-2

break;

case val-3 : statement-block-3

break;

case val-n : statement-block-n

break;

default : statement-block-default

Here switch,case and default are keywords . The “


expression” following the switch keyword can be any C expression that
yields an integer value i.e. if expression takes any value from val-1,val-2,val-
3,…….., val-n , the control is transferred to that appropriate case. In each
case , the statements are executed and then the break statement
transfers the control out of switch statement. If no break statement is used
following a case , except the last one in the absence of default keyword ,
the control will fall through to the next case. If the value of the expression
41

does not match any of the case values , control goes to the default keyword,
which is usually at end of the statement.

Note :- The floating point or string constant can’t used as a case value.

Now we’ll see some valid and invalid ways of writing switch
expressions and case constants.

Int a, b, c ; char d, c; float f;

Valid invalid

switch(a) switch(f)

switch(a>b) switch(a+4.5)

switch(d+e-3) case “second”:

switch(a>b && b>c) case 2.3:

switch(func(a,b)) case a:

case 4: case a>b:

case ‘a’: case a+2:

case 2+4: case 2,4,5:

case ‘a’ >’b’: case 2 :4 :5 :

Now let us see how the switch statement works. Firstly the switch
expression is evaluated , then the value of this expression is compared one
by one with every case constant , then all statements under that particular
case are executed . If none of the case constant matches with the value of
the expression then the block of statements under default is executed .
‘default’ is optional . If it is not present and no case matches then no action
takes place. These cases and default can in any order.

Looping statement :-

Loops are used when we want to execute a part of the


program or a block of statement . For example, suppose we want to print “
C is the best ” 10 times . One way to get the desired output is – we write
10 printf statement , which is not preferable . Other way out is –use loop.
Using loop we can write one loop statement and only one printf statement ,
and this approach is definitely better than the first one . With the help of
42

loop we can execute a part of the program repeatedly till some condition is
true. Ther are three loop statement in C:-

(i) while

(ii) do while

(iii) for

While loop:-

The while statement is suited for problems where it is not


known in advance that how many times a statement or a statement-block
will be executed

The syntax of while statement is :-

While(condition)
False
{ While(conditi
on)
Statement ;
True
Statement ;

--------------
Body of loop
}
Next statement
out of loop

Now let’s see how this loop works.

First the condition is evaluated, if it is true then the statements in the body
of lop are executed . After the execution , again the condition is checked
and if it is found to be true then again the statements in the body of loop
are executed . This means that these statements are executed continuously
till the condition is true and when it becomes false, the loop terminates and
the control comes out of the loop. Each execution of the loop body is
known as iterartion
43

/* program to print sum of digits of any number */

#include<stdio.h>

main( )

int n,r,sum=0;

printf(“enter the no”);

scanf(“%d”,&n);

while(n>0)

r=n%10;

sum+=r;

n=n/10;

Printf(“sum of digits=%d”,sum);

Do while loop:-

The do-while statement, like while statement , is also suited for problems
where it is not known in advance that how many times a statement will be
executed .

The syntax of do---while statement is

do

Statement ;

Statement ;

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

} while(condition);
44

Here firstly the statements inside loop body are executed and then the
condition is evaluated . If the condition is true , then again the loop body is
executed and this process continues until the condition become false .

Note:- The difference between while and do----while loop:-

In a ‘while’ loop , first the condition is evaluated and then


the statements are executed whereas in a do while loop, first the
statements are executed and then the condition is evaluated . So if initially
the condition is false the while loop will not execute at all, whereas the do
while loop will always execute at least once.

/* program to count the digits in any number */

#include<stdio.h>

main( )

int n,count=0,rem;

printf(“enter the number : “);

scanf(“%d”,&n);

do

n/=10;

count++;

}while(n>0);

Printf(“ Number ofn digits = %d\n”,count);

For loop:-

The for statement is suited for problems where the number of


times a statement or statement-block will be executed is known in
advance.

The syntax of for statement is


45

for (expression1;expression 2;expression 3)

statement ;

statement ;

---------

The loop body can be a single statement or a block of statements.

expression 1 is an initialization expression, expression 2 is a test expression


or condition and expression 3 is an update expression . expression 1 is
executed only once when the loop starts and is used to initialize the loop
variables . expression 2 is a condition and is tested before each iteration of
the loop. Expression 3 is an update expression and is executed each time
after the body of the loop is executed .

/* multiply two positive numbers without using * operator */

main( )

int a,b,i;

int result=0;

printf(“ Enter two numbers to be multiplied : “);

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

for ( i=1;i<=b;i++)

result=result+a;

printf(“%d %d = %d\n”,a,b,result);

Nesting of loop:-

When a loop is written inside the body of another loop, then


it is known as nesting of loops. Any type of loop can be nested inside any
46

other type of loop. For example a for loop may be nested inside another for
loop or a while loop. Similarly while and do---while loops can be nested.

/* program to understand nesting in for loop */

main( )

int I,j;

for(i=1;i<3;i++) /* outer loop */

For(j=1;j<=4;j++) /* inner loop */

printf(“j=%d\t”,j);

printf(“\n”);

Output:

i=1

j=1 j=2 j=3 j=4

i=2

j=1 j=2 j=3 j=4

i=3

j=1 j=2 j=3 j=4

Infinite loop:- The loops that go on executing infinitely and never terminate
are called infinite loops. Sometimes we write these loops by mistake while
sometimes we deliberately make use of these loops in out programs .

Let us take some examples :-

(A) for(i=0;i<=5;i--)

printf(“%d”,i);
47

(B) int k=1;

do

Printf(“%d”,k);

Sum=sum+k;

}while(k<5);

break statement:-

break statement is used inside loops and switch statements.


Sometimes it becomes necessary to come out of the loop even before the
loop condition becomes false. In such a situation, break statement is used to
terminate the loop . This statement causes an immediate exit from that loop
in which this statement appears .

It can be written as:-

break;

For example:-

/* program to understand the use of break */

main( )

int n;

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

if(n==3)

Printf(“ I understand the use of


break\n”);

Break;

}
48

Printf(“number = %d \n”,n);

Printf(“out of for loop\n”);

Output:

Number=1

Number=2

I understand the use of break

Out of the loop

Continue statement:-

The continue statement is used when we want to go to the


next iteration of the loop after skipping some statements of the loop.

This continue statement can be written simply as:-

continue;

It is generally used with a condition . When continue statement is


encountered all the remaining statements in the current iteration are not
executed and the loop continues with the next iteration.

The difference between break and continue is that when


break is encountered the loop terminates and the control is transferred to
the next statement following the loop, but when a continue statement is
encountered the loop is not terminated and the control is transferred to the
beginning of the loop.

/* program to understand the use of continue statement */


49

#include<stdio.h>

main( )

int n;

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

if(n==3)

Printf(“ I understand the use of


continue\n”);

continue;

Printf(“number = %d\n “,n);

Printf(“out of for loop\n”);

Output:-

Number=1

Number=2

I understand the use of continue

Number=4

Number =5

Out of for loop

Array:
50

An array is a collection of homogeneous data elements (i.e, elements of same type)


described y a single name. Each element of an array is references by a subscripted
variable formed by affixing to the array name or index enclosed in parentheses. The
term subscript has the same meaning as in the mathematical notations. If single
subscript is required to reference an element of an array, the array is known as
single dimensional array or linear array. And if two subscripts are required to
reference an element, the array is known as two dimensional array and son. The
arrays whose elements are referenced by two or more subscripts are called multi
dimensional arrays.

Characteristics of array:

1. It is linear data structure and is a collection of similar type of elements

2. Each array elements are stored in consecutive manner

3. Array elements can be referred thorough array index

4. The array subscript must be positive integer constant

5. Maximum size of the array is 65535

6. The array index starts from 0 to n-1 for the array of size n.

LINEAR ARRAYS
A linear array a is a list of a finite number n of homogeneous data elements such
that

• The elements of the array are referenced by a index set consisting of n


consecutive integer numbers

• The elements of the array are stored in consecutive memory locations

int a[4];
3 3 4 43
2

a[0] a[1] a[2] a[3] a[4]

Syntax for linear array:

Data type array name[size];

Examples:

int a[5]; float p[6]; char st[20];

Compile time initialization of the linear array:


51

int a[5]={5,3,5,33,22}; float p[3]={3.3,56.4,64.33}; char


st[10]=”rina”;

Runtime initialization of the linear array:

int a[5];

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

printf(“enter a number:”);

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

Traversing the linear array:

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

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

Write a program to find sum and average of all array elements

void main()

int a[100];

int n,s=0;

float avg;

printf(“Enter how many numbers:”);

scanf(“%d”,&n);

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

printf(“enter a number:”);

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

s=s+a[i];

avg=(float)s/n;

printf(“sum= %d avg=%f”,s,avg);

Write a program to search element in an array

Void main()

int n,k;

Int a[100];

printf(“enter how many numbers:”);

scanf(“%d”,&n);

for(i=0;i<n;I++)

printf(“enter a number:”);

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

printf(“”enter the element to search:”);

sacnf(“%d”,&k);

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

If(a[i]==k)

Printf(“data is found on position %d”,i+1);

exit(0);
53

printf(“data not found”);

Two dimensiaonal array:

A two dimensional array is a list of a finite number, m*n of homogeneous data


elements such that:

The elements of the array are referenced by two index sets consisting of m
and n consecutive integer numbers

The elements of the array are stored in consecutive memory locations.

The size of the two dimensional array is denoted by m*n and pronounced as m by n.

Systax:

Data type array[size];

Example:

Int a[3][3];

Float p[3][3];

col 0 col 1 col 2

Row 0 00 01 02

Row 1 10 11 12

Row 2 20 21 22

Picturing a two dimensional array a

Represnting two dimensional array:


54

Coumn major order:

The elements are stored column by column i.e, m elements of the first column and
stored in first m locations, elements of the 2 nd column are stored in next m columns
and so on.

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

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

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

Rowmajor order:

The elements are stored column by row i.e, n elements of the first row and stored
in first n locations, elements of the 2nd row are stored in next n rows and so on.

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

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

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

Compile Initialization of two dimensional array

int a[3][3]={{1,4,5},{6,4,33},{45,66,54}};
55

float g[3][2]={{2.3,3.4},{4.5,3.4},{2.3,5,3}};

Run time initialization of two dimensional array

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

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

Printf(“enter a no:”);

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

Example:

Find total and average of all elements in double dimensional array.

void main()

int a[3][3];

int s=0;

float avg;

printf(“Data entry for matrix:”);

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

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

printf(“enter a number:”);

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

s=s+a[i][j];
56

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

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

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

printf(“\n”);

avg= (float)s/n;

printf(“sum= %d avg=%f”,s,avg);

Matrix addition

void main()

int a[3][3],b[3][3];

printf(“Data entry for 1st matrix:”);

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

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

printf(“enter a number:”);

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

printf(“Data entry for 2nd matrix:”);


57

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

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

printf(“enter a number:”);

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

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

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

c[i][j]=a[i][j]+b[i][j];

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

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

printf(“%5d”,c[i][j]);

}printf(“\n”);

FUNCTIONS

The best way to handle complex problems to split the problems, called sub
problems that can be handled easily. This we are used to do in our day-to-day
working. Once all these sub problems are solved separately, solutions of these sub
problems can be synthesized to generate the solution of the given complex
problem.
58

Like was, if program to be developed is very large and complex, it is always


recommended to split into two or more functions (subprograms) that can be
developed separately and then integrated.

Defining a Function

The general form of function definition is

returnType functionName (List Of Arguments)

Local declarations

………………………….

………………………….

Executable body

………………………….

 Following are some points to remember while defining functions :

 The first statement of the function must be the function defining statement
specifying the return type, name and formal arguments.

 If the type of the function is omitted, then it is assumed of type integer (int).
But it is recommended that the return type must be explicitly specified.

 Rules for naming a function are same as for variable names.

 The formal argument should neither be constants nor expressions.

Function Prototype

A function prototype is a function declaration that specifies the return type and the
data types of the arguments. The main purpose of the function prototyping is to
prevent errors caused by data type mismatches between the values passed to a
function and the type of values function is expecting.

The general form of a prototype is

returnType functionName (List Of Argument Types);

The following is an example of function prototype for a function that computes


factorial of a given positive integer number:
59

int factorial(int k);

It is important to note that name of the formal argument is optional. Further, names
of formal argument in a function prototype and in the function defining statement
can be different.

Therefore, following is equally valid prototype

int factorial(int);

Accessing a function

Like library functions, the user-defined functions are accessed from a function
simply by its name, including the actual arguments, if any, enclosed within
parenthesis. However, parenthesis must follow the name even if there is no actual
argument to be passed to the function. The actual arguments, if any, must
correspond in number, type, and order with formal arguments can be constants,
variables or expressions.

When the name of the function is encountered, the control is transferred to the
called function. The formal argument s are replaced by the actual arguments and
the execution of the function is carried out. When the return statement is executed
or last statement has finshed its execution, the control is transferred back to the
calling function.

Note: Note that semicolon must follow the function call if it is a solitary statement
but not the function definition. However, if the function call occurs as part of
another statement then semicolon after the function call may or may not be used.
This will be determined the actual; place of call.

The return statement

The syntax of return statement is

return [exp];

where exp can be a constant, variable or expression. Use of parenthesis around exp
is optional. The return statement serves two purposes:

 Execution of return statement immediately transfers control from the


function back to the calling function.

 Whatever is following the return statement is returned as a value to the


calling function.
60

Note: There is key limitation of return statement is that it can return only one
value. If you want your function to return two or more values to the calling function,
you need another mechanism.
61

Passing Arguments to a Function

The mechanism to pass data to a function is via argument list, where individual
arguments are called actual arguments. These arguments are enclosed in
parenthesis after the function name. The actual arguments must correspond in
number, type, order with formal arguments specified in the function definition. The
actual arguments can be constants, variables, array names or expressions.

There are two approaches to passing arguments to a function:

 Call by value

 Call by address, also call by reference

Let us describe one by one.

Call by Value

In this approach, the names of the arguments are used in the function call. In this
way the values of the arguments are passed to the function. When control is
transferred to the calling function, the values of the actual arguments are
substituted to the corresponding formal arguments and the body of the function is
executed. If the called function is supposed to return value, it is returned via return
statement.

Call by Address

In this approach, the addresses of the actual arguments are used in the function
call. In this way the addresses of the actual arguments are passed to the function.
When control is transferred to the called function, the addresses of the actual
arguments are substituted to corresponding formal arguments and the body of the
function is executed. The formal arguments are declared as pointers to types that
match the data types of the actual arguments. This approach is of practical
importance while passing arrays and structures among function, and also passing
back more than one value to the calling functions.

Note: It is important that arguments in a function in C are passed from right to left.

Specifying Argument Data Types

While defining a function, the information to the compiler regarding the return type
of the function and the data types of the arguments must be provided. As described
in the beginning of this chapter that there are two ways to specify the data types of
the formal arguments:
62

1. In the argument list, only the names of the formal arguments are used. The
data types of these arguments are specified before the body of the function
begins. To illustrate this approach, consider an example of defining a
samplefunction() function that takes four arguments. Of these arguments,
first is of type integer, second is of type real, third is of type character, and
fourth one of type integer.
63

The functio0n definition may look like

float samplefunction(arg1, arg2, arg3, arg4);

int arg1, arg4;

float arg2;

char arg3;

Body of the function

2. In the argument list itself, that data type of each argument is specified
individually. Using this approach the definition of the above samplefunction()
function may look like

Float sampleFunction(int arg1, float arg2, char ag3, int arg4)

Body of the function

Throughout the present text, we will consider the later approach.

I hope with this short recap of C language, you will in a position to take off and
enjoy implementing different data structures.
64

CONCEPT OF RECURSION

A powerful concept in the development of programs is the ability for a function to


refer to itself to solve a problem. This control technique, called recursion is an
important concept in computer science and its convenient for a variety of problems
that would be difficult to solve using iterative constructs such as for, while, and do –
while loops. Recursion is used extensively in many of the data structures and the
algorithms in the present text. Recursive functions can be directly implemented in
C. This section introduces recursion, and illustrates the implementation of recursion
through various illustrative examples using C.

Recursion Defined

In mathematics and computer science, recursion means self-reference. A recursive


function, therefore, is a function whose definition is based upon itself. In other
words, words, a function containing either a call statement to itself or a call
statement to another function that may eventually may result in a call statement
back to the original function, then that function is called a recursive function.

In order that the program should not continue indefinitely, a recursive function
must have that following properties:

1. There must be certain criteria, called base criteria, for which the function
does not call itself.

2. Each time the function does call itself(directly or indirectly), it must be closer
to the base criteria, i.e it uses an argument(s) closer than the one it was
given.

A recursive function with these properties is said to be well-defined.

Depth of Recursion

Suppose P is a recursive function. During the execution of a program, which


contains P, we associate level number with each execution of P as follows. The
original execution of P is assigned level 1; and each time P is executed because of
recursive call, its level is one more than the level of execution that had made the
recursive call.

The depth of recursive function P with given set of arguments refer to the maximum
level number of P during its execution.

Example:
65

Factorial Function

The factorial of a positive number n, written as n!, is the product of the positive
integers from 1 to n:

n!= 1.2.3….(n-2).(n-3)

where as

0!=1

From this definition, we have

0!=1

1!=1

2!=1.2=2

3!=1.2.3=6

4!=1.2.3.4=24

5!=1.2.3.4.5=120

and so on.

Observe that

4!=4.3!=24

5!=5.4!=120

And this is true for every positive integer n, that is

n!=n.(n-1)!

Thus, this definition of n! is recursive, since it refers to itself when it uses (n-1)!.
However.

1. The value of n! is explicitly given when n=0. Thus 0 is that base value for n
and

2. The value of n! is defined in terms of a smaller value of n which is closer the


base value.

Thus the factorial function is well defined.


66

Write a program to find gcd of a given number

void main()

int gcd(int a,int b);

printf(“enter two numbers:”);

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

printf(“gcd=%d”,gcd(a,b));

Int gcd(int a,int b)

Int r;

If(b==0)

Return a;

Else

r=a-(a/b)*b;

return(gcd(b,n));

}
67

POINTER
Pointer is a variable that represents the location of the data item where the data
item may be integer , float, char etc.

Advantages of taking pointer variable:

1. Pointer variable easily handles arrays

2. Pointer variable supports dynamic memory management operations

3. Pointer easily handles chars and strings.

4. Using pointer can return multiple values from functions.

5. Pointer reduce length and complexity of the program

6. They increase the execution speed and thus the program execution time

Declaration of pointer variable:

Data type *ptr;

Where ptr is a pointer variable.

Example:

int *a; char *s; float *p;

suppose v is a variable that represents some particular data item. The compiler will
automatically assign memory cells for this data item. The data item can be
accessed if we know the location of the memory cells. The address of v’s memory
location can be determined by the expression &v, where & is a unary operator
called the address operator, that evaluates the address of its operand.

pv=&v;

This new variable is called a pointer to v, since it points to the location where v is
stored in memory. How ever pv represents v’s address not its value. Thus pv is
referred to as a pointer variable.

Address Address
of v of v
pv v
68

the data item represented by v can be accessed by the expression *pv, where * is a
unary operator, that operates only on a pointer variable. Therefore *pv and v both
represents the same data item.

Example:

#include<stdio.h>

main()

int u=3;

int v;

int *pu;

int *pv;

pu=&u;

v=*pu;

pv=&v;

printf(“\n u=%d &u=%X pu=%X *pu=%d”,u,&u,pu,*pu);

printf(“\nv=%d &v=%X pu=%X pv=%d *pv=%d”,v,&v,pv,*pv);

Example:

main()

int u1,u2;

int v=3;

int *pv;

u1=2*(v+5)
69

pv=&v;

u2=2*(*pv+5);

printf(“u1=%d u2=%d”,u1,u2);

PASSING POINTERS TO A FUNCTION:

Pointers are often passed to a function as arguments. This allows data items with in
the calling portion of the program to be accessed by the function, altered with in
the function and then returned to the calling portion of the program to be accessed
by the function, altered with in the function and then returned to the calling portion
of the program in altered form.

When an argument is passed by value, the data item is copied to the function. Thus
any alteration made to the data item with in the function is not carried over into the
calling routine. When an argument is passed by reference, how ever the address of
a data item is passed to the function. The contents of that address can be accessed
freely, either with in the function or with in the calling routine. More ever, any
change that is made to the data item will be recognized in both the function and
calling routine. Thus the use of a pointer as a function argument permits the
corresponding data item to be altered globally from with in the function.

Void main()

int u=1,v=3;

void f1(int x,int y);

void f2(int *pa,int *pb);

printf(“before calling f1: u=%d v=%d”,u,v);

f1(u,v);

printf(“after calling f1: u=%d v=%d”,u,v);

f2(&u,&v);

printf(“after calling f2: u=%d v=%d”,u,v);

void f1(int x,int y)

{
70

Printf(“%d %d”,x,y);

x++;

y++;

void f2(int *pa,int *pb)

printf(“%d %d”,*pa,*pb);

pa++;

pb++;

printf(“%d %d”,*pa,*pb);

Example:

Input two numbers and swap their values

void main()

void swap (int *pa,int *pb);

int a,b;

printf(“enter two number:”);

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

printf(“before swapping a=% b=%d”,a,b);

swap(&a,&b);

printf(“after swapping a=% b=%d”,a,b);

void swap (int *pa,int *pb)

{
71

int k;

k=*pa;

*pa=*pb;

*pb=k;

Operation on pointer variables:


1. Pointer variables stores address of data item

e.g: p=&a;

2. Pointer variables can stores NULL

e.g: p=NULL;

3. An integer value can be added to and subtracted from a Pointer variable

e.g: p++,p--,p+2,p-2

4.two pointer variables can be compared provided both pointer variables have
same data type.

e.g:

if(pa==pb)

7. One pointer variable can be subtracted from another Pointer variables

e.g: pa-pb

chain of pointers:

It is possible to make a pointer to point to another pointer, thus creating a chain of


pointers as shown:

P2 p1 variable
Address 2 Address1 value

Here the pointer variable p2 contains the address of the pointer variable p1 , which
points to the location that contains the desired value. This is known as multi
indirections.
72

A variable that is apointer to a pointer must be declared using additional indirection


operator symbols in front of the name.

Eg:

Int **p2;

This indirection tells the compiler that p2 is a pointer to a pointer int type.

We can accesss the target value indirectly pointed to by pointer by applying the
indirection operator twice.

Eg:

main()

Int x,*p1,**p2;

x=100;

p1=&x;

p2=&p1;

printf(“%d”,**p2);

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. Th e base address is the location of the first element(index )) of the array.
The compiler alos defines the array name as a constant pointer to the first element.
Suppose we declare an array x as follows:

Int x[5]={1,2,3,4,5};

Suppose the base address of x is 1000 and assuming that each integer requires two
bytes, the five elements will be stored as follows:

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


1 2 3 4 5
73

Value

Address 1000 1002 1004 1006 1008

Base address

If we declare p as an integer pointer, then we can make the pointer p to point to the
array x by the following statement:

P=x;

This is equivalent to

P=&x[0];

Now we can access every value of x using p++ to move from one element to
another. The relationship between p and x is shown as:

p=&x[0](=1000)

p+1=&x[1](=1002)

p+2=&x[2](=1004)

p+3=&x[3](=1005)

p+4=&x[4](=1008)

address of x[3]=base address+(3*scale factor of int)

=1000+(3*2)=1006

Write a program to find sum of all elements using pointers.

void main()

int *p,sum,I;

int x[5]={5,9,6,3,7};

i=0;

p=x;

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

s=s+*p;
74

p++;

printf(“sum=%d”,s);

Pointers and multidimensional array

Columns

0 1 2

Rows 0 p
3 1 p+1
5 2 p+2

*(*(P+2)+2)

P : pointer to first row

P+1 : pointer to row

*(*(p+i)+j): value stored in the cell(I,j)

Pointer and character strings:


Strings are treated like character arrays and therefore they are declared and
initialized as follws:

Char str[5]=”good”;

The complier automatically inserts the null character ‘\0’ at the end of string. C
supports an alternative method to create strings using pointer variables of type
char.
75

Eg:

Char *str=”GOOD”

This creates a string for the literal and then stores its address in the pointer str.

The pointer str now points to the first charcter of the string “good” as:

G O O D \0

st

We can also use the run time assignment for giving values to a string pointer.

Char *string1;

string1=”good”

Note that the assignment

string1=”good”

is not a string copy because the variable string1 is a pointer, not a string.

Write a program to find length of string using pointer variable.

void main()

int l,i;

char nam[50];

char *p;

printf(“enter a string:”);

gets(st);

p=st;

for(i=0;*p!=’\0’;i++)

printf(“%c”,*p);

}
76

printf(“length=%d”,l);

Array of pointers

One important use of pointers is in handling of a table of strings.

Consider the following array of strings:

Char name[3][25];

This says that the name is a table containing three names, each with a maximum
length of 25 characters(including null character). The total storage requirements for
the name table are 75 bytes.

We know that rarely the individual strings will be of equal lengths. There fore,
instead of making each row a fixed number of characters, we can make it a pointer
to a string of varying length.

For example:

Char *name[3]={“New Zealand”,”Australia”,”India”};

Declare name to be an arrya of three pointers to character, each pointer pointing to


a particular name as:

Name[0] New Zealand

Name[1] Australia

Name[2] India

This declaration allocates only 28 bytes, sufficient to hold all the characters as
shown:

N e w Z E a l a n d \0

A u s t r A l i a \0

I n d i a \0

Dynamic memory allocation


The process of allocating memory at run time is known as dynamic memory
allocation.
77

There are four library routines known as “memory management functions” that can
be used for allocating and freeing memory during program execution.

Memory allocation functions:

malloc(): allocates request size of bytes and returns a pointer to the first byte of
the allocated

space

calloc(): allocates space for an array of elements, initialize them to zero


and then returns a

pointer to the memory

realloc(): modifies the size of previously allocated space

free(): pointer to the first byte of the allocated space

malloc(): allocates request size of bytes and returns a pointer to the first byte of
the allocated space

Allocating a block of memory: malloc()

A block of memory may be allocated using the function malloc. The malloc function
reserves a block of memory or specified size and returns a pointer of type void. This
means that we can assign it to any type of pointer. It takes the following :

Ptr=(cast type*) malloc(byte size);

Ptr is a pointer of type cast type. The malloc returns a pointer to an area of memory
with size byte size.

x=(int *)malloc(5*sizeof (int))

Write a program for array sorting using dynamic array

main()

int *a;

int n,i,j,k;

printf(“enter how many numbers:”);

scanf(“%d”,&n);

a=(int *) malloc (n*sizeof(int));


78

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

pritnf(“enter a no:”);

scanf(“%d”,(a+i));

for(i=0;i<n-1;i++)

for(j=i+1;j<n;j++)

If(a[i]>a[j])

k=a[i];

a[i]=a[j];

a[j]=k;

free(a);

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

pritnf(“%d”,*(a+i));

free(a);

Calloc()
79

Calloc is another memory allocation function that is normally used for requesting
memory space at run time for storing derived data types such as arrays and
structures. While malloc allocates a single block of storage space , calloc allocates
multiple blocks of storage, each of the same size, and then sets all bytes to zero.

Sysntax:

Ptr=(cast type*) calloc(n,elem-size);

Ex:

struct student

int rollno;

char nm[20];

}*s;

s=(struct student *)calloc(5,sizeof(struct student));

This statement allocates 5 consecutive records for pointer s

free()

This function release memory which are allocated dynamically by malloc and
calloc function.

Syntax:

free(ptr);

Ex:

free(x);

realloc()
This function realloc modifies the size of a dynamic array which are already
allocated by malloc or calloc.

Syn:

ptr=realloc(ptr,new size);

}
80

Storage class:-

To fully define a variable one needs to mention not only its


‘type’ but also its ‘storage class’ . In other words , not only do all variables
have a data type , they also have a storage class .

A variable’s storage class tells us:-

(a) Where the variable would be stored.

(b) What will be the initial value of the variable, if the initial value
is not specifically assigned .(i.e. the default initial value).

(c) What is the scope of the variable ; i.e. in which functions the
value of the variable would be available.

(d) What is the life of the variable ; i.e. how long would the
variable exist.

There are four storage classes in C:-

(a) Automatic storage class

(b)Register storage class

(c) Static storage class

(d)External storage class

Automatic storage class:-

The features of a variable defined to have an have an automatic storage


class are:-

Storage Memory

Default initial value An unpredictable value , which


is often

called a garbage value.

scope Local to the block in which the


variable is defined
81

Life Till the control remains within the


blocks

in which the variable is defined.

main( )

auto int i=1;

auto int i =2

auto int i=3;


printf(“\n %d “, i);

Printf(“%d”,i);

printf(“%d”,i);

Output :- 3 2 1

Register storage class:-

The features of a variable defined to have an have an register storage


class are:-

Storage CPU registers

Default initial value Garbage value.

scope Local to the block in which


the variable is
82

defined

Life Till the control remains within


the blocks

in which the variable is defined.

Register is a memory location which is located inside CPU , hence a value


stored in a CPU register can always be accessed faster than the one which is
stored in memory. We cannot use register storage class for all types of
variables . For example, the following declarations are wrong :

register float q;

register double a;

register long c;

This is because the VPU registers in a microcomputer are usually 16 bit


registers and therefore cannot hold a float value or a double value, which
require 4 and 8 bytes respectively for storing a value.however if you use
the above declarations you won’t get any error message . It would treat the
variables to be of auto storage class.

main( )

register int I;

for( i=1 ; i<=10 ; i++ )

printf(“\n %d “,i); }

Static storage class:-

The features of a variable defined to have an have an static storage class


are:-

Storage Memory

Default initial value Zero

scope Local to the block in which the


variable is defined
83

Life Value of the variable persists


between different

function calls

main ( ) main( )

{ {

increment( ); increment( );

increment( ); increment( );

increment( ); increment( );

} }

increment( ) increment( )

{ {

auto int i =1; auto int I =1;

printf(“%d\n”,i); printf(“%d\n”,i);

i=i+1; i=i+1;

} }

The output of the above program would be:

1 1

1 2

1 3

Like auto variables , static variables are also local to the block in which they
are declared . The difference between them is that static variables don’t
disappear when the function is nom longer persist. If the control comes back
to the same function again the static variables have the same values they
had last time around.

In the above example , when variable I is auto , each time


increment( ) is called it is reinitialized to one. When the function
terminates , i is vanishes and its new value of 2 is lost.
84

The auto variable can be reinitialized again and again but


the static variable can’t be reinitialized .

External storage class:-

The features of a variable defined to have an have an register storage


class are:-

Storage Memory

Default initial value Zero

scope Global

Life As long as the program’s


execution doesn’t

Come to an end

Note:- External variables are declared outside all functions .

int i;

main ( )

Printf(“\ni=%d”,i);

increment( );

increment( );

decrement( );

decrement( );

increment( )

i=i+1;

printf(“\n non incrementing i=%d”,i);

}
85

decrement( )

i=i-1;

printf(“\n non decrementing i= %d”,i);

The output would be:-

i=0

on incrementing i=1

on incrementing i=2

on decrementing i=1

on decrementing i=0

Structure And Union


Array is a collection of same type of elements but in many real life
applications we may need to group different type of logically related data.
For example if we want to create a record of a person that contains name,
age and height of that person , then we can’t use array because all the
three data elements are of different types . To store these related fields of
different data types we can use a structure , which is capable of storing
heterogeneous data. Data of different types can be grouped together under
a single name using structure . The data elements of a structure are referred
to as members.

Defining a structure:-
86

It is a collection of disimilar type of elements stored in sequential manner .

The syntax of a structure definition:-

struct tagname

Datatype member1;

Datatype member2;

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

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

Datatype member N;

};

Here struct is a keyword , which tells the compiler that a structure is being
defined ,memebr1,member2………….memberN are known as members of
the structure and are declared inside curly braces, like int , char ,float
,array ,pointers or another structure type.Tagname is the name of the
structure and it is used further in the program to declare variables of this
structure type.

Declaring structure variables:-

We can declare structure variables in two ways:-

1. With structure definition

2. Using the structure tag

With structure definition:- struct student

char name[20]
int rollno;
float marks;

} stu1,stu2,stu3;
87

Here stu1,stu2 and stu3 are variables of type struct student . when we
declare a variable while defining the structure template, the tagname is
optional .

So we can also declare them as:-

struct

char name[20];
int rollno;
float marks;

}stu1,stu2,stu3;

If we declare variables in this way , then we’ll not be able to declare other
variables of this structure type anywhere else in the program nor can we
send these structure variables to functions.

Using Structure Tag :-

This can be written as :-

struct student

char name[20]
int rollno;
float marks;

};

Struct student stu1,stu2,stu3;

Here stu1,stu2 and stu3 are variables of type student.Each


variables of typen struct student will occupy 26(20+2+4) bytes.

Initialization of structure variables:-

The syntax of initializing structure variables is similar to that


arrays. All the values are given in curly braces .

struct student

{
88

char name[20]
int rollno;
float marks;

} stu1=(“mary”,25,98);
struct student stu2=(“john”,24,67.5);

Here value of members of stu1 will be “mary” for name, 25 for rollno,98 for
marks . Here value of members of stu2 will be “john” for name, 24 for
rollno,67.5 for marks .

Note:-

struct student

char name[20]
int rollno;
float marks=99; /* invalid */

} stu1;

This is invalid because there is no variable called marks , and no memory is


allocated for structure definition .

Accessing Members of a Structure:-

For accessing any member of a structure variable we use the


dot ( . ) operator which is also known as the period or membership operator .
The dot operator is one of the highest precedence operator , its associativity
is from left to right.

The format for accessing a structure member is :-

Structvariable . member

Here on the left side of the dot there should be a variable of


structure type and on right hand side there should be the name of a member
of that STRUCTURE .

For example:-

struct student

{
89

char name[20]
int rollno;
float marks;

};

Struct student stu1,stu2;

Name of stu1 is given by – stu1.name

Rollno of stu1 is given by – stu1.rollno

Marks of stu1 is given by – stu1.marks

Name of stu2 is given by – stu2.name

Rollno of stu2 is given by – stu2.rollno

Marks of stu2 is given by – stu2.marks

These variables can be read, displayed , processed , assigned values or can


be send to functions as arguments.

/* program to display the values of structure members */

#include<stdio.h>
#include<string .h>
struct student

char name[20]
int rollno;
float marks;

};

main( )

struct student stu1={ “Mary”,25,68 };

struct student stu2,stu3;

strcpy(stu2.name,”john”);
90

stu2.rollno=26;

stu2.marks=98;

printf(“Enter name, rollno and marks for stu3 : “);

scanf(“%s %d %f”, stu3.name, &stu3.rollno,&stu3.marks);

printf(“ stu1 : %s %d %.2f \n “,stu1.name,


stu1.rollno,stu1.marks);

printf(“ stu2 : %s %d %.2f \n “,stu2.name,


stu2.rollno,stu2.marks);

printf(“ stu3 : %s %d %.2f \n “,stu3.name,


stu3.rollno,stu3.marks);

Output :-

Enter name, rollno and marks for stu3 : tom 27 79.5

Stu1 : Mary 25 68.00

Stu2 : John 26 98.00

Stu3 : Tom 27 79.50

Assignment of structure variables:-

we can assign values of a structure variable to another


structure variable,

if both variables are defined of the same structure type .

For example:-

/* program to assign a structure variable to another structure variavble */

struct student

char name[20]
int rollno;
float marks;
91

};

main( )

Struct student stu1={“Oliver” , 12,98 };

Struct student stu2;

Stu2=stu1;

Printf(“ stu1 : %s %d %.2f \n “, stu1.name,stu1. rolllno,


stu1.marks);

Printf(“ stu2 : %s %d %.2f \n “, stu2.name,stu2. rolllno,


stu2.marks);

Output:-

Stu1 : oliver 12 98.00

Stu2 : oliver 12 98.0

Storage of structures in Memory:-

The members of structures are stored in consecutive memory


locations.

/* program to show that members of structure are stored in consecutive


memory location */

#include<stdio.h>

main( )

{
92

struct student

char name[20]
int rollno;
float marks;

};

Printf(“Address of name = %u \n “, stu.name);

Printf(“Address of rollno = %u \n “, & stu.rollno);

Printf(“Address of marks = %u \n “, & stu.marks);

Output:-

Address of stu.name =65514

Address of stu.rollno =65519

Address of stu.name =65521

Array of structure:-

Array of structure can be declared as :-

Struct student stu[10];

Here stu is an array of 10 elements , each of which is a structure of type


struct student , means each element of stu has 3 memebrs , which are name
,rollno and marks . these structure can be accssed through subscript
notation. This can be written as :-

St[0].name St[0].rollno St[0].marks

St[1].name St[1].rollno st[1].marks

St[2].name st[2].rollno st[2].marks

………………. ………………. ………………...

……………….. ……………….. …………………

St[9].name st[9].rollno st[9].marks


93

/* program to understand array of structures */

#include<stdio.h>

Struct student

char name[20];

int rollno;

float marks;

};

main( )

int i;

struct student stuarr[10];

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

Printf(“enter name, rollno and marks : “);

Scanf(“%s%d
%f”,stuarr[i].name,&stuarr[i].rollno,&stuarr[i].marks);

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

printf(“%s %d %f \n”,
stuarr[i].anme,stuarr[i[.rollno,stuarr[i].marks);

}
94

Note:- In some compiler tha above program may not work correctly and will
give the message “ floating point formats not linked “ at run time . this
problem occurs because the floating point formats (for scanf( ) and other
related functions ) are not always linked , to reduce the size of executable
file. The solution to this problem will be given in the manual of your
compiler.For example,Borland C suggests the inclusion of these two lines to
solve this problem.

extern unsigned _floatconvert;

#program extrf_floatconvert

Another way to avoid the above problem is to insert a definition of a function


like this-

void link ( )

{ float x,*ptr=&x; }

Array within structures:-

We can have an array as a member of structure . In structure


student , we have take the member name as an array of character.

/* program to understand arrays within structures */

#include<stdio.h>

Struct student

Char name[20];

int rollno;

int submarks[4];

};

main( )

int i,j;

struct student stuarr[3];


95

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

Printf(“Enter data for student %d\n”,i+1);

printf(“Enter name : “);

scanf(“ %s ”, stuarr[i] . name);

printf(“Enter roll number : “);

scanf(“%d” , &stuarr[i].rollno);

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

printf(“Enter marks for subject %d : “,j+1);

scanf(“%d”,&stuarr[i].submarks[j]);

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

Printf(“Data of student %d\n”,i+1);

Printf(“Name : %s , Roll number : %d \n Marks : “,


stuarr[i].name,stuarr[i].rollno);

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

printf(“%d “, stuarr[i].submarks[j]);

printf(“\n”);

Here stuarr is a variable of type struct students then:-

Stuarr[0].submarks[0] – Denotes the marks of first student In first subject.

Stuarr[4].submarks[3] – Denotes the marks of fifth student in fourth subject.


96

Stuarr[0].name[0] – Denotes the first character of name member of first


student .

Stuarr[5].name[7] – Denotes the eighth character of name member of sixth


student .

Nested structures( structure within structure)

If the structure is defined within another structure is called nested


structure. A structure variable can be a member of another structure .

Syntax:-

Struct tag1

{
Member1;

Member2;

Struct tag2

Member1;

Member2;
…………..

Member m;

} var1;

………………….

Member n;

}var2;
97

For example:-

struct student

char name[20];

int rollno;

struct date

int day;

int month;

int year;

} birthdate;

float marks;

}stu1,sty2;

Here we have defined a structure date inside the structure student . This
structure date has three members day, month ,year and birthdate is a
variable of type struct date . we can access the members of inner struc
ture as:-

Stu1.birthdate.day day of birthdate of stu1

Stu1.birthdate.month month of birthdate of stu1

Stu1.birthdate.year year of birthdate of stu1

Stu2.birthdate.day day of birthdate of stu2

Pointers to structures:-

We have studied that pointer is a variable which holds the


starting address of another variable of any data type like int, float, char .
Similarly we can have pointer to structure , which can point to the starting
address of a structure variable. These pointers are called structure pointers
and can be declared as :-
98

/* program to understand pointers to structure */

#include<stdio.h>

Struct student

char name[20]

int rollno;

int marks

};

main( )

Struct student stu ={ “mary”,25,68} ;

Struct student *ptr=&stu;

Printf(“Name : %s \t”,ptr->name);

Printf(“Rollno : %d \t “,ptr->rollno);

Printf(“marks : %d \t “,ptr->marks);

Here ptr is a pointer variable that can point to a variable of type struct
student. We will use the & operator to access the starting address of a
structure variable, so ptr can point to stu by writing:- ptr=&stu

There are two ways of accessing the members of structure through the
structure pointer:-

1. (*ptr).name Here paranthesis are necessary because dot


operator are higher precedence than th * operator

2. Ptr->name

We can also have pointers that point to individual members of a structure


variable.

For example:-
99

int *p=&stu.rollno;

float *ptr=&stu.marks;

pointer within structure:-

A pointer can also used as a member of structure . For


example we can define a structure like this :-

Struct student

char name[20];

int *ptrmem;

};

Struct student stu , *stuptr=&stu;

Here ptrmem is pointer to int and is a member of the structure student.

To access the value of ptrmem , we’ll write

Stu.ptrmem or stuptr->ptrmem

To access the value pointer to by stu.ptrmem , we’ll write

*stu.ptrmem or *stuptr -> ptrmem

Since the priority of dot and arrow operators is more than that of
dereference operator , hence the expression *stu.ptrmem is equivalent to
*(stu.ptrmem) and the expression *stuptr->ptrmem is equivalent to *(stuptr-
>ptrmem)

Structures and functions :-

Passing structure member as argument:-

/* program to understand how structure members are sent to a function */

#include<stdio.h>

#include<string.h>

Struct student
100

char name[20]

int rollno;

int marks

};

display(struct student);

main( )

Struct student stu1={“John”,12,87};

Struct student stu2;

Strcpy(stu2.name, “mary”);

Stu2,rollno=18;

Stu2.marks=90;

display(stu1.name,stu1.rollno,stu1.marks);

display(stu2.name, stu2.rollno,stu2.marks);

display(char name[ ], int rollno , int marks)

Printf(“Name : %s \t”,name);

Printf(“rollno :%d\t” ,rollno);

Printf(“marks : %d \n”,marks);

UNION

Union is a data structure where all the union members will refer to the single
location which are allocated by union whose member size is larger.
101

Its syntax is same as structure like:

Union tag

Member1;

Member2;

…..

Member n;

}v;

The difference between structure and union is in area of memory allocation


process of members. In structure memory is allocated for each data member
but in union memory is allocated for a single member whose is large.

Eg:

struct key union key

{ {

int a; int a;

float a; float b;

char c; char c;

}k; }k; b
b
c

a b c a b c

2 4 1

Eg:

struct student
102

int rollno;

char nm[20];

float m1,m2,m3;

union result

char gd;

char div[3];

}res;

}s;

DATA FILES
Many applications require that information be written to or read from an auxiliary
storage devices. Such information is stored on the device in the form of a data file.
Thus data file allow us to store information permanently and to access and alter
that information when ever necessary.

In c, an extensive set of library functions is available for creating and processing


data files.

There are two different types of data files. Stream oriented data files and system
oriented data files.

Stream oriented data files are generally easier to work with than system oriented
data files and are there fore more commonly used.

Stream oriented data files can be divided into two categories . In the first category
are data files comprising consecutive characters. These characters can be
interpreted as individual data items or as components of strings or numbers. The
manner in which these characters are interpreted is determined either by the
particular library function used to transfer the information or by format specification
with in the library function.

The second category of stream oriented data files , often referred to as unformatted
data files, organizes data into blocks containing contiguous bytes of information.
These blocks represent more complex data structures such as arrays, structure. A
103

separate set of library functions is available for processing stream oriented data
files of this type. These library function provide single instructions that can transfer
entire arrays or structure to or from data files.

OPENING AND CLOSING A DATA FILE:


When working with a stream oriented data file, the first step is to establish a buffer
area, where information is temporarily stored while being transferred between the
computer’s memory and the data file. This buffer area allows information to be read
from or written to the data file more rapidly than would otherwise be possible. This
buffer area is established by writing

FILE *ptr;

Where FILE is a special structure type that establishes the buffer area, and ptr is a
pointer variable that indicates the beginning of the buffer area. The structure FILE
is defined with in stdio.h header file.

The pointer ptr is refered to as a stream pointer or simply as a stream.

The library function fopen is used to open a file. This function is typically written as

Ptr=fopen(filename,file type);

Where file name and file type are strings that represents the name of the data file
and the manner in which the data file will be utilized respectively.

File type description

r open a existing file for reading only

w open a new file for writing only

a open an existing file for append only

r+ open an existing file for both reading and writing

w+ open a new file for both reading and writing

a+ open an existing file for both reading and appending.

Eg:

FILE *fp;

fp=fopen(“x.txt”,”w”);
104

CLOSING A FILE

fclose function is used to close a file.

Syntax: fclose(fp);

Single char input & output for a file


fputc():

this stores a single char in a file.

Syntax: fputc(ch,fp);

Where ch is a character and fp is the file pointer. This function stores a single char
ch into file.

Ex:

Input a string and store in upper case

#include<process.h>

FILE *fp;

fp=fopen(“text.txt”,”w”);

while(ch=getchar()!=’\n’)

Ch=toupper(ch);

fpuc(ch,fp);

fclose(fp);

fp=fopen(“text1.text”,”r”);

if(!fp)

printf(“file not exist”);

exit(0);
105

While((ch=fgetc(fp))!=EOF)

putchar(ch);

fclose(fp);

Copy the contents of a source file to target file

Void main()

char ch;

FILE *fp,*fp1;

fp=fopen(“x.txt”,”w”);

fp1=fopen(“y.txt”,”w”);

if(!fp)

printf(“file does not exist”);

exit(0);

While((ch=fgetc(fp))!=EOF)

fputc(ch,fp);

fclose(fp);

fclose(fp1);
106

Single string input and output for a file

fputs():

syntax:

fputs(s,fp);

stores a single string into a file.

fgets():

syntax:

fgets(s,I,fp);

Reads a string containing I characters from file fp.

Example:

Read line of text from user and store in a file

main()

char st[80];

FILE *fp;

fp=fopen(“x.txt”,”w”);

while(strlen(gets(st))>0)

fputs(st,fp);

fputc(‘\n’);

fclose(fp);

fp=fopen(“x.txt”,”r”);

while(fgets(st,79,fp)!=NULL)
107

puts(fp);

fclose(fp);

Storing and reading integer data for a file.

The getw and putw are integer oriented functions. They are similar to the getc and
putc function and are used to read and write integer values from a file.

putw():

This function stores an integer value to a file.

Syntax:

putw(v,fp);

where v is a integer variable, fp is file pointer.

getw():

This function stores an integer value to a file.

Syntax:

int g=getw(v,fp);

where v is a integer variable, fp is file pointer and g is a integer variable.

Example:

Inputs n numbers and store only evens in a file.

Ans:

main()

Int n;

FILE *fp;

int a,i;

fp=fopen(“even.dat”,”w”);
108

printf(“how many nos:”);

scanf(“%d”,&n);

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

printf(“enter a no:”);

scanf(“%d”,&a);

if(a%2==0)

fpuw(a,fp);

fclose(fp);

fp=fopen(“even.dat”,”r”);

while(a=fgetw(fp))

printf(“%d”,a);

fclose(fp);

Formatted data Input and output to function:

For formatted reading and writing of character, string, integers, float data uses two
library functions:

fscanf() and fprintf().

fscanf():
109

Sysntax: fscanf(fp,”string format”,&v1,&v2…);

fscanf function stores different type of data in a file.

fprintf():

Sysntax: fscanf(fp,”string format”,&v1,&v2…);

fprintf function reads different type of data from a file.

Example:

Read employee data items from user and store in a file.

main()

char ch=’y’;

struct emp
{

int empno;

char nm[20];

float sal;

}e;

FILE *fp;

fp=fopen(“emp.dat”,”w”);

while(ch==’y’)

printf(“enter empno,nm,sal:”);

scanf(“%d%s%f”,&e.empno,e.nm,&e.sal);

fprintf(fp,”%d%d%f”\n”,e.empno,e.nm,&e.sal);

printf(“want to continue y/n:”);

fflush(stdin);

scanf(“%c”,&ch);

}
110

fclose(fp);

fp=fopen(“emp.dat”,”r”);

while((fscanf(fp,”%d%s%f”,&e.empno,e.nm,&e.sal)!=NULL)

printf((“\n %d%s%f”,e.empno,e.nm,e.sal);

fclose(fp);

Unformatted input and output for a file:

fwrite():

syntax:

fwrite(s,I1,i2,f);

send i2 data items each of zise i1 bytes from string s to file f.

eg:

fwrite(&e,sizeof(e),1,fp);

fread():

syntax:

Read i2 data items each of size I,bytes from file f to string s.

Eg:

fread(&e,sizeof(e),1,fp);

Read employee data items from user and store in a file.

main()

char ch=’y’;

struct emp
{
111

int empno;

char nm[20];

float sal;

}e;

FILE *fp;

fp=fopen(“emp.dat”,”w”);

while(ch==’y’)

printf(“enter empno,nm,sal:”);

scanf(“%d%s%f”,&e.empno,e.nm,&e.sal);

fwrite(&e,sizeof(e),1,fp);

printf(“want to continue y/n:”);

fflush(stdin);

scanf(“%c”,&ch);

fclose(fp);

fp=fopen(“emp.dat”,”r”);

while((fwrite(&e,sizeof(e),1,fp))

printf((“\n %d%s%f”,e.empno,e.nm,e.sal);

fclose(fp);

Command line arguments:


The parenthesis of main function may contain special arguments that allow
parameters to be passed to the main from the operating system. The arguments
are traditionally called as argc and argv. Argc is an integer value which counts
112

number of arguments and argv is and array of strings which stores the argument
list.

Syntax:

main(int argc,char *argv[])

example:

copy data from source file to target file.

#include<stdio.h>

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

FILE *fp1,*fp2;

Char ch;

If(argc!=3)

pritnf(“syntax error…:”);

exit(0);

If(strcmp(argv[1],argv[2])==0)

pritnf(“same file can’t be copied”);

exit(0);

fp1=fopen(argv[1],”r”);

if(!fp1)

printf(“file does not exist”);

exit(0);

}
113

fp2=fopen(argv[2],”w”);

while((ch=fgetc(fp1))!=EOF)

fputc(ch,fp2);

fclose(fp1);fclose(fp2);

C PREPORCESSOR:
The c preprocessor is a program that processes our source program that processes
our source program before it is passed to the compiler.

The preprocessor offers several features called preprocessor directives. Each of


these preprocessor directives begin with a # symbol. The directives can be placed
any where in a program but are most often placed at the beginning of a program
before main().

The types of preprocessors are:

1. Macro expansion

2. File inclusion

3. Contional compilation

4. Miscellaneous directives.

Macro expansion:
# define upper 25

This statement is called “macro definition” or more commonly, just a macro.

The macro template and its macro expansion are separated by blanks or
tabs. A space between # and define is optional. It is never terminated by
semi colon.

Eg:

#define PI 3.1415
114

main()
{

float r=6.25;

float area;

area=PI * r*r;

printf(“\n area of circle=%f”,area);

Eg2:

#define AND &&

#define ARANGE (a>25 AND a<50)

Main()

Int a=30;

If (ARANGE)

printf(“with in range”);

else

printf(“out of range”);

Macro with arguments:

#define AREA(x) (3.14 *x*x)

main()

Float r1=6.25,r2=2.5,a;

a=AREA(r1);

printf(“area of circle=%f”,a);
115

a=AREA(r2);

printf(“area of circle=%f”,a);

File inclusion:
The preprocessor command for file inclusion looks like this:

#include “filename”

And its simply causes the entire contents of file name ro be inserted into the
source code at that point in the program.

Actually there exist two ways to write #include statement.

These are:

#include “file name”

#include <filename>

The meaning of each of these forms is given below:

#include “goto.c”

This command would look for the goto.c in the current directory as well as
the prescribed list of directories as mentioned in the include in the include
search path that might have been setup.

#include<goto.c>

This command would look for the file goto.c in the specified list of directories
only.

Conditional compilation:
116

We can, if we want have the compiler skip over part of a source code by
inserting the processing commands #ifdef and #endif, which have the
general form:

#ifdef macroname

Statement 1;

Statement 2;

Statement 3

#endif

Eg:

#define background 5

#ifdef background

#define background 4

#else

#define background 3

#endif

Miscellaneous directives:

#undef directive
In order to undefine a macro which has been already define we can use
#undef

Eg:

#undef max
117

You might also like