Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

C

What is a Language ? ............................................................................................................ 4


(1) Machine Languages :- .................................................................................................... 4
(2) Assembly Languages :- .................................................................................................. 4
(3) Procedure Oriented Languages ...................................................................................... 4
What is language Translators?............................................................................................. 5
(1) Compiler :- ..................................................................................................................... 5
(2) Interpreters :- .................................................................................................................. 5
Difference of Compiler Interpreter :-................................................................................ 5
Why C language ? ............................................................................................................... 5
FEATURES OF C LANGUAGE.......................................................................................... 6
FLEXIBLILITY:.................................................................................................................. 6
PORTABILITY: .................................................................................................................. 6
COMPACTNESS: ............................................................................................................... 6
REUSABILITY: .................................................................................................................. 6
C AS MIDDLE LEVEL LANGUAGE ................................................................................ 6
Problem oriented languages or high languages : ................................................................. 6
Machine oriented languages of Low Level Languages : ..................................................... 6
C as Middle Level Language : ............................................................................................. 6
BASIC STRUCTURE OF C PROGRAM........................................................................... 7
Documentation Section:....................................................................................................... 7
Link Section:........................................................................................................................ 7
Definition Section: ............................................................................................................... 7
Global Declaration Section : ................................................................................................ 7
Main Function Section :....................................................................................................... 7
Subprogram Or Sub Function Section : ............................................................................... 7
VARIABLES .......................................................................................................................... 8
VARIABLE NAMING CONVENTION............................................................................. 8
KEYWORDS......................................................................................................................... 8
Data Types In C : ................................................................................................................... 8
Character :............................................................................................................................ 9
Integer : ................................................................................................................................ 9
Float : ................................................................................................................................... 9
Long : ................................................................................................................................. 10
OPERATORS....................................................................................................................... 11
Arithmetic operators :-....................................................................................................... 11
Relational Operators :-....................................................................................................... 11
Logical Operators : ........................................................................................................... 12
Assignment Operators:....................................................................................................... 12
Increment and Decrement Operators : ............................................................................... 12
Conditional operators :....................................................................................................... 13
Sizeof Operator : ................................................................................................................ 13
Bitwise operators : ............................................................................................................. 13
The Ones Complement operator :..................................................................................... 13
Logical bit wise operators :................................................................................................ 14
Shift operators :.................................................................................................................. 14
Comma Operator :.............................................................................................................. 14
Precedence and Associativity Table .................................................................................. 15
DATA INPUT AND OUTPUT ........................................................................................... 16
Printf() function : ............................................................................................................... 16
1
Scanf() Function : .............................................................................................................. 17
Single character input the getchar function : .................................................................. 18
Single character output The putchar function:................................................................ 18
Decision Control Structure : ............................................................................................... 19
The if-else statement: ......................................................................................................... 19
LOOP CONTROL STRUCTURE..................................................................................... 21
While statement : ............................................................................................................... 21
FOR statement : ................................................................................................................. 23
BREAK STATEMENT: .................................................................................................... 25
CONTINUE STATEMENT .............................................................................................. 25
SWITCH-CASE Statement :.............................................................................................. 26
THE GOTO STATEMENT :............................................................................................. 28
ARRAY...................................................................................................................................... 29
DEFINING AN ARRAY :................................................................................................. 29
Single Dimension Array .................................................................................................... 29
MULTIDIMENTIONAL ARRAY.................................................................................... 29
Two Dimension Array ....................................................................................................... 30
ARRAY AND STRINGS .................................................................................................. 31
The gets and puts functions: .............................................................................................. 31
Strlen() ............................................................................................................................... 32
Strcpy() .............................................................................................................................. 32
Strcat()................................................................................................................................ 32
Strcmp() : ........................................................................................................................... 33
PROCESSING AN ARRAY : ........................................................................................... 33
FUNCTION............................................................................................................................... 34
DEFINING A FUNCTION : ............................................................................................. 34
ACCESSING A FUNCTION : .......................................................................................... 35
Data-type name(); .............................................................................................................. 36
PASSING ARGUMENT TO A FUNCTIN : .................................................................... 36
SPECIFYING ARGUMENT DATA TYPES ; ................................................................. 36
CATEGORY OF FUNCTION : ........................................................................................ 37
No arguments and not return values: ................................................................................. 37
Arguments with return values :.......................................................................................... 37
RECURSION :................................................................................................................... 37
THE SCPOE AND LIFETIME OF VARIABLES IN FUNCTION : ............................... 38
Automatic variables : ......................................................................................................... 38
External variables : ............................................................................................................ 38
MULTIFILE PROGRAMS : ............................................................................................. 40
Static variables :................................................................................................................. 41
Register variable: ............................................................................................................... 41
PASSING ARRAYS TO A FUNCTION: ......................................................................... 41
PASSING BY BALUE APPROACH................................................................................ 42
PASS BY REFERENCE APPROACH............................................................................. 43
LIBRARY FUNCTION:.................................................................................................... 43
POINTERS........................................................................................................................... 44
AND & OPERATORS ...................................................................................................... 44
POINTER DECLARATIONS : ......................................................................................... 45
PASSING POINTER TO A FUNCTION : ....................................................................... 45
POINTER AND ONE DIMENTSIONAL ARRAY.......................................................... 47
OPERATIONS ON POINTERS........................................................................................ 48
POINTERS AND MULTIDIMENSIONAL ARRAYS : .................................................. 48
2
ARRAY OF POINTERS: .................................................................................................. 49
PASSING POINTER TO FUNCTIONS : ......................................................................... 51
Structures ................................................................................................................................... 52
Simple Structures............................................................................................................... 52
The struct Keyword............................................................................................................ 52
Defining and Declaring Structures..................................................................................... 52
Accessing Structure Members ........................................................................................... 53
Arrays of Structures ........................................................................................................... 54
Pointer To Structure........................................................................................................... 56
Passing Structures as Arguments to Functions .................................................................. 56
FILE MANAGEMENT....................................................................................................... 58
Opening and closing a data file :........................................................................................ 58
Input-output operation on file : .......................................................................................... 59
THE GETC AND PUTC FUNCTIONS : .......................................................................... 59
THE FGETS AND FPUTS FUNCTIONS : ...................................................................... 60
THE FSCANF AND FPRINTF FUNCTIONS : ............................................................... 61
THE FREAD AND FWRITE FUNCTIONS :................................................................... 61
RANDOM ACCESS TO FILES :...................................................................................... 61
ftell : ................................................................................................................................... 61
rewind : .............................................................................................................................. 62
DYNAMIC MEMORY ALLOCATION........................................................................... 63
Malloc().............................................................................................................................. 63
Calloc() .............................................................................................................................. 63
Program List......................................................................................................................... 64
C Theory ............................................................................................................................... 69

























3
C
WHAT IS A LANGUAGE ?
Language is a collection of words and symbols which can be used to perform certain task or
activities and to establish a communication between person to person.
In the same manner computer languages are the collection of predefine key words
which can be used to perform certain task and to communicate between to entities like between
two machines or between human and computers or computers and others peripherals.

There are three different level of programming languages. They are
(1) Machine languages (low level)
(2) Assembly languages
(3) Procedure Oriented languages (high level)
(4) Fourth Generation languages (4 GLS)

(1) Machine Languages :-
Computers are made of No. of electronic components and they all are two state electronic
components means they understand only the 0 (pulse) and 1 (non pulse). Therefore the
instruction given to the computer must be written using binary numbers. 1and 0.
Computers do not understand English or any other language but they only understand or
respond to binary numbers (0 and 1). So each computer has its own Machine languages.

(2) Assembly Languages :-
As it was very tedious to understand and remember 0s representing numerous data and
instruction. So to resolve this problem mnemonics codes were developed. For example add is
used as symbolic code to represent addition. SUB is used for subtraction. They are the
symbolic representation of certain combination of binary numbers
for example
S U B
Which represents certain actions as computer understand only Machine language instructions a
program written in Assembly Language must be translated into Machine languages. Before it
can be executed this translation if done by another program called assembler. This assembler
will translate mnemonic codes into Machine languages.

(3) Procedure Oriented Languages
In earlier assembly languages assembler programs produced only one Machine languages
instruction for every assembly languages instruction. So to resolve this problem now assembler
were introduced. Which can produce several machine level instructions for one assembly
language instruction. Thus programmer was relieve from the task of writing and instruction for
every machine operation performed. These languages contains set of words and symbols and
one can write program with the combination of these keywords. These languages are also
called high level languages. Basic, Fortran, Pascal and COBOL. The most important
characteristic of high level languages is that it is machine independent and a program written in
high level languages can be run on any computers with different architecture with no
modification or very little modification.
.




4
WHAT IS LANGUAGE TRANSLATORS?
As we know that computer understand only the instruction written in the Machine
language. Therefore a program written in any other language should be translated to Machine
language. For this purpose special programs are available they are called translators or
language processors. This special programs accept the user program and check each statement
and produces a corresponding set of Machine language instructions. There are two types of
Translators.

(1) Compiler :-
A Compiler checks the entire program written by user and if it is free from error and mistakes
then produces a complete program in Machine language known as object program. But if it
founds some error in program then it does not execute the single statement of the program. So
compiler translate whole program in Machine language before it starts execution.

(2) Interpreters :-
Interpreters performs the similar job like compiler but in different way. It translates (Interprets)
one statement at a time and if it is error free then executes that statement. This continues till
the last statement in the program has been translated and executed.
Thus Interpreter translates and executes the statement before it goes to next statement. When it
founds some error in statement it will immediately stop the execution of the program.
Since compiler of Interpreter can translate only a particular language for which it is
designed one has to use different compiler for different languages.

Difference of Compiler Interpreter :-
Error finding is much easier in Interpreter because it checks and executes each statement at a
time. So wherever it fine some error it will stop the execution. Where Compiler first check all
the statement for error and provide lists of all the errors in the program.
Interpreter take more time for the execution of a program compared to Compilers
because it translates and executes each statement one by one.

WHY C LANGUAGE ?
In early of 1960 there were many languages available but they were used for some
specific purpose. For example Cobol was used for commercial application Fortran was used for
some scientific and engineering application. So at this stage people were searching some
language which can fulfill the need of all type of application. So invention of different
language taken place.
The C language becomes very popular due to its robustness rich set of built in
function and operators that can be used to write any complex program.

Sr. No. Year Language Developer Remarks
1 1960 ALGOL International Committee Too General, Too Abstract
2 1963 CPL Cambridge University
3 1967 BPCL Martin Richards &
Cambridge University

4 1970 B Kent Thomson at AT&T
Laboratory

5 1972 C Denis Ritchie at AT&T
Laboratories
Modular,General,

5
FEATURES OF C LANGUAGE
There are several reasons why many computer professionals feel that C is at the top of the list :

FLEXIBLILITY:
C is a powerful and flexible language. C is used for projects as diverse as operating system,
word processor, graphics, spreadsheets and even compilers for other language. C is a popular
language preferred by professional programmers. As a result, a wide variety of C compilers
and helpful accessories are available.
PORTABILITY:
C is a portable language. Portable means that a C program written for one computer system can
be run on another system with little or no modification. Portability is enhanced by the ANSI
standard by C, the set of rules for C compilers.
COMPACTNESS:
C is a language of few words, containing only a handful terms, called keywords, which serve
as the base on which the languages functionality is built. You might think that a language with
more keyword would be more powerful. This isnt true. As you will find that it can be
programmed to do any task.
REUSABILITY:
C is modular, C code can and should be written in routine called functions. These functions can
be reused in other applications or programs. By passing pieces of information to the function,
you can create useful, reusable code.

C AS MIDDLE LEVEL LANGUAGE
All programming languages can be divided into two categories:

Problem oriented languages or high languages :
Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These
languages have been designed to give a better programming efficiency, faster program
development. Generally these languages have better programming capability but they are less
capable to deal with hardware or Hardware related programming.

Machine oriented languages of Low Level Languages :
Examples of languages falling in this category are Assembly language and Machine Language.
This languages have been designed to give a better machine efficiency i.e. faster program
execution. Generally these languages have better hardware programming capability but it is
very difficult and tedious to do create complex application like and business application or
some commercial application

C as Middle Level Language :
C stands in between these two categories. Thats why it is called a Middle Level Language,
since it was designed to have both; a relatively good programming efficiency (as compared to
Machine Oriented Language) and a relatively good machine efficiency (as compared to
Problem Oriented Language).








6
BASIC STRUCTURE OF C PROGRAM
C program can be viewed a s group of building blocks called functions. A function is a
subroutine that may include one or more statement designed to perform a specific task. A C
program may contain one or more section as shown below :
Documentation Section
Link Section
Definition Section
Global declaration Section
Main() function section
{

Declaration Part
Executable Part
}
Subprogram Section
Function1 ()
{
}
Function2 ()
{
}

Documentation Section:
This section contains set of comments lines consist of details like program name, author name
and purpose or functionality of the program.
Link Section:
This section consist of instructions to be given to the compiler to link functions from the
system library. For example if you want to use some mathematical function then you have to
define link for math.h file in link section. For Example
# include<stdio.h>
# include<math.h>
Definition Section:
This section defines all the symbolic constants. For example PI=3.14. By defining symbolic
constant one can use these symbolic constant instead of constant value.
# define PI 3.14
# define Temp 35
Global Declaration Section :
This section contains the declaration of variables which are used by more then more then one
function of the program.
Main Function Section :
A main() function is a heart of any C language program. Any C program is made up of 1 or
more then 1 function. If there is only 1 function in the program then it must be the main
program. An execution of any C program starts with main() function.
Subprogram Or Sub Function Section :
They are the code section which are define outside the boundary of main function. This
function can be called from any point or anywhere from the program. Generally they are
define to solve some frequent tasks.


7
VARIABLES
A variable is a named data storage location in your computers memory. By using a variables
name in your program, you are, in effect, referring to the data stored there.

VARIABLE NAMING CONVENTION
To use variables in your C programs, you must know ho to create variable names in
C,variables names must adhere to the following rules:
The name can contain letters, digits, and the underscore character(_).
The first character of the name must be a letter. The underscore is also a legal first
character, but its use is not recommended.
Case matters (that is uppercase and lowercase letters). Thus, the names count and Count
refer to two different variables.
C keywords cant be used as variable names. A keyword is a word that is part of the C
language.

KEYWORDS
There are words with specific meaning to C language system. They are known as keywords
of C language. Keyword must not be used as variable names. There are 32 keywords in C
language. Which are as under :

DATA TYPES IN C :
C language has very rich set of data types. At presently we will go through some of the basic
data types available in C.

Variable Type Keyword Bytes
Required
Range Format
Character
(signed)
Char 1 -128 to +127 %c
Integer
(signed)
Int 2 -32768 to +32767 %d
Float
(signed)
Float 4 -3.4e38 to +3.4e38 %f
Double Double 8 -1.7e308 to + 1.7e308 %lf
Long integer
(signed)
Long 4 2,147,483,648 to
2,147,438,647
%ld
Character
(unsigned)
Unsigned char 1 0 to 255 %c
Integer
(unsigned)
Unsigned int 2 0 to 65535 %u
Unsigned long
integer
unsigned long 4 0 to 4,294,967,295 %lu
Long double Long double 10 -1.7e932 to +1.7e932 %Lf
Auto double int struct break
Else long switch case enum
Register typeof char external return
Union const float short unsigned
Continue for signed void default
Goto sizeof volatile do if
Static while
8
Character :
To access and to store single character it use char data type in C. Char data type occupies 1
bytes. It means that char data type use 1 byte of memory to store some character value.

Declaration of character variable :
char ans;
Assigning values to character variable :
Ans=y;

8 7 6 5 4 3 2 1
Sign
2
7
2
6
2
5
2
4
2
3
2
2
2
1
2
0


Above given is a general structure of character variable. The leftmost bit is used to indicate the
positive or negative value of a variable. So the range for character variable is 2
7
to 2
7
1
.means 128 to 127.

Integer :
To access and to store any integer value int data type is use. Cs int data type occupies 2 bytes
in the memory.
To declare any integer variable :
Int rollno;
Int accno;
To assign or to store integer value in this variable:
Rollno=10;
Accno=100;
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
S
i
g
n


2
15
2
14
2
13
2
12
2
11
2
10
2
9
2
8
2
7
2
6
2
5
2
4
2
3
2
2
2
1
2
0

Above given is a general structure of integer variable. The leftmost bit is used to indicate the
positive or negative value of a variable. So the range for integer variable is 2
15
to 2
15
1
.means 32768 to 32767.

Float :
To access and to store any real value float data type is use. Cs float data type occupies 4
bytes in the memory.

To declare any float variable :
Float per;
Float rate;
To Assign or to store some real value
Per=70.20;
Rate=123.45





9

32 1
S
i
g
n

2
31
2
0

Above given is a general structure of float variable. The leftmost bit is used to indicate the
positive or negative value of a variable. So the range for float variable is 231 to 2
31
1 .
Means -3.4e38 to +3.4e38

Long :
To access and to store any integer value long data type is use. Cs long data type occupies 4
bytes in the memory.
To declare any long variable :
long account;
long price;
To Assign or to store some long value
account=123456;
Rate=98765;
32 1
S
i
g
n

2
31
2
0

Above given is a general structure of long variable. The leftmost bit is used to indicate the
positive or negative value of a variable. So the range for long variable is 231 to 2
31
1 .
Means - 2,147,483,648 to +2,147,438,647






















10

OPERATORS
Operator is symbol, which represents, a particular operation that can be performed on some
data. The data itself (which can be either a variable or a constant) is called the operand. The
operator thus operates on operand. They are Classified as
(1) Arithmetic (2) relational (3) logical
(4) Assignment (5) increment/decrement
(6) conditional (7) bitwise (8) special

Arithmetic operators :-
There are five arithmetic operators in C. They are :

OPERATOR PURPOSE
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division

Examples (Suppose A=10 and B=3)
Expression Values
A+b 13
a-b 7
A*b 30
A/b 3
A%b 1

Relational Operators :-
There are four relational operators in C. They are:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
The associatively of these operators is left-to-right. Closely associated with the relational
operator are the following two equality operators :
= = equal to
! = not equal to

Suppose that i, j and k integer variable whose values are 1,2 and 3 respectively, Seven logical
expressions involving these variables are shown below. :

Expression Interpretation Value
i<j True 1
(i+j)>=k True 1
(j+k)>(I+5) False 0
K!=3 False 0
J = = 2 True 1



11

Logical Operators :
C provides three logical operations. They are :

Operator Meaning
&& AND
|| OR
! NOT

These operators are referred to as logical AND logical OR and logical NOT respectively.
The following table shows the result of the combined expressions depending on the value of
the expression :

Operands Results
Exp1 Exp2 Exp1 && exp2 Exp1 || exp2
0 0 0 0
0 Non-zero 0 1
Non-zero 0 0 1
Non-zero Non-zero 1 1

The associatively us left-to-right.

Assignment Operators:
Assignment operators are use to form assignment expressions, which assign the value of an
expression to an identifier. The most commonly used assignment operator is =. Assignment
expression that make use of this operator are written in the form

Identifier = Expression
a= a+1 a+=1
a=a-1 a-=1
a=a*( c + d) a*=(c + d)
a=a/(n-1) a/=(n-1)
a=a%10 a%=10

Increment and Decrement Operators :
C offers two special operator ++ and called increment and decrement operators,
respectively. There are unary operators since they operator on only one operand. The
operand has to be a variable and not a constant. Thus the expression a++ is valid as 6++ is
invalid. The use of these operates resulting incrementing or decrementing value of the variable
is 1. So the expression a++ increment the value of a by 1 and the expression a- - decrements a
by 1. These operators can be used either before or after their operand. (i.e. in either prefix or
postfix position) so we can have a++(postfix) and ++a (prefix). Prefix and postfix have some
effect if they are used in an isolated statement. For example, the effect of the following
statements would be same :
a++;
++a;
However prefix and postfix operators have different effects when used in association with
some other operator in c statement. For example, if we assume the value of a variable to be 5
and then assign that new value to b. The effect is exactly same. If the following two statements
have been executed :
12
b = a++; b=++a;
On the other had, execution of the statement b = a++; will be first set the value of b to 5 and
then increases the value of a to 6. The effect is now same as if the following statement had
been executed :
b = a; b= a+1;
[ Note : First precedence : R->L associatively)

Conditional operators :
Simple conditional operations can be carried out with the conditional operator (?:) An
expression that makes the use of the conditional operator is called a conditional expression.
Conditional operators are also known as turnery operators.
Syntax:
(condition) ? true : false
Exp1 ? Exp2 : Exp3
Here if condition is evaluated as true then value of exp2 will be return and if condition is
evaluated as false then exp3 will be return.
For example
T=(I<0) ? 0 : 100
If I variable value is less then 0 then condition is evaluated as true and T will be assigned with
0 but if I variable value is greater then 0 then condition is evaluated as false and 100 will be
assign to variable T. For example
Printf(%d, (I<0) ? 0:100);

Sizeof Operator :
The size of a compile time operator and when used with an operand, it returns the number of
bytes the operand occupies. The operand may be variable, a constant or a data type qualifies.
M = sizeof(sum);
N= sizeof(long int);
K= sizeof(253L);
The size of operator is normally used to determine the length of array and structures, when
their sizes are not known to the programmer. It is used to allocate memory space dynamically
to variable during execution of a program.

Bitwise operators :
Some applications require the manipulation of individual bits within a word of memory.
Assembly language or machine language is normally required for operations of this type.
However C contains several special operators that allow such bitwise operations to be carried
out easily and efficient. These bitwise operators can be divided into three general categories:
the ones complement operator, the logical bitwise operators, and the shift operators. c also
contains several operators that combine bitwise operations with ordinary assignment.

The Ones Complement operator :
The ones complement operator (~) is a unary operator that causes the bits of its operand to be
inverted (i.e. reversed) so that is become so a so become is. This operator always precedes its
operand. The operand must be an integer type quantity (including integer, long, short,
unsigned, or char).(Linearly the operand will be an unsigned octal or an unsigned hexadecimal
quantity, though this is not a firm requirement.
Suppose int a=16 with 2 byte=16 bit pattern
it will be 00000000 00010000
b=~a
the b will have 16 bit pattern like 11111111 11101111

13
Logical bit wise operators :
There are three logical bitwise operators : bitwise and ($), bitwise exclusive or(^) and bitwise
or(!). Each of these operators requires two integer type operands. The operations are carried
out independently on each pair of corresponding bits within the two operands will be. Thus the
least significant bits( i.e. the rightmost bits) within the two operands will be compared then the
least significant bits. And so on. Until these comparisons are :

B1 B2 B1&b2 B1^b2 B1 | b2
1 1 1 0 1
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
The associatively for each bitwise operator is left-to-right.

Shift operators :
The two bitwise shift operator is shift left (<<) and shift right(>>). Each operator requires two
operands. The first is an integer-type operand that represents the bit pattern to be shifted. The
second is an unsigned integer that indicates the number of displacements (i.e. whether the bits
in the first operand will be shifted by 1 bit position, 2 bit position, 3 bit positions and so on).
This value cannot exceed the number of bits associated with the word size of the first operand.
The left-shift operator causes the left by the bits in the first operand to be shifted to the left by
the number of position indicated by the second operand. The leftmost bit positions that become
vacant will be tilled with us.
A = 01101101 10110111
A<<6 = 0110 1100 0000 = 0x5dc0
All the bits originally assigned to a are shifted to the left six places, as the arrows indicate. The
leftmost 6 bits (originally 011011) are lost. The rightmost 6 bits positions are filled with 00
0000.
The right shift operator causes all the bits in the first operand to be shifted to the right
by the number of positions indicated by the second operand. The rightmost bits(i.e. the
underflow bits) in the original bit pattern will be lost. If the bit pattern being shifted represents
an unsigned integer, then the leftmost bit positions that become vacant will be filled with 0s.
Hence, the behavior of the right-shift. When the first operand is an unsigned integer.
A= 0110 1101 1011 0111
A>>6 = 000 0001 1011 0110 = 061bc
We see that all the bits originally assigned to a are shifted to the right six places, as the arrows
indicate. The rightmost 6 bits ( originally 11 011) are lost. The leftmost 6 bits positions are
filled with 00 0000.

Comma Operator :
The comma operators are use primarily in conjunction with the for statement. This operator
permits two different expressions to upper in situation where only one expression would
ordinarily be used. For example, it is possible to write
For(expression la, expression lb; expression2; expression3) Statement
Where expression la and lb are the two expression, separated by the comma operator, where
only one expression would normally appear. These two expression would typically initialize
two separate indices that would be used simultaneously within the for loop.
Similarly, a for statement might make use of the comma operator in the following manner.
For(expression 1a; expression2;expression3a, expression3b) statement;
14
Here expression 3a and expression 3b separated by the comma operator, appear in place of the
usual single expression. In this application the two separate expressions would typically be
used to alter the two different indices used simultaneously within the loop. For example, one
index might count forward while the order counts backward. In for loops.
For(n=1,m=10; n<=m; m++, n++)

Precedence and Associativity Table
Precedence is a priority of the operator for evaluation or execution when there are more then 1
operator in a single expression or statement. If there are operators of same precedence then the
expression will evaluated either from LEFT-TO-RIGHT or RIGHT-TO-LEFT. This is called
an associativity of an operator.

Description Operator Associativity Precedence
Function expression ( ) L TO R
Array expression [ ] L TO R
Structure operator -> L TO R
Structure operator . R TO L

1
Unary minus - R TO L
Increment/Decrement ++ -- R TO L
Ones complement R TO L
Negation ! R TO L
Address of & R TO L
Value of address * R TO L
Type cast (type) R TO L
Size in bytes Size of R TO L




2
Multiplication * L TO R
Division / L TO R
Modulus % L TO R

3
Addition + L TO R
Subtraction - L TO R
4
Left Shift << L TO R
Right Shift >> L TO R
5
Less than < L TO R
Less than equal to <= L TO R
Greater than > L TO R
Greater than or equal to >= L TO R


6
Equal to = = L TO R
Not equal to != L TO R
7
Bitwise AND & L TO R 8
Bitwise exclusive OR ^ L TO R 9
Bitwise inclusive OR | L TO R 10
Logical AND && L TO R 11
Logical OR || L TO R 12
Conditional ? : R TO L 13
Assignment


= *,= ,/=, %=
+=,-=,^=,|=,&=
<<=,>>=
R TO L 14
Comma , R TO L 15

15
DATA INPUT AND OUTPUT
As we know that any c program is made up of 1 or more then 1 function. Likewise it use some
functions for input output process. The most common function are printf() and scanf().

Printf() function :
Printf() function is use to display something on the console or to display the value of some
variable on the console The general syntax for printf() function is as follows
printf(<format string>,<list of variables>);

To print some message on the screen
Printf(God is great);
This will print message God is great on the screen or console.
More Examples:
printf(\nIndia is the best);
printf(\nVande Matram);
printf(\nJay Hind);
Output
India is the best
Vande Matram
Jay Hind

To print the value of some variable on the screen
Integer Variable :

int a=10;
printf(%d,a);
Here %d is format string to print some integer value and a is the integer variable whose value
will be printed by printf() function. This will print value of a 10 on the screen. You can make
this output interactive by writing them
Int a=10;
Printf(a=%d,a);
This will print a=10 on the screen

To print multiple variables value one can use printf() function in following way.
Int p=1000,r=10,n=5;
Printf(amount=%d rate=%d yeat=%d,p,r,n);
This will print amount=1000 rate=10 year=5 on the screen

Float Variable :
Float per=70.20;
printf(Percentage=%f,per);
Here %f is format string to print some float(real) value and per is the float variable whose
value will be printed by printf() function. This will print value of a Percentage=70.20 on the
screen.

Character Variable :
char ans=Y;
printf(Answer=%c,ans);
Here %c is format string to print single character value and ans is the character variable whose
value will be printed by printf() function. This will print value of a Answer=Y on the screen.



16
Suppose we want to print Amar on the screen with character variable
Char c1=A,c2=m,c3=a,c4=r ;
Printf(Name = %c %c %c %c,c1,c2,c3,c4);

This will print Name=A m a r on the screen.

You can use single printf() function to print different data type variables value also.
Example
Int rno=10;
Char res=P;
Float per=75.70;
Printf(Rollno=%d Result=%c Percentage=%f,rno,res,per);

This will print message Rollno=10 Result=P Percentage=75.70 on the screen.

Scanf() Function :
Scanf() function is use to read data from keyboard and to store that data in the variables.
The general syntax for scanf() function is as follows.

Scanf(Format String,&variable);

Here format string is used to define which type of data it is taking as input this format string
can be %c for character, %d for integer variable and %f for float variable. Where as variable
the name of memory location or name of the variable and & sign is an operator that tells the
compiler the address of the variable where we want to store the value. One can take multiple
input of variable with single scanf() function but it is recommended that there should be one
variable input with one scanf() function.

Scanf(Format string1,format string2,&variable1,&variable2);

For Integer Variable :
Int rollno;
Scanf(%d,&rollno);
Printf(Enter rollno=);
Here in scanf() function %d is a format string for integer variable and &rollno will give the
address of variable rollno to store the value at variable rollno location..

For Float Variable :
Float per;
Printf(Enter Percentage=);
Scanf(%f,&per);
Here in scanf() function %f is a format string for float variable and &per will give the address
of variable per to store the value at variable per location.


For Character Variable :
Char ans;
Printf(Enter answer=);
Scanf(%c,&ans);



Here in scanf() function %c is a format string for character variable and &ans will give the
address of variable ans to store the value at variable ans location.
17

Single character input the getchar function :
Single characters can be entered into the computer using the C library function getchar. The
getchar function is a part of the standard C language I/O library. It returns a single character
from a standard input device (typically a keyboard). The function does not required any
arguments through a pair of empty parentheses must follow the word getchar.
In general terms, a reference to the getchar function is written as.
Character variable=getchar();

Where character variable refers to some previously declared character variable.
A C program contains the following statements.
char c;
c=getchar();
The first statement declares that c is a character type variable. The second statement causes a
single character to be entered from the standard input device and then assigned to c.
If an end-of file condition is encountered when reading character with the getchar function, the
value of the symbolic constant EOF will automatically be returned. The detection of EOF in
this manner offers a convenient way to detect an end of file, whenever and wherever it may
occur. Appropriate corrective action can be taken. The getchar function can also be used to
read multicharacter strings, by reading one character at a time a multiples loop.

Single character output The putchar function:
Single character can be displayed (i.e. written out of the computer) using the C library function
putchar.The putchar function, like getchar is a part of the standard C language I/O library. It
transmits a single character to a standard output device. The character being transmitted will
normally be represented as a character-type variable. It must be expressed as an argument to
the function, enclosed in parentheses following the word putchar. In general a reference to the
putchar function is written as

Putchar (character variable)

Where character variable refers to some previously declared character variable.
A C program contains the following statements.:
char c=a;
putchar(c);

The first statement declares that c is character type variable. The second statement causes the
current value of c to be transmitted to the standard output device where it will be displayed.
The putchar function can be used to output a one-dimensional, character type array.
Each character can then be written separately within a loop.











18
DECISION CONTROL STRUCTURE :

The if-else statement:
The if-else statement is used to carry out a logical test and then take one of two possible
actions depending on the outcome of the test (i.e. whether the outcome is true or false).The else
position of the if-else statement is optional. Thus, in its simplest general form, the statement
can be written.

If(expression)
statement;

The expression must be placed in parenthesis, as shown. In this form, the statement will be
executed only if the expression has non-zero value (i.e. true). If the expression has a value of
zero (i.e. expression is false), then the statement will be ignored. The statement can be either
simple or compound. In practice, it is often compound statement, which may include other
control statements.

The general form of an if statement which include the else clause is

If(expression)
statement 1;
else
statement 2;


If the expression has a non-zero value (i.e. if expression is true), then statement 1 will be
executed. Otherwise, (i.e. expression is false), statement 2 will be executed. It is possible to
next ifelse statement within one-another, just as we did with loops, there are several different
forms that nested ifelse two-layer nesting is : In this situation, one can complete ifelse
statement will be executed if expression is nonzero(true) and another complete if else statement
will be executed if expression is false (zero). It is of course, possible that statement 1,
statement2, statement3 and statement4 will contain another ifelse statements. We would then
have multi layer nesting. Some other forms of two layer are :


If<exp1>
{
statement1;
}
else
{
if<exp2>
{
statement2;
}
}




19


if<exp1>
{
statement1;
}
else
{
if<exp2>
{
statement2;
}
else
{
statement3;
}
}
if<exp1>
{
if<exp2>
{
statement1;
}
else
{
statement2;
}
else
{
statement3;
}




if<expr1>
{
if<exp2>
{
statement1;
}
else
{
statement2;
}
}



















20
LOOP CONTROL STRUCTURE
If we want to perform certain action for no of times or we want to execute same statement or a
group of statement repeatedly then we can use different type of loop structure available in C.
Basically there are 3 types of loop structure available in C
(1) While loop
(2) Do..while
(3) For loop

While statement :
The while statement is used to carry out looping operations. The general form of the statements
Initialization;
While(exp)
{
statement 1;
statement 2;
increment/ decrement;
}


The enclose statements within two braces will be executed repeatedly as long as the expression
evaluated as true. When the expression is evaluate a false or when condition will be false then
it will come out from the loop and stop the execution of that loop. Initialization statement
initialize some memory variable with some value. Increment or decrement operator increase or
decrease the value of operator is use by expression. This statement can be simple of compound,
though it is typically a compound statement, it must include some features, which eventually
offers the value of expression, thus provides a stopping condition for the loop.

The practice, the included expression is usually a logical expression that is either true or false.
(remember that true corresponds to non-zero value and false corresponds to zero value). Thus
the statement will continue to execute as long as the logical expression is true.

The part of while statement, which contains the statement, is called the body of the loop. Body
of the loop may have one or more statements. The braces are needed only if the body contains
two or more statements. However, it is a good practice to use braces even if the body has only
one statement.
Suppose we want to display the consecutive digits 0,1,2,3,9 with one digit on the each line.
This can be accomplished with the following program.

#include<stdio.h>
main ()
{
int digit = 0;
while(digit<=9)
{
printf(%d \n,digit);
++digit ;
}
}
Initially, digit is assigned a value of 0. The while loop then displays the current value of digit,
increases its value by 1 and then repeats the cycle, until the value of the loop will be repeated
21
by 10 times, resulting in 10 consecutive lines of output. Each line will contain a successive
integer value, beginning with and ending with 9. Thus when the program to run, the following
output will be generated :
0 1 2 3 4 5 6 7 8 9
Do-While statement :

Sometimes, however, it is desirable to have a loop with the test for continuation at the end or
each pass. This can be accomplished by means of the do-while statement.
The general form of do-while statement is
Do
{
statement1;
statement2;
increment/decrement operator;
} while(expression);

The enclosed statement within 2 braces will be executed repeatedly as the value of expression
is not zero. Notice that statement will always be executed at least once. Since the test for
repetition does not occur until the end of the first pass through the loop. The statement can be
either simple or compound, though most applications will require it to be a compound
statement. It must include some feature which eventually alters the value of expression so that
the looping action can terminate. Since the expression is evaluated at the bottom of the loop,
the dowhile loop construct provides an exit controlled loop and therefore the body of the
loop is always executed at least once.

In practice, expression is usually a logical expression, which is either true(with a non zero
value) or a false(with a value of 0). The included statement will be repeated (i.e. another pass
will be made through the loop) if the logical expression is true.

For most applications it is more natural to test for continuation of a loop at the beginning rather
than at the end of the loop for this reason, the dowhile statement is use less frequently than
while statement. Suppose that we want to display consecutive 0,1,2,3,9 with one digit on
each line. This can be accomplished with the following program.



#include <stdio.h>
main()
{
int digit = 0;
do
{
printf(%d, digit++);
}while(digit<=9);
}



22
The digit is initially assigned a value of 0. The do while loop displays the current value of
digit. Increases it value by 1, and then tests to see if the current value of digit exceeds 0. If so
loop terminates; otherwise the loop continues, using the new value of digit. Note that the last
is carried out at the end of each pass through the loop. The net effect is that the loop repeated
10 times, resulting in 10 successive lines of output. Thus, when
the program is run the following output is generated :
0 1 2 3 4 5 6 7 8 9

FOR statement :
The for statement is another entry controller that provides a more concise loop control
structure. The general form of the for loop is :



For(initialization, test condition, increment)
{
statement 1;
statement 2;
}

The execution of the for statement is as follows :
1. Initialization of the control variables is done first, using assignments statement such as
I=0 and count=0. The variables I and count are known as loop controls.
2. The value of the control variables is tested using the test condition. The test condition is
relational expression, such as I>0 or I<10 that determines when the loop is terminated
and the execution continues with statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement
either evaluating the last statement is the loop. Now, the control variable is incremented
using and assignment statement such as I=I+1 and if the new value of the control is
satisfied under test condition, then the body of the loop is executed. This process
continues till the value of the control variable fails to satisfy the test-condition.
(a) Consider the following segment of a program :

For(x=0; x<9; x++)
{
printf(%d, x);
printf(\n);
}
This for loop is executed 10 times and prints the digits 0 to 9 in one line. The three sections
within parentheses must be separated by a semicolons. Note that there is no semicolon at eh
end of the increment section x++.

The for statement allows for negative increments. For example, the loop discussed above can
be written as follows:
For(x=9; x>=0; x--)
{
Printf(%d,x0
Printf(/n);
}
23
This loop is also executed 10 times. But the output would be from 9 to 0 instead of 0 to 9. Note
that, braces are optional when the body of the loop contains only one statement.

Additional features of for loop :
The for loop in C has several capabilities that are not found in the other loop constructs. For
example, more than one variable can be initialized at a time in the for statement.

For(n=1,m=50; n<m; n++, m--)
{
p=m/n;
printf(%d%d%d \n,n,m,p);
}
This is perfectly valid. The multiple arguments in the increment section are separated by
commas.

The third feature is that the test condition may have nay compound relation and the testing
need not be limited only to the loop control variable. Consider the example below :

Sum=0;
For(I=1;I<20 && sum<100; I++)
{
sum=sum+I;
printf((%d \n, sum);
}
The loop uses a compound test condition with the control variable; and external variable sum.
The loop is executed as long as both the conditions I<20 and sum<100 are true. The sum is
evaluated inside the loop.

It is also permissible to use expressions in the assignment statements of initialization and
increment sections, For example, a statement of the type :
For(z=(m+n)/2; x<0;x=x/2)
is perfectly valid.

Another unique aspect of the for loop is that one or more sections can be omitted, if necessary.
Consider the following statements :
M=0;
for(;m!=100;)
{
printf(%d \n, m);
m=m+5;
}

Both the initialization and increment sections are omitted in the for statement. The
initialization has been done before the for statement and the control variable is incremented
inside the loop. In such cases the sections are left blank. However, the semicolons separating
the sections must remain. If the test condition is not present, the for statement sets up an
24
infinite loop. Such loops can be broken using break or go-to statements in the loop. We can set
up time delay loop using the null statement as follow:

For(j=1000;j>0;j--) {}
The loop executed 1000 times without producing any output; it simply causes a time delay.
Notice that the body of the loop contains only a semicolon, known as null statement. This can
also be written as :

For(I=1000; I>0; I--);
This implies that C compiler will not give an error message. If we place a semicolon by
mistake at the end of a for statement. The semicolon will be considered as a null statement and
the program may produce some nonsense.

Loops can be nested (i.e. embedded) one within another. The inner and outer loops need not
be generated by the same type of control structure. It is essential that one loop be completely
embedded within the other. There can be no overlap. Also each loop must be controlled by a
different index.

BREAK STATEMENT:

The break statement is used to terminate loops or to exit a switch. The break statement will
break or terminate the inner-most loop. It can be used within a while, a do-while, a for or a
switch statement. The break statement is written simply as break; Without any embedded
expressions or statement. For example,
For(I=1; I<=10; I++)
{
if(I==5)
break;
printf(\nI=%d,I);
}

The output will be 1,2,3,4 and then break will terminate this loop and stop the execution of the
for loop.

CONTINUE STATEMENT
The continue statement is used to skip or to bypass some step or iteration of looping structure.
It does not terminate the loop but just skip or bypass the particular sequence of the loop
structure. It is simply written as continue;.

For(I=1; I<=10; I++)
{
if(I==5)
continue;
printf(\nI=%d,I);
}
The output of the above program will be 1,2,3,4,6,7,8,9,10. The 5
th
iteration of the loop will be
skipped as we have define the continue for that iteration. So it will not print the value 5.

25
SWITCH-CASE Statement :
The switch statement causes a particular group of statements to be chosen from several
available groups. The selection is based upon the current value of an expression that is
included within a switch statement. The general form of switch-case statement is :
Switch(expression)
{
Case expression1
Statement1;
Statement2;
Case expression2
Statement1;
Statement2;
Case expression3
Statement1;
Statement2;
}

Usually each of these expression will be written as either an integer constant or a character
constant. Each individual statement following the case labels may be either simple or complex.
Where expression1 1, expression 2,,expression m represent constant, integer valued
expression .When switch statement is executed the expression is evaluated and control is
transferred directly to the group of statements whose case labels value matches the value of the
expression. If none of the case-label values matches the value of the expression, then non of
the groups within the switch statement w8ll be selected in this case control is transferred
directly to the statement that follows the switch statement.
Example :
Switch (choice=getchar())
{
case r
case R
printf(RED);
break;
case w
case W
printf(WHITE);
break;
case b
case B
printf(BLUE);
break;
}

Thus RED will be displayed if choice represents either r or R, WHITE will be display choice
represents either w or W and BLUE will be displayed if choice represents either b or B.
Nothing will be displayed if any other character has been assigned to choice. Notice that each
group of statements has two case labels, to account for either upper or lower case. Also, note
that each of the first two group ends with the break statement. The break statement causes
26
control to be transferred out of the switch statement thus preventing more than one group of
statement from being executed.

One of the labeled groups of statements within the switch statement may be labeled default.
This group will be selected if none of the case labels matches the value of expression. The
default group may appear anywhere within the switch statement. It need not necessary be
placed at the end. If none the case labels matches the value of the expression and the default
group is present, then the statement will take no action.
Here is a variation of switch statement :
Switch(choice=toupper(getchar())
{
case R :
printf(RED);
break;
case B :
printf(BLUE);
break;
case W :
printf(WHITE);
break;
default :
printf(ERROR);
break;
}

The switch statement now contains a default group, which generates an error message if
none of the case labels matches the original expression. Each switch statement now contains a
default group, which generates an error message if none of the case labels matches the original
expressions.

Each of the first three groups of statements now has only one case labels. Multiple case labels
are not necessary in the example, since the library function toupper causes all incoming
characters to be converted to the upper case. Hence choice will always be assigned an upper
case character. In a special sense, the switch statement may be thought of as an alternative to
the use of nested if-else statements, though it can only replace those if else statements that tests
for equality. In such situations using the switch statement is generally much more convenient.

Notice that each group of statement ends with a break statement in order to transfer control out
of the switch statement. The break statement is required within each of the first three groups in
order to prevent the succeeding groups of statement from executing. This last group does not
require a break statement since control will automatically be transferred out of the switch
statement after the last group has been executed. This last break statement is included, however
has a matter of good programming practice. So that it will be present, if another group of
statement is added later.





27
THE GOTO STATEMENT :
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program. In its general for the goto statement is written as
goto label; Where label is an identifier used to label the target statement to which control will
be transferred.

Control may be transferred to any other statement within the program. The target statement
must be labeled and the label must be followed by a color. Thus the target statement will
appear as label : statement. Each labeled statement within the program must have unique label,
i.e. no two statement can have same label.

The common application of goto are :

1. Branching around statement or groups of statements under conditions.
2. Jumping to the end of a loop under certain conditions, thus by passing the reminder
of the loop during the loop during the current pass.
3. Jumping completely out of a loop under certain conditions, thus terminating the
execution of the loop.
Branching ground statement can be accomplished with the if-else statement, jumping to the
end of a loop can be carried out with the continue statement, and jumping out of a loop easily
completed using the break statement. The uses of these structured features are preferable to the
used of the goto statement because the use of goto tends to encourage logic that skips all over
the program.

Occasional situations do arise, however, in which the goto statement can be useful. Consider,
for example, a situation in which it is necessary to jump out of a doubly nested loop if a certain
conditions are detected. This can be accomplished with two if break statements. One within
each loop, though this is awaked. A batter solution in this particular situation might make user
of the goto statement to transfer out of both loops at once.






















28
ARRAY
Array is a collection or group of similar data type elements stored in contiguous memory. The
individual data items can be characters, integers, floating points numbers and so on . Here
contiguous memory allocation means array occupies contiguous bytes as needed in the
memory.

DEFINING AN ARRAY :
Arrays are defined in much the same manner as ordinary variables. Except that each array
name must be accompanied by a size specification number of elements for a one-dimensional
array. The size specified by positive integer expression enclosed in square brackets. The
expression is usually written as a positive integer constants. For example if we want to declare
an array of 10 integer values then we can define it as following. The general form is
Storage class data type array[expression] = {vlaue1, value2,valuen}

Single Dimension Array

Int a[10];
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
2
bytes
2
bytes
2
bytes
2
bytes
2
bytes
2
bytes
2
bytes
2
bytes
2
bytes
2
bytes
2001 2003 2005 2007 2009 2011 2013 2015 2017 2019

Each array elements is referred to by specifying the array name followed by one or more
subscripts. With each subscript enclosed in square brackets. Each subscript must be
expressed as a non-negative integer : thus in the n- element array x, the array elements
arr[0], arr[1], arr[2]arr[n-1]. The value of each subscript can be expressed as an integer
constant, an integer variable or a more complex integer expression.

The number of subscripts determines the dimensionality of the array. For example, x[I]
refers to an element in the one dimensional array x. Similarly y[I][j] refers to an element in
the two dimensional array..

MULTIDIMENTIONAL ARRAY

Multidimensional, array is defined in much the same manner as one-dimensional arrays, except
that a separate pair of square brackets is required for each subscript. Thus a two dimensional
array will require two pairs of square brackets, three dimensional array will require three pairs
of square brackets and so on.

In general terms, a multidimensional array definition can be written as
Storage_class data_type array[exp1][exp2][expn];

Where storage class refers to the storage class of the array, data type is its data type. Array is
the array name and exp1, exp2, expn are positive valued expressions that indicate the
number of array element associated with each subscript. The storage class is optional, the
default values are automatic for arrays that are defined inside of a function, and external for
arrays defined outside of a function.



29
For example,
Float table [50][50];
Char page[24][80];
Static double records[100][66][255];
Static double records[L][M][N];



Two Dimension Array
Int a[5][5];
0 1 2 3 4

A[0][0] A[0][1] A[0][2] A[0][3] A[0][4]
A[1][0] A[1][1] A[1][2] A[1][3] A[1][4]
A[2][0] A[2][1] A[2][2] A[2][3] A[2][4]
A[3][0] A[3][1] A[3][2] A[3][3] A[3][4]
A[4][0] A[4][1] A[4][2] A[4][3] A[4][4]

The first line defines table as a floating point array having 50 rows and 50 columns (hence 50 x
50 = 2500 elements) and the second line establishes page as a character array with 24 rows and
80 columns (24 x 80 =1920 elements), the third array can be thought of as a set of double
precision tables, each having 66 lines and 266 columns (hence 100 x 66 x 255 = 1,683,000
elements).

The last definition is similar to the preceding definition except that the symbolic constant
L,M,N defines the array size. Thus the values assigned to these symbolic constant will
determine the actual size of the array.

If a multidimensional array definition includes the assignment of initial values, then care must
be given to the order in which the initial values are assigned to the array elements(remember
only external and static arrays can be initialized). The rule is that the last (right most) subscript
increases most rapidly and the first(left most) subscript increases least rapidly. Thus the
elements of a two-dimensional array will be assigned by rows, that is the element of the first
row will be assigned, then the element of the second row and so on.

For example, consider following two-dimensional array definition :

Int values[3][4] = {1,2,3,4,5,6,7,8,9,10,11.13};


Note that values can be thought of a table having three rows and for columns (four element per
row.) Since the initial values are assigned by rows (i.e. last subscript including most rapidly,
the results this initial assignment are as follows:

Value[0][0] = 1 Value[0][1] = 2 Value[0][2] = 3
Value[0][3] = 4 Value[1][0] = 5 Value[1][1] = 6
Value[1][2] = 7 Value[1][3] = 8 Value[2][0] = 9
Value[2][1] = 10 Value[2][2] = 11 Value[2][3] = 12
30
Remembers that the first subscript ranges from 0 to 2 and the second ranges from 0 to 3.
This example can be written as :
Int values[4][3]
{
{1,2,3},
{4,5,6},
{7,8,9},
10,11,12}
};

The natural order in which the initial values are assigned can be altered by forming groups of
initial values enclosed in braces. The values within each innermost pair of braces will be
assigned to those array element whose last subscript changes most rapidly. In a two
dimensional array, for example, the value within the inner pair of braces will be assigned to the
element of row, since the second subscript increase most rapidly. If there array two few values
within a pair of braces, the remaining elements of that row will be assigned zeros. On the other
hand, the number of values within each pair of braces cannot be exceed the defined row size.

Multidimensional arrays are processed in the same manners as one-dimensional arrays, an
element-by-element basis. However, some care is required when passing multidimensional
arrays to a function. In particular, the formal argument declarations within a function definition
must include explicit size specifications in all of the subscript positions except the first. These
size specification must be consistent with the corresponding size specifications in the calling
program. The first subscript position may be written as an empty pair of square brackets as
with a one-dimensional array.

At individual array element that are not assigned explicit values will automatically to set to
zero. This includes the remaining elements of an array in which certain elements have been
assigned non zero values.

The array size need not be specified explicitly when initial values are included as a part of an
array definition, with a numerical array, the size will automatically be set equal to the number
of initial values included within the definition.

ARRAY AND STRINGS
The gets and puts functions:

The gets and puts functions facilitate the transfer of strings between the computer and the
standard input/output devices. Each of these functions accepts a single argument. The
argument must be a data item that represents a string(e.g. character array). The string may
include white space characters. In the case of gets, the string will enter from the keyboard and
will terminate with a new line character(i.e. the string will end when the user presses the
RETURN key).

The gets and puts functions offer simple alternatives to the use of scan f and printf for reading
and displaying strings, as illustrated in the following example. Here is a program that reads a
line of text into the computer and then writes it back out in its original form :


31

#include<stdio.h>
main()
{
char inne[80];
gets(line);
puts(line);
}

This program utilizes gets and puts to transfer the line of text into and out of the computer.
Most C compilers include library functions that allow strings to be compared. Copied or
concatenated. Other functions permit operations on individual character within strings. For
example, they allow individual characters to be found within strings and so on. The following
example illustrate the use of some of these library functions :

Strlen()
This function counts a number of characters present in a string while giving a call to the
function we are to pass the base address of the string. Total numbers of characters of the stings
are counted without counting null character, returning length of the string.
Static char msg[] = Lord krishna;
Int n;
N=strlen(msg);
Printf(length of string =%d, n);

Strcpy()
This function copies the contents of one string to another. The base address of source and
target strings are supplied to the function.

Static char source[] = Lord Krishna;
Static char target[15];
Strcpy(target, source);
Printf(Source string is : %s, source);
Printf(target string is :%s,target);
Strcat()
This function concatenates the source string at the end of target sting.

Static char s[] = Lord;
Static char t[] = Krishna;
Strcat(t,s);
Printf(source string is %s\n, s);
Printf(target stirng is %s\n, t);
This function compare two strings to find out whether they are same of different. The process
of character wise comparison continues till a mismatch is attained or end of string. If two
strings are identical, it returns a values zero, if they are not, it returns numeric difference
between ASCII values of non-matching characters.
32
Strcmp() :
This function compares two strings and returns some integer value. If both the strings are
equal then it returns 0 otherwise it returns some other integer value.

Main()
{
static char s1[]=Jerry;
static char s2[]=Ferry;
static char s3[]=jerry boy
int I,j,k;
I = strcmp(s1, jerry);
J= strcmp(s1, s2);
J=strcmp(s1, s3);
Printf(%d %d %d, I,j,k);
}

PROCESSING AN ARRAY :
Single operations involving entire arrays are not permitted in C. thus if a and b are similar
arrays, assignment operations. Comparison operations, and so on must be carried out on an
element-by-element basis. This is usually accomplished within a loop where each pass of loop
will therefore equal the number of array elements to be passed.
For example,
#include<stdoio.h>
#define EOL \n;
main()
{
char letters[80];
int tag, count=0;
while(letter[count] = getchar() != EOL)
count ++;
tag = count;
count=0;
while(count<tag)
{
putchar(toupper(letter[count]));
++count;
}
}









33
FUNCTION
DEFINING A FUNCTION :
A function has three principal components :
the first line,
the argument declarations
the body of the function
The first line of a function definition contains the byte specification of the value returned byte
the function, followed by the function name and (optionally) a set of parameters separated by
comas and enclosed in parenthesis. The type specification can be omitted if the function returns
an integer or a character, in entry pair of parenthesis must follow the function name if the
function definition does not include any arguments. In general terms, the first line can be
written as :

Data-type name(formal arg1, arg2, argn)

Where data type represents the data type of the value, which is returned, and name represents
the function name.

The formal argument allows information to be transferred from the calling portion of the
program to the function. They are also known as parameter on formal parameters.(the
corresponding arguments in the functions reference are called actual arguments since they
define the information actually being transferred. The identifiers used as formal argument are
local in the sense that they are not recognized outside of the function. Hence, the names of the
formal arguments may be same as the names of the other identifiers that appear outside the
function definition.

The argument declaration follows the first time. All format arguments must be declared at the
point in the function. Each format argument must have the same data type as its corresponding
actual arguments. That is each formal argument must be of the same data type as the data items
it receives from the calling portion of the program.

The remainder of the function definition is a compound statement that defines the action to be
taken by the function. This command statement is sometimes referred to as the body of the
function. It must follow the formal argument declarations. Like any other compound
statements, the statement can contain expression statements. Other compound statement,
control statements, and so on. As a result it can even access itself. This process is known as
recursion.

For example,
Low-to-up(Char el)
{
char c2
c2 = c1>=a && c1<=z) ? (A+cl-a) : cl;
return c2;
}



34
The first line contains the title, low-to-up followed by the formal argument cl, within is
enclosed n parameters. Note that g1 represents the lowercase character that is transferred to
function from the calling portion of the program.

Notice that this function returns a character content which actually an integer value. Therefore,
a type specification is not required in the first line. It would be permissible, however, to write
the first line as
Char low-to-up(c1)

The first formal argument c1 is declared to be a char type. The body of the function follows
this. Which begins on the third line. Notice that the body contains the declaration of the local
char-type variable c2. following the declaration of a statement that tests whether c1 represents
a lowercase letter. Finally, the program information is returned from the function to the calling
portion of the program via the return statement. The return statement also causes control to be
returned to the point from which the function was accessed.

In general terms, the return statement is written as return(expression);

The value of the expression is returned to the calling portion of the program. The expression is
optional. However, a return statement can be written without it. If the expression is omitted ,
the return statement simply causes control to never back to the calling porting of the program,
without any information transfer.

Now let us momentarily return to the function type specification, which appears in the first line
of the function definition. This type specification can be omitted if the function returns an
integer quantity or a character. If the function returns different type of quantity, such as a long
integer, floating point or double precision quantity, however, the first line of the function
definition must include a corresponding type specification.

Now suppose the data type specified in the first line is inconsistent with the expression that
appears in the return statement. Under such conditions the compiler will attempt to convert the
quantity to be represented by the expression that the data type specified in the first line. This
could result in a compilation error, as it might in value a partial loss of data.
ACCESSING A FUNCTION :

A function can be accessed (i.e. called) by specifying its name, followed by a list of arguments
enclosed in parentheses and separated by commas. If the function call does not require any
arguments, an empty pair of parenthesis must follow the functions name. The function call
may appear to itself (that is, it may comprise a simple expression), and it may be one of the
operands within a more complex expression.

The arguments appearing in the function call are referred to as actual arguments. In contrast, to
the formal arguments that appear in the first line of the function definition.(they are also known
simply as arguments or as actual parameters). In a normal function call there will be one actual
argument for each formal argument. The actual arguments may be expressed as constants,
single variables, or more complex expressions. However, actual argument must be of the same
type as its corresponding formal arguments.

There may are several different calls to the same function from various places within a
program. The actual argument may differ from one function call to another, within each
function call, however, the actual argument must correspond to the formal arguments in the
35
function definition.; i.e. the number of actual argument must be same as the number of formal
argument and each actual arguments must be of the same data as its corresponding for
argument.
If a function returns a non-integer quantity and the portion of the program containing the
function call precedes the function definition, then there must be a function declaration in the
calling position of the program. This is sometimes referred to as a forward declaration. The
function declaration effectively informs the compiler that a function will be accessed before it
is defined.
In its simplest form, a function declaration can be written as,

Data-type name();

Where data-type refers to the data type of the quantity returned by the function and name refers
to the function name.

Function calls can span several levels within a program; function A can call function B which
can call function C and so on. Also function a can call function c directly, and so on.

PASSING ARGUMENT TO A FUNCTIN :

When a single value is passed to a function via an actual argument. The value of actual
argument is copied to the function. Therefore, the value of the corresponding formal argument
can be altered within the function. But the value of the actual argument within the calling
routine will not change. This procedure for passing the value of an argument i/o a function is
known as passing by value.

Passing an argument by value has advantages and disadvantages on the plus. It allow a single-
value used actual argument to be written as an expression rather than, being restricted to a
single variable. Moreover, if the actual argument is expressed as a single variable. It prevents
information from being transferred back the calling portion of the program via arguments.
Thus, passing by value is restricted to a one-way transfer of information.
Array is passed differently than single-valued entities. If an array name is specified as an actual
argument the individual array elements are not copied to the function. Instead, the location of
the array (i.e. the location of the first element) is passed to the function. If an element of the
array is accessed within the function; the access will refer to the location of the array element
relative the location of the first element. Thus any alteration to an array element within the
function will carry over to the calling routine.

SPECIFYING ARGUMENT DATA TYPES ;

An additional reason for including a function declaration within the calling portion of a
program it is possible to include the data type of the arguments within the function declaration.
The compiler will then convert the value of each actual argument to the declared data type ( if
necessary ) and then compare each (converted) actual data type with the corresponding formal
function declarations will allow the programmers to be informal of data type, inconsistencies
detected during the compilation process.

When the argument data types are specified in a function declaration; the general form of the
function declaration can be written as :

Data-type name(argument type1, argument type2, argument typen);
36

Where data type represents the data type of the quantity returned by the function, name
represents the function name and argument type 1 argument type 2 argument type n refers
to argument data types of the first argument, second argument and so on. Remember that the
argument data type are optional even in the situations that requires a function declaration. Most
C compilers supports the use of the keyword void in function definition as a return data type
indicating that the function does not return anything. Function declaration may also include
void for the same purpose. In addition void may appear in an argument list, in both function
definition and function declarations, to indicate that a function does not require arguments. In
the later case, void appears by itself in the area normally used for argument specifications.

CATEGORY OF FUNCTION :

A function, depending and where argument are present or not and where a value is returned or
not, may belong to one of the following categories.

No arguments and not return values:

When a function has no arguments, it does not receive a data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data from
calling function. In fact, there is not data transfer between the calling function and the called
function.

We would ensure that the function call has matching arguments. In case, the actual arguments
are more than the formal arguments, extra actual arguments are discarded. On the hand, if the
actual arguments are less than the formal arguments, the unmatched formal arguments are
initialized to some garbage values. Any mismatch in data type may also result in passing of
garbage value. Remember no error message will be generated.

While the formal arguments must be void variable names; the actual arguments may be
variable name expression or constants. The variable used in actual arguments may be assigned
values before the function call is made.

Arguments with return values :

When function is called with arguments, then called function will receive the arguments. Then
the statement included within the body at the called function will be executed.

RECURSION :
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied. The process is used for repetitive computation in which each
action is stated on forms of previous result. The process is used for repetitive computation in
which each action in terms of a previous result. Many iterative problems can be written in this
form.

In order to solve a problem recursively, two condition must be satisfied. First, the problem
must be written in recursive form and second the problem example, we wish to calculate the
factorial of a positive integer quantity. We would normally express this problem as n1=1 x 2 x
3 x 4 x n where n is the specified positive integer. However, we can also express in another
way, by writing n=1 = n*(n-1). This is a recursive statement of the problem, in which last
expression provides a stopping condition for the recursion.
37
When a recursive program is executed the recursive function calls are not executed
immediately. Rather, they are placed on a stack until the condition that terminates the recursion
is encountered. The function calls are then executed in reverse order, as they are popped off the
stack.

If a recursive function contains local variables, a different set of local variables will be created
during each call. The name of the local variables, will be cause always be the same, as declared
within the function. However, the variables will represent a different set of values each time
the function is executed. Each set of values will be stored on the stack, so that they will be
available as the recursive process unwinds i.e. as the various function calls are popped off
the stack and executed.

THE SCPOE AND LIFETIME OF VARIABLES IN FUNCTION :

A variable in C can have any one of the four storage classes :

Automatic variables :
Automatic variables are declared inside a function in which they are to be utilized. They are
created when the function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are therefore private to the function in which
they are declared. Because of this property, automatic variables are also referred to as local or
internal variable.
A variable declared inside a function without storage class specifications, by default, an
automatic number in the example below is automatic.

One important feature of automatic variable is that their value cannot be changed accidentally.
This assures that we may declare and use the same variable name in different function in the
same program without causing any confusion to the compiler. There two consequences of the
scope and longevity of auto variables. First any variable local to main will normally live
throughout the whole program, although, it is active only in main. Secondly, during recursion,
the nested variables are unique auto variables, a situation similar to function, nested auto
variable with identical names.

Automatic, variable can also be defined within a set of braces known as blocks they are
meaningful only inside the block where they are defined.

External variables :
Variables that are both alive and active throughout the entire program are known as external
variables. They are also known as global variables. Unlike function in the program external
variables are declared outside a function. For example the external declaration of integer
number and float length might appear is :

Int number;
Float length = 7.5;
Main()
{
---
---
}


38
function1()
{
---
---
}
function2()
{
---
---
}

the variables number and length are available for use in all the three functions. In case a local
variable and a global variable have the same name, the local variable will have preceded over
the global variable in the function where it is declared.

Once a variable has been declared as global, any function can use it and change its value. Then
subsequent function can reference only that new value. Because of this property, we should try
to use global variables only for tables of for variables shard between functions when it is
inconvenient to pass them as parameters.

One other aspect of a global variable is that it is visible only form the point of declaration to
the end of the program.

Note that the extern declaration does not allocate storage space for variables. In case of arrays,
the definition should include their size as well.

An extern within a function provides the type information to just that one function. We can
provide type information to all function within a file by placing external declaration before any
of them, as shown below.


Extern float height []
Main ()
{
int t;
void printout();
---
---
printout();
}
void printout ()
{
int t;
---
---
}

float height(size);

39

MULTIFILE PROGRAMS :
Multiple source files can share a variable provided it is declared as an external variable
appropriately variable that are shared by two or more files are global variables and therefore
must declared them according in one file and then explicitly define them with extern in other
files. The extern specifies tells the compiler that the following variables types and names have
already been declared elsewhere and now need to create storage space for them. For example,

File 1.c
Main()
{
extern int m;
int l;
---
---
}
function1()
{
int j;
---
---
}

file 2.c
int m;
function2()
{
int il;
---
---
}
function3()
{
int count;
---
---
}
the extern, declaration in place where secondary reference are made, if we declare a variable as
global in two different files used by a single, program then the linker will have a conflict as to
which variable to use and therefore, is use a warning. When a function is defined in one file
and accessed in other, the later file must include a function declaration. The declaration
identifies the function we usually place such declarations at the beginning of the file, before all
function. Although all functions are assumed to be external, it would be good practice to
explicitly declare such functions with the storage class extern.





40
Static variables :
As the name suggest, the value of static exist until the end of the program. A variable can be
declared static using the keyword static like:

Static int x;
Static float y;
A static variable may be either an internal type or an external type depending on the piece of
declaration. Internal static variables are those which are declared inside a function. The scope
of internal static variable extend up to the end of the function in which they are defined.
Therefore, internal static variable are similar to auto variables, except that they remain in
existence throughout the remainder of the program. Therefore, internal static variables can be
used to retain values between function calls.

A static variable is initialized only once, when the program is compiled. It is never initialized
again. An external static variable is declared outside that program. The difference between a
static external variable and simple external variable is that the static external variable is
available only within the file where it is defined while the simple external variables can be
accessed by other files.

It is possible to control the scope of the function. For example, we would like a particular
function accessible only to the function in the file in which it is defined. And not to function in
other files. This can be accomplished by defining that function with the storage class static.

Register variable:
We can tell the compiler that a variable should be kept in one of the machines register instead
of keeping in the memory where normal variables are stored. Since a register access is much
faster than a memory access. Keeping frequently accessed variables in the register will lead to
faster execution of program. This is done as follows :
Register int count;

Since only a few variables can be placed in the register, it is important to carefully select the
variable for the purpose.

PASSING ARRAYS TO A FUNCTION:

An array name can be used as an argument to a function, thus permitting the entire array to be
passed to the function. The manner in which the array is passed differs mainly. However, from
that of an ordinary variable.

To pass an array to a function, the array mane must appear by itself without brackets or
subscripts as an actual argument within the function call. The corresponding format argument
is written in the same manner, though it must be declared as an array within the formal
argument declaration. When declaring array as a format argument, the array name is written
with a pair of empty square brackets. The size of the array is not specified within the format
argument declaration.

The following program outline illustrates the passing of an array from the main portion of the
program to the function :



41


Main()
{
int n;
float avg;
float list[100];
float average(int a, float x[]);
---
---
avg = average(n,list);
---
}
float average(n,x)
{
int a;
float x[];
---
---
}
within main we see a call to the function average. This function call contains two actual
argument the integer variable n and the one-dimensional floating-point array list. Notice that
list appears as an ordinary variable within the function call.

In the first line of the function definition we see two formal arguments, called a and x. the
formal argument declarations establish a as an integer variable and x as an one-dimensional
floating point array. Thus there is a correspondence between the actual argument list and the
formal argument x. note that the size of x is not specified within the formal argument.

If the first line of a function definition includes the formal argument declaration, each array
name appearing as a formal argument must be followed by an empty pair of square braces. We
can pass the elements of array to the function in two ways :

pass by value approach
pass by reference approach

PASSING BY BALUE APPROACH

When each element of array is passed one by one to the functions as an actual argument, at that
time element behaves as an ordinary variable. This manner of passing array value is called pass
by value approach.
In such cases, formal argument need not be an array. It may be any ordinary variable. That
element then be accessed throughout the function and then control returns to the calling
function, that alteration can not be recognized in the calling portion of the program because
passing element process will make a copy of original element to the formal argument.




42
PASS BY REFERENCE APPROACH

When an array is passed to a function, however the values of the array elements are not passed
to the function. Rather the array name is interpreted as address of the first array element (i.e.
the address of the memory location containing the first array element). This address is assigned
to the corresponding format argument when function is called. The formal argument therefore
becomes a pointer to the first array element. Argument passed in this manner are said to be
passed by reference.

When a reference is mad to an array element within the function, the value of the element
subscript is added to the value of the pointer to indicate the address of the specified array
element. Therefore any array element can be accessed from within the function, alteration will
be recognized in the calling portion of the program.

The return statement cannot be used to return an array. Therefore, if the elements of an array
are to be passed back to the calling portion of the program, the array must either be defined as
an external array whose scope includes both the function and the calling portion of the
program, or it must be passed to the function as a formal arguments.


LIBRARY FUNCTION:
Library functions are routines that carry out various commonly used operations or calculations.
They are contained within one or more library files that accompany each C compiler.
During the process of converting a C source program into an executable object program, the
compiled source program is linked with the library final program will be assembled from two
or more separate files, even though the original source program may have been contained
within a single file. The source program must therefore include declarations for the library
functions, just as it would for programmers defined functions that are defined in separate files.
C places the required library function declaration in special source files, called header files.
Most C compilers include several header files, each of which contains declarations that are
functionally related. For example, stdio.h is a header file containing declaration for i/o
routines; math.h contains declarations for certain mathematical function and so on. The header
files also contain other information related to the use of the library functions, such as symbolic
constant definitions.

The required header files must be merged with the source program during the compilation
process. This is accomplished by placing one or more #include statements at eh beginning of
the source program or at the beginning of the individual files.

Machine independence is a significant advantage in this approach to the use of library function
and header files. The machine independent features can be provided as library function, as
characters contain or as macros that are included within the header files. A typical C program
will therefore run on many different computers without alteration. Provided the appropriate
ability resulting from this approach is a major contributor to the popularity of C.







43

POINTERS

A pointer is a variable that represents the location of a data item, such as a variable or an array
element. Pointers have a number of useful applications. For example, pointer can be used to
pass information back and forth between a function and a reference point. In particular, other
provides a way to return multiple data items from a function via arguments. Pointer also
permits references to other functions to be specified as arguments to a given function. This has
the effect of passing function as arguments to the given functions. Pointers are also closely
associated with arrays and therefore provide an alternative way to access individual array
elements.

AND & OPERATORS
Suppose v is a variable that represents some particular data item. The address location can be
determined by the expression &v. where & is a unary operator called the address operator. That
evaluates the address of its operand.

Now let us assign the address of v to another variable pv. Thus pv = &v;
This new variable is called pointer to v. since it points to the location where v is stored in
address, not its value. Thus pv is referred to as a pointer variable. The relationship between pv
and v is illustrated in the following figure.



value of v address of v

The data item represented by v. (i.e. the data item stored in vs memory cells) can be
accessed by the expression *pv where * is a unary operator called the indication operator, that
operates only on a pointer variable. Therefore, *pv and v both represent the same data item.
(i.e. contents of same memory cell). Furthermore, if we write pv = &v and u=*pv then u and v
will both represent the same value. i.e. the value of v will indirectly be assigned to u. (it is
assumed that u and v are declared to have the same data type).

The unary operators & and * are members of the same precedence group as the other unary
operators. This group of operators has a higher precedence than the groups containing the
arithmetic operators. The associativity of the unary operators is right to left.

The address operator(&) must act upon operand associated with unique addresses. Such as
ordinary variables or single array elements. Thus the address operator cannot act upon
arithmetic expressions such as 2*(u+v).

The indirection operator(*) can only act upon operands that are pointers. However, if pv points
to v (i.e. pv=&v) then an expression such as *pv can be used interchangeably with its
corresponding variable v. thus an indirect reference can also appear on the left side and
assignment statement. This provides another method for assigning a value to an array element
of an ordinary variable (e.g. v) within a more complicated expression.

Pointer variables can point to numeric or character variables, arrays, functions or other pointer
variables. Thus a pointer variable can be assigned the address of an ordinary variable (i.e.
pv=&v). also a pointer can be assigned the value of another pointer variable (i.e. pv=px)
provided both pointer variables point to data items of the same type. More over, a pointer
variable can be assigned a null (zero ) value.
44

POINTER DECLARATIONS :
Pointer variables, like all other variables, must be declared before, they may be used in C
program. When a pointer variable is declared, the variable name must be preceded by an
asterisk(*). This identifies the fact that the variable is a pointer. The data type that appears in
the declaration refers to the object of the pointer. i.e. the data item that is stored in the address
represented by the pointer, rather than the pointer itself.

Thus a pointer declaration may be written in general terms as :

Data_type *ptvar;
Where ptvar is the name of the pointer variable and data type refers to the data type of the
pointer object. Remember that an asterisk must precede ptvar.

For example,
Float u,v;
Float *pv;
---
pv = &v;

The first line declares u and v to be floating point variables. The second line declares pv to be a
pointer whose object is a floating-point quantity. i.e. pv points to a floating point quantity. note
that pv represents an address not a floating-point quantity. An asterisk should not be included
in the assignment statement.

Within a variable declaration, a pointer variable can be initialized by assigning in the address
of another variable, remember that the variable whose address is assigned to the pointer
variable must have been declared earlier in the program, for example,

Float u,v;
Float *pv=&v;

PASSING POINTER TO A FUNCTION :
Pointers are often passed to a function as arguments. This allows data items within the calling
portion of the program to be accessed by the function altered within the function and then
returned to the calling portion of the program in altered form. We refer to this use of pointer as
passing of arguments by reference (or by address or by location).

When an argument is passed by value, the data item is copied to the function. Thus any
alteration made to the data item within the function is not carried over into the calling routine.
When an argument is passed by reference, however (i.e. when a pointer is passed to a function)
the address of a data item is passed to the function. The contents of that address can be
accessed freely, either within the function or within the calling routine. More over change that
is made to the data item(i.e. to the contents of the address) will be recognized in both the
function and the calling routine, thus the use of pointer as a function argument permits the
corresponding data item to be altered globally from within the function. When pointers are
used as argument to a function the formal arguments that are pointers must each be preceded
by an asterisk. Also, if a function declaration is included in the coding portion of the program.
The data type of each argument that corresponds to a pointer must be followed by an asterisk.
Both these points are illustrated in the following example :

45


#include <stdio.h>
main()
{
int n=1, v=3;
void fun2(int pu, int *pv) ;
printf( \n after calling func2 : u=%d v=%d , u,v) ;
}
void fun2(int *pu, int *pv)
{
*pu=0 ;
*pv=0 ;
printf(\n within fun2 pu=%d pv=%d, pu,*pv);
return;
}
here, fun2 receives two pointer to integer variables as its arguments. The arguments are
identified as pointers by the indirection operators (i.e. the asterisk) that appear in the argument
declaration, in addition declaration indicates that the pointers represents the integer quantities.

Within fun2, the contents of the pointer address are reassigned the values 0.0; since, the
address are recognized in both fun2 and main, the reassigned values will be recognized within
main after the call to fun2, therefore, the integer variables u and v will have accessed
indirectly, by referencing the pu and pv. This is necessary because the variable u and v are not
recognized such as within fun2.

The items in parentheses identify the arguments as pointers to integer quantities. The pointer
variable, pu and pv have not been declared elsewhere in main.In the declaration of the formal
argument within the first line of fun2, that is void func2(int *pv, int *pv) .The formal
arguments pu and pv are consistent with the dummy arguments in the function prototype. In
this example the corresponding variable names are the same though this is generally not
required.

An array name is actually a pointer to the array. i.e. the array name represents the address of
the first element in the array. therefore, an array name is treated as pointer when it is passed to
a function. However, it is not necessary to precede the array names with an ampersand within
the function call. An array name that appears as a formal argument within a function definition
can be declared either as a pointer or as an array of unspecified size.

It is possible to pass a portion of an array, rather than an entire array, to a function. To do so,
the address of the first array element to be passed must be specified with the argument. The
remainder of the array, starting with specified array element, will then be passed to the
function.

A function can also return a pointer to the calling portion of the program. The do so, the
function definition and any corresponding function declaration must indicate that the function
will return a pointer. this is accomplished by preceding the function name with an asterisk. The
asterisk must appear in both the function definition and the function declaration.

46

POINTER AND ONE DIMENTSIONAL ARRAY
If x is a one-dimensional array, then the address of the first array element can be expressed as
either &x[0] or simply x. moreover, the address of the second array element can be written as
either &x[1] or as (x+1). And so on. In general the address of I+1 th array element is
expressed as (x+I). Since x[1] and (x+1) both represent the address of 1 element of x. it would
seem reasonable that x[1] and *(x+1) both represent the contents of that address. i.e. the value
of the 1
st
element of x for example.

#include <stdio.h>
main()
{
static int x[5] = {10, 11, 12, 14};
int I;
for(I=0; I<5; I++)
printf(\n I=%d x[I]=%function *(x+I)=%d &x[I] = %d(x+I)
%d, x[I], *(x+I),&x[I],x+I);
}

executing this program results the following output :

I=0 x[I]=10 *(x+I)=10 &x[I]=72 x+I=72
I=1 x[I]=11 *(x+I)=11 &x[I]=74 x+I=74
I=2 x[I]=12 *(x+I)=12 &x[I]=76 x+I=76
I=3 x[I]=13 *(x+I)=13 &x[I]=78 x+I=78
I=4 x[I]=14 *(x+I)=14 &x[I]=7A x+I=7A

We can see that the value of the ith array element can be represented either x[I] or x[I+1] and
the address of the ith element can be represented by either &x[I] or x+i. When assigning a
value an array element such as x[I], the left side of the assignment statement may be written as
either x[I] or as *(x+I). Thus a value may be assigned directly to an array element or it may be
assigned to the memory area whose address is arbitrary address to an array name or to an array
element. Thus expression such as (x+1) and &x[I] cannot appear on the left side of an
assignment a\statement. For example. these four statement are all equivalent.

Line[2] = line[1];
Line[2] = *(line+1);
*(Line+2) = line[1];
*(Line+2) = *(line+1);

The address pf an array element cannot be assigned to some other array element. We cannot
write a statement such as.
&line[2] = &line[1];
we can assign the value of one array element to another through a pointer. if we wish, for
example,
pl = &line[I]
line[2]=*pi
pl = line+l;
*(line+2) = *pl;
47

numeric array element cannot be assigned initial values if the array is defined as a pointer
variable. Therefore a conventional array definition is required if initial values will be assigned
to the element of a numerical array. however, a character type pointer variable can be assigned
an entire string as a part of the variable declaration. Thus a string can conveniently be
represented by either a non-dimensional array or a character pointer.

OPERATIONS ON POINTERS
In particular an integer value can be added to or subtracted from a pointer variable though the
resulting expression must be interpreted very carefully. Suppose for example that, px is the
pointer variable representing the address of the same variable x, we can write expressions such
as ++px, --px, (px+3), (px-1), where I is an integer variable. Such expression will represent an
address located some distance of the integer quantity and the number of bytes or words
associated with the data item to which px points. Suppose for example, that px points to an
integer quantity, and each integer quantity requires 2 bytes of memory. Then the expression
(px+3) will result in an address 6 bytes beyond the integer to which px points as illustrated
following ;

Px-> 2 bytes v (px+3)

One pointer variable can be subtracted from another provided both pointer point to element of
the same array. the resulting value indicates the number of words or bytes separating the
corresponding array elements.
Pointer variable can be compared provided both variable point to object of the same data
type. Such comparisons can test for either quality or inequality.
Moreover, a pointer variable can be computed with 0.

The permissible operations on pointers are summarized below :
1. a pointer variable can be assigned the address of an ordinary variable (e.g. pv=&v)
2. a pointer variable can be assigned the value of another pointer variable (e.g. pv=px)
provided both pointers points to the object of the same data type.
3. a pointer variable can be assigned a null(zero) value (e.g. pv=null)
4. an integer quantity can be added to or subtracted from a pointer variable (e.g. pv+3,
++pv, pv-1)
5. one pointer variable can be subtracted from another provided both pointer points to the
element of the same array.
6. the pointer variables can be compared provided both pointers point to the object of the
same type.

Other arithmetic operations on pointers are not allowed. Thus a pointer variable cannot be
multiplied by a constant. Two pointer variables cannot be added and so on.

POINTERS AND MULTIDIMENSIONAL ARRAYS :
A two dimensional array, for example is actually a collection of one-dimensional arrays
. therefore, we can define a two dimensional array as a pointer to a group of contiguous one-
dimensional arrays. A two-dimensional array declaration can be written

Data-type (*ptvar) expression 2;

This concept can be generalized to higher dimensional arrays that is
Data-type (*ptvar) [expression 2][expression 3] [expression n];
48

In these declarations data type refers to the data type of the array. ptvar is the name of the
pointer variable. Array is the corresponding array name an expression 1, expression 2,
expression n are positive valued integer expression that indicate the maximum number of
array element associated with each subscript.

The parentheses that surround the array name should normally be evaluated right to left.
Suppose that x is a two-dimensional integer array having 10 rows and 20 columns. We can
declare x as a

Int(*x)[20];

In this declaration, x is defined to be a pointer to a group of contiguous, one-dimensional 20
element integer arrays. Thus x points to the first 20-element array, which is actually the first
row (row 0) of the original two-dimensional array. Similarly, (x+1) points to the second 20
elements array. which is the second row(row 1) of the original two-dimensional array and so
on.

An individual array element within a multidimensional array can also be accessed by
repeatedly using the indirection operator. Usually, however this procedure is more awkward
then the conventional method for accessing an array element. The following example illustrates
the use of the indirection operator.

Suppose that x is a two dimensional integer array having 10 rows and 20 columns, as declared
as

Int(*x) [20];

The item in row2, column 5 can be accessed by working either.

X[2][5] or *(*(x+2)+5)

Here, (x+2) is a pointer to row 2, therefore, the object of this pointer *(x+2), refers to the entire
row since row2 is a one-dimensional array. *(x+2) is actually a pointer to the first element in
row 2. we now add 5 to the pointer. hence, (*(x+2)+5) is a pointer to element 5 in row 2. the
object of this pointer, refers to the item in column 5 or row 2 which is x[2][5].

ARRAY OF POINTERS:
A multidimensional array can be expressed in terms of an array of pointers rather than as a
pointer to a group of contiguous arrays. In such situations the newly defined array will have
one less dimension that the original multidimensional array. such pointer will indicated the
beginning of separate (n-1) dimensional array.

In general terms a two-dimensional array can be defined as one-dimensional array of pointes
by writing

Data-type *array(expression 1);

Similarly an n-dimensional array can be defined as (n-1) dimensional array of pointer by
writing,
Data-type *array[expression 1][expression 2][expression n];
49

In these declaration data type refers to the data type of the original n-dimensional array. array
is the array name and expression 1, expression 2, expression n are positive valued integer
expressions that indicate the maximum number of element associated with each subscript.

A right-to-left rule first associates the pairs of square brackets with array, defining the named
object as an array. the preceding asterisk then establishes that the array will contain pointers.

The last (the right most) expression is when defining an array of pointers. Where as the first
(the left most) expression is omitted when defining a pointer to a group of arrays. When an n-
dimensional array expressed in this manner an individual array element within the n-
dimensional array can be accessed by a single use of the indirection operator for example,
We can define x as a one dimensional array of pointers by writing

Int *x[10];

Hence, x[0] points to the beginning of the first row, x[1] points to the beginning of the second
row and so on. Note that the number of element within each row is not explicitly specified.

An individual array element, such as x[2][5] can be accessed by writing,

*(x[2]+5)
In this expression, x[2] is a pointer to the first element in row 2 so that x[2] +5 points to
element 5 within row 2. the object of this pointer, *(x[2] +5) therefore refers to x[2][5]. Now
consider a three-dimensional floating-point array t. suppose the dimension of t is 10 x 20 x 30.
this array can be expressed as a two-dimensional array of pointers by writing

Float *t[10][20];

Therefore we have 200 pointers, each pointing to a one-dimensional array. an individual array
element, such as t[2][3][5] can be accessed by writing
*(t[2][3]+5)

In this expression, t[2][3] is a pointer to the first element in the one-dimensional array
represented by t[2][3]. Hence (t[2][3]+5) points to element 5 within this array. the object of this
pointer *(t[2][3]+5) therefore represents t[2][3][5].

Pointer arrays offer a particularly convenient method for storing strings. In this situation, each
array element is a character type pointer that indicated the beginning of separate string. Thus
an n-element array can be point to n different strings. Each individual string can be accessed by
referring to its corresponding pointer.

For example, char name[10][12]; here name contains 10 rows to accommodate the 10 strings.
Each row must be large enough to store at least 12 characters. A better way to do this is to
define a 10 element of pointer, that is,

Char *name[10];

Thus, name[0] will indicate the first name. Name[1] will indicate the second name and so on.
Just as individual strings can be accessed by referring to the corresponding pointers. (i.e.
corresponding array element). So can individual string element be accessed through the use of
50
the indirection operator. For example, *(*(name+2)+3) refers to the forth character in the third
string of the array name.

If the element of the array is sting pointers, a set of initial values can be specified as a part of
the array declaration. In such cases the initial values will be strings, where each string
corresponds to a separate array element. Remember however that an array must be declared
static if it is initialize within a function. For example
Static char *name[5] = {
pacific,
Atlantic,
Indian,
Caribbean,
Bering
};

in this example, name is a 5-element array of pointers. The first array element (i.e. the first
pointer ) will point to Pacific, the second element will points to Atlantic, and so on.


PASSING POINTER TO FUNCTIONS :
Pointer parameters are commonly employed in string functions. Consider the function copy
which copies one sting to another.

Copy(s1,s2);
Char *s1, *s2;























51
Structures
Simple Structures
A structure is a collection of one or more variables types grouped under a single name for easy
manipulation. The variables in a structure, unlike those in an array, can be of different variable
types. A structure can contain any of C's data types, including arrays and other structures. Each
variable within a structure is called a member of the structure.

The struct Keyword

Defining and Declaring Structures

The struct keyword is used to declare structures. A structure is a collection of one or more
variables (structure_members) that have been grouped under a single name for easy man-
ipulation. The variables don't have to be of the same variable type, nor do they have to be
simple variables. Structures also can hold arrays, pointers, and other structures.The keyword
struct identifies the beginning of a structure definition. It's followed by a tag that is the name
given to the structure. Following the tag are the structure members, enclosed in braces. An
instance, the actual declaration of a structure, can also be defined. If you define the structure
without the instance, it's just a template that can be used later in a program to declare
structures. Here s1 is student kind of variable which has 3 members no,name and per.

NO NAME Per
2 Bytes 5 Bytes 4 Bytes
Struct student
{
int no;
char nm[5];
float per;
};
struct student S1;
struct tag
{
structure_member(s);
/* additional statements may go here */
} instance;


2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011

Struct student
{
int no;
char nm[5];
float per;
}S1,S2;

52
These statements define the structure type student and declare two structure variable S1 and
S2 of type studnet. S1 and S2 are each instances of type student Each structure variable
contains 3 members no, name and per.

Accessing Structure Members
Individual structure members can be used like other variables of the same type. Structure
members are accessed using the structure member operator (.), also called the dot operator,
between the structure name and the member name. Thus variable s1 can be access in following
way
S1.no=10;
S1.name=AMAR;
S1.per=80;

To display the screen locations stored in the structure variable s1, you could write

printf("%d,%s,%f", s1.no, s1.name,s1.per);

At this point, you might be wondering what the advantage is of using structures rather than
individual variables. One major advantage is that you can copy information between structures
of the same type with a simple equation statement. Continuing with the preceding example, the
statement

S2 = S1;
is equivalent to this statement:
S2.no=S1.no=;
S2.name=S1.name;
S2.per=S1.per;

When your program uses complex structures with many members, this notation can be a great
time-saver. Other advantages of structures will become apparent as you learn some advanced
techniques. In general, you'll find structures to be useful whenever information of different
variable types needs to be treated as a group. For example, in a mailing list database, each
entry could be a structure, and each piece of information (name, address, city, and so on) could
be a structure member.

Example 1
/* Declare a structure template called SSN */
struct SSN
{
int first_three;
char dash1;
int second_two;
char dash2;
int last_four;
}


/* Use the structure template */
struct SSN customer_ssn;
53
Example 2
/* Declare a structure and instance together */
struct date
{
char month[2];
char day[2];
char year[4];
} cur_date;

Example 3
/* Declare and initialize a structure */
struct time
{
int hours;
int minutes;
int seconds;
} time_of_birth = { 8, 45, 0 };

Arrays of Structures
If you can have structures that contain arrays, can you also have arrays of structures? You bet
you can! In fact, arrays of structures are very powerful programming tools. Here's how it's
done. You've seen how a structure definition can be tailored to fit the data your program needs
to work with. Usually a program needs to work with more than one instance of the data. For
example, in a program to maintain a list of phone numbers, you can define a structure to hold
each person's name and number:
struct entry
{
char fname[10];
char lname[12];
char phone[8];
};

A phone list must hold many entries, however, so a single instance of the entry structure isn't
of much use. What you need is an array of structures of type entry. After the structure has been
defined, you can declare an array as follows:

struct entry list[1000];
This statement declares an array named list that contains 1,000 elements. Each element is a
structure of type entry and is identified by subscript like other array element types. Each of
these structures has three elements, each of which is an array of type char. This entire complex
creation is diagrammed in When you have declared the array of structures, you can manipulate
the data in many ways. For example, to assign the data in one array element to another array
element, you would write

list[1] = list[5];
54
This statement assigns to each member of the structure list[1] the values contained in the
corresponding members of list[5]. You can also move data between individual structure
members. The statement

strcpy(list[1].phone, list[5].phone);
copies the string in list[5].phone to list[1].phone. If you want to, you can also move data
between individual elements of the structure member arrays:

list[5].phone[1] = list[2].phone[3];
This statement moves the second character of list[5]'s phone number to the fourth position in
list[2]'s phone number. (Don't forget that subscripts start at offset 0.)
Listing 11.3 demonstrates the use of arrays of structures. Moreover, it demonstrates arrays of
structures that contain arrays as members.
Example
#include <stdio.h>
/* Define a structure to hold entries. */
struct entry
{
char fname[20];
char lname[20];
char phone[10];
};
/* Declare an array of structures. */
struct entry list[4];
int i;
main()
{
/* Loop to input data for four people. */
for (i = 0; i < 4; i++)
{
printf("\nEnter first name: ");
scanf("%s", list[i].fname);
printf("Enter last name: ");
scanf("%s", list[i].lname);
printf("Enter phone in 123-4567 format: ");
scanf("%s", list[i].phone);
}
/* Print two blank lines. */
printf("\n\n");
/* Loop to display data. */
for (i = 0; i < 4; i++)
{
printf("Name: %s %s", list[i].fname, list[i].lname);
printf("\t\tPhone: %s\n", list[i].phone);
}
return 0;
}


55
Pointer To Structure
We can also address or point the structure variable with structure pointer itself. Also we can
access the members of structure variable with the pointer variable
# include<stdio.h>
Void main()
{
struct emp
{
int empno;
char nm[20];
float sal;
};

struct emp e1={10,RAJ,10000};
Struct emp *p;
P=&e1;
Printf(%d %s %f,e1.empno,e1.nm,e1.sal);
Printf(%d %s %f,p empno,p nm,psal);
}

The operator is used to refer to the structure elements with pointer.

Passing Structures as Arguments to Functions
Like other data types, a structure can be passed as an argument to a function. Listing 11.5
shows how to do this. This program is a modification of the program shown in Listing 11.2. It
uses a function to display data on the screen, whereas Listing 11.2 uses statements that are part
of main().

Example
#include <stdio.h>
/* Declare and define a structure to hold the data. */
struct data
{
float amount;
char fname[30];
char lname[30];
} rec;
void print_rec(struct data x)
{
printf("\nDonor %s %s gave $%.2f.\n", x.fname, x.lname,x.amount);
}


/* The function prototype. The function has no return value, */
/* and it takes a structure of type data as its one argument. */


56

main()
{
/* Input the data from the keyboard. */
printf("Enter the donor's first and last
names,\n");
printf("separated by a space: ");
scanf("%s %s", rec.fname, rec.lname);
printf("\nEnter the donation amount: ");
scanf("%f", &rec.amount);
/* Call the display function. */
print_rec( rec );
return 0;
}

































57

FILE MANAGEMENT
A file is a place on the disk where a group of related date is stored. Some basic file operation
can be given as :
naming a file
opening a file
reading data from a file
writing data to a file
closing a file

Opening and closing a data file :
When working with a file steps it to establish a buffer area, where information is temporarily
stored while being transferred between the computers memory and the data file. This buffer
area allows information to be read from or written to the data file more rapidly then would
otherwise be possible. The buffer area is established by writing

FILE *ptvar;

Where FILE (uppercase required) is a special structure type that establishes the buffer area and
ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type file
is defined with a system include file : typically stdio.h

A data file must be opened or created before it can be created or processed. Thus associates the
file name with the buffer area. It also specifies how the data file will be utilized. That is a read
only file, a write-only file or a read/write file, in which both operations are permitted. The
library function fopen is used to open a file. This function is typically written as :

Ptvar = fopen(file_name, 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. The name chosen for the file_name
must be consistent within the rules for naming files, as determined by the computers operating
system. The file_type must be one of the strings shown in the following table :

File_type meaning
r open an existing file for reading only.
w open a new file for writing only. If the file with specified
file_name currently exists it will be destroyed and new
file is created in its place.
a open an existing file for appending. A new file will be
created if the file with the specific file_name does not
exist.
r+ open an existing file for both reading and writing.
w+ open a new file for both reading and writing. If a file with
the specified file_name currently exists, it will be
destroyed and a new file is created in its place.
a+ open an existing file for reading and writing. A new file
will be created if the file with the specified file_name
does not exist.

58
The fopen function returns a pointer to the beginning of the buffer area associated
with the file. A NULL value is returned if the file cannot be opened as for
example, when and existing file cannot be found. Finally a data file must be
closed at eh end of the program. This ensures that all outstanding information
associated with the file is flushed out from the buffers and all links to the file are
broken. It also prevents any accidental misuse of the file. In case there is a limit to
the number of files that can be kept open simultaneously, closing of unwanted file
might help open the required files. Another instance, where we have to close a file
is when we want to reopen the same file in a different mode. This can be
accomplished with the library function fclose. The syntax is simply :

fclose(fptvar);

Example
#include <stdio.h>
main()
{
FILE *fpt;
Fpt=fopen(simple.dat,w);
fclose(fpt);
}



Input-output operation on file :

THE GETC AND PUTC FUNCTIONS :

The simplest file i/o functions are fgetc and fputc. These are used to handle one character at a
time. Assume that a file is opened with mode w and file point fpt. Then, the statement
fputc(c,fpt);
Writes the character contained in the character variable c to the file associated with FILE
pointer fpt. Similarly getc is used to read character from a file that has been opened in read
mode. For example, the statement
C = fgetc(fp2);
Would read character from file whose file pointer is fp2. the file pointer moves by one
character position for every operation of getc and putc. The getc will have been reached.
Therefore, the reading should be terminated when EOF is encountered.

For example,









59

Main()
{
FILE *fp;
Char c;
Fp = fopen(input, w);
While(c=getchar()) != EOF)
{
fputc(c,fp);
}
fclose(fp);
f1 = fopen(input,r);
while(c=fgetc(f1)) != EOF)
{
printf(%c,c);
}
fclose(f1);
}

THE FGETS AND FPUTS FUNCTIONS :
These functions are used to handle a string at a time. Assume that a file is open in the write
mode and file pointer is fp1, then the statement
Fputs(s,fp1);
Writes the string contained in the character arrays to the file associated with FILE pointer fp1.
similarly, fgets is used to read a string of particular length from a file that has been opened in
read mode. For example,
Fgets(s,79,fp1);
Would read string of 79 character from the file whose file pointer is fp1. The fgets will return
NULL character when reached at the end of file. Therefore the reading should be terminated
when NULL is encountered. For example,
#include<stdio.h>
main()
{
FILE *fp;
Char c[80];
Fp = fopen(INPUT, w);
While(strlen(getc(c)>0)
{
fputs(c,fp);
fputc(\n, c);
}
fclose(fp) ;
fp = fopen( INPUT , r ) ;
while(gets(c,79, fp) = NULL)
printf(%s \n,c);
fclose(fp);
}

60
THE FSCANF AND FPRINTF FUNCTIONS :

These functions are used to read or write in formatted from from/to the files. The general form
of fprintf is
Fprintf(f1, %s%d%function, name, age, 7.5);

Here f1 is the file pointer name is an array variable of type character, age is integer variable.
The general form of fcanf is :
Fscanf(fp, control string, list);

This statement would cause the reading of the items in the list from the file specified by fp,
according to the specifications contained in the control string. For example,

Fcanf(f2, %s %d %f, item, qty,price);
Fcanf returns the number of items that are successfully read. When the end of the file is
reached, it returns the value of EOF.

THE FREAD AND FWRITE FUNCTIONS :
Some applications involve the use of data files to store blocks of data, where each block
consists of a fixed number of contiguous bytes. Each block will generally represent a complete
data structure, such as a structure or an array. for such applications it may be desirable to read
the entire block from the data file or write the entire block to the file.

The library function fread and fwrite are intended to be used in situations of this size of the
data block, the number of data block being transferred and file pointer. thus typical fwrite and
fread functions :
Fwrite(&customer, sizeof(record),1,fpt);
Fread(&customer, sizeof(record),1,fpt)
Where customer is a structure variable of type record and fpt is the file pointer associated with
the data file that has been opened for input/output. Once an unformatted data file has been
created with fwrite, it can be read with fread function. The function returns a zero value if an
end-of-file condition has been detected and non-zero value if an end-of-file is not detected.
Hence, a program that reads an unformatted data file can be reading file, as long as the value
returned by fread is non-zero value.

RANDOM ACCESS TO FILES :
There are occasions however, when we are interested in accessing only a particular part of a
file and not in reading the other parts. This can be achieved with the help of the function fseek,
ftell and rewind available in the library.

ftell :
ftell take a file pointer and returns a number of type long that corresponds to the current
portion. This function is useful in saving the current position of a file, which can be used in the
program. It takes the following form.
N =ftell(fp);
N would give the relative offset (n bytes) of the current position. This means that n bytes have
already bean read.




61
rewind :
rewind takes a file pointer and resets the position to the start of the file. For example the
statement :
Rewind(fp);
N=ftell(fp);
Would assign to fp because the file position has been set to the start of the file by rewind. This
function helps us in reading a file more than once. Without having to close and open the file.

fseek :
fseek function is used to move the position to a desired location within the file. It takes the
following form.

Fseek(fpt, offset, position)
Fpt is a pointer to file concerned. Offset is a number of variable of type long and position is an
integer number. The offset specifies the number of bytes(position) to be moved from the
location specified by position. The position can take one of the following three values :

0 beginning of file
1 current position
2 end of file
The offset may be positive, meaning move forward and negative, meaning move backwards.
When the operation is successful, fseek returns a zero. If we attempt to move beyond the file
boundaries and error occurs and fseek returns.




























62
DYNAMIC MEMORY ALLOCATION
The process of allocating memory at run time is known as dynamic memory allocation.
malloc() and calloc() are library routines known as Memory Management Functions that can
be used for allocating and freeing memory during program execution.

Malloc()
A block of memory may be allocated using the function malloc(). The function reserves a
block of memory of 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 form.
Ptr = (cast_type *) malloc(byte_size)
Ptr is a pointer of type cast_type. The malloc returns a pointer of cast_type to an area of
memory of size byte_size. For example,
X = (int *) malloc(100*sizeof(int));
On successful execution of this statement a memory space equivalent to 100 times for the size
of int bytes is reserved and the address of the first byte of the memory allocated is assigned to
the pointer x of type int. Similarly statement
Cptr = (char *) malloc(10);
Allocates 10 byte of space for the cptr of type char. We may also use malloc to allocate space
for complex data types such as structures. For example,
Stptr = (struct store*)malloc(sizeof(struct store));
Where stptr is pointer of type struct store. The malloc allocates a block of contiguous bytes.
The allocation can fall if the space in the heap is not sufficient to satisfy the request. If it fails it
returns a NULL.

Calloc()
Calloc is memory allocation function that is normally used for requesting memory space at
runtime for storing derived data types such as arrays and structures. Calloc allocates multiple
block of storage, each of the same size and then sets all bytes to zero. The general form of
calloc is ;
Ptr = (cast_type *) calloc(n,elem_size);
The above statement allocates contiguous space of n blocks. Each of size elem_size. All bytes
are initialized to zero and a pointer to the first byte of allocated region is returned. If there is
not enough space, a NULL pointer is returned. The following segment of program allocates
space to a structure variable.


struct student
{
char name[25];
float age;
long int id_num;
};
type of struct student record;
record *stptr;
int class size=30;
stptr = (record *) calloc(class_size, sizeof(record));
record is of type struct student, having three members name, age and id_num. The calloc
allocates memory to hold data for 30 such records.
63
PROGRAM LIST
(1) Write a program that perform the addition, subtraction, division and
multiplication of 2 values.
(2) Write a program to count the simple interest.
(3) Write a program that find maximum of 2 values.
(4) Write a program that interchange or swap the values of 2 variables.
(5) Write a program that find minimum and maximum out of 3 values.
(6) Write a program to interchange the value of 2 variable without using 3
rd

variable
(7) Write a program that take input of 5 subjects marks. Count the
percentage. Print the result for following condition
If student has 70% or more then 70% then DISTINCTION.
If student has percentage between 60 and 69 then FIRST CLASS.
If student has percentage between 50 and 59 then SECOND CLASS.
If student has percentage between 40 and 49 then PASS CLASS.
If student has percentage less then 40 then FAIL.

(8)Write a program that take input of 5 subjects marks. If student get 40 or
more then 40 then he is PASS in that subject otherwise FAIL print the result
for following condition.
If student is pass in all subjects then declare PASS.
Is student is fail in 1 or 2 subject then declare ATKT.
If student is fail in more then 2 subject then declare FAIL.

(9) Write a program that perform the following output for n rows
1
1 2
1 2 3
1 2 3 4

(10) Write a program that perform the following output for n rows
1
2 2
3 3 3
4 4 4 4

(11) Write a program that perform the following output for n rows
1 2 3 4 5 4 3 2 1
1 2 3 4 4 3 2 1
1 2 3 3 2 1
1 2 2 1
1 1
(12) Write a program that perform the following output for n by n matrix
without using array
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25

64
(13) Write a program that perform the following output for n rows
1
3
5 6
8 9 10

(14) Write a program that perform the following output for n rows
*
*
* *
* * *
(15) Write a program that perform the following output for n rows
1
1 2
1 2 3
1 2 3 4
(16) Write a program to perform the following output for n rows
1
0 1
1 0 1
0 1 0 1
(17) Write a program to perform the following output for n rows
1 *
2 * * *
3 * * * * *
4 * * * * * * *
(18) Generate the value of n! factorial for n number
(19) 1+2+3+4+5+6 up to n terms
(20) 1+3+5+7+9 up to n terms
(21) 1+2+4+5+7+8 up to n terms
(22) X+ X
2
+ X
3
+ X
4 +
X
5
up to n terms
(23) X/Y + X
2
/Y
2
+ X
3
/Y
3
up to n terms
(24) X/Y + X
2
/Y

+ X
2
/Y
2
+

X
3
/Y
2
+ X
3
/Y
3
up to n terms
(25) A+AR+AR
2
+AR
3
+AR
4
up to n terms
(26) 1! + 2! + 3! + 4! + 5! Up to n terms
(27) 1! + 3! + 5! + 7! Up to n terms
(28) X + X
3
+ X
5
+ X
7
up to n terms
(29) X/1 + X
2
/2
2
+ X
3
/3
3
+ X
4
/4
4
up to n terms
(30) AB+CD+A
2
B
2
+C
2
D
2
up to n terms
(31) Write a program to generate fibona series 0,1,1,2,3,5,8,13 up to n terms.
(32) 1*3 + (1+2) * 3
2
+ (1+2+3) * 3
3
+ (1+2+3+4) 3
4
up to n terms
(33) 1!/2! + 3!/4! + 5!/6! Up to n terms
(34) X/1! - X
3
/3! + X
5
/5! - X
7
/7! Up to n terms
(35) Write a program to check whether the entered no is odd or even.
(36) Write a program to calculate the sum of odd and even number between
given no of series.





65
(37) Write a program for following output for n no of rows( Pascal triangle)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
(38) Write a program for following output for n no of rows.
1
0 1
1 0 1
0 1 0 1
(39) Write a program that count the area for circle, square, rectangle and
triangle
using Switch-Case control structure
(40) Write a program that take input of percentage in integer only. Print the
result for following condition using Switch-Case control structure.
If student has 70% or more then 70% then DISTINCTION.
If student has percentage between 60 and 69 then FIRST CLASS.
If student has percentage between 50 and 59 then SECOND CLASS.
If student has percentage between 40 and 49 then PASS CLASS.
If student has percentage less then 40 then FAIL.

(41) Write a program that take input of year in 4 digit. Determine whether
the year is leap year or not.(try to solve this problem with && and or
operator)

(42)Write a program that determine the grade of steel according to following
condition.
1 Hardness must be greater then 50
2 Carbon must be less then 0.7
3 Tensile must be greater then 5500

Take the input for above qualities through keyboard from user
Grades are decided as follows.

Grade A if all 3 conditions are met.
Grade B if condition (1) and (2) are met.
Grade C if condition (2) and (3) are met.
Grade D if condition (1) and (3) are met.
Grade E if only one condition met.
Grade F if none of conditions are met.

(43) Write a program to find maximum from 3 values using conditional
operator.
(44) Write a program that generate same output as of program no (10) using
break
statement.
(45) Write a program that performs the sum of given numbers until user says
no
using Go-To statement.
(46) Write a sample program that demonstrate the use of Continue statement.
66
(47) Write a program that find maximum and its position from 10 number
using array.
(48) Write a program that sort the value in ascending order in array.
(49) Write a program that generate the array of distinct or unique values from
the array given by user.
(50) Write a program that calculates the total marks and percentage for 5
subject marks using array.
(52)Write a program that arrange the array values in reverse order.
(53) Write a program that perform the summation and subtraction of two
matrices.
(54) Write a Program that perform the sum of rows and sum of column for n
by n matrix
(55) Write a Program that perform the sum of rows and sum of column for m
by n matrix
(55) Write a program that take the input of sales of 5 salesman for 4
different quarter of year. Count the total sales perform by each salesman and
sales performed during each quarter also perform the grand total sales.
(56) Write a program that perform the sum of diagonal elements of n by n
matrix
(57) Write a program of spiral matrix using 2-D matrix.
(58) Write a function to count the simple interest..
(59) Write a function that count compound interest.
(60) Write a function to generate the square of any given number
(61) Write a function which should work as a power function
(62) Write a functions to count the area of circle, triangle, rectangle and
square.
(63) Write a function to print any character for n no of time.
(64) Write a function which should work as absolute function.
(65)Write a program witch demonstrate the use of pre and post increment and
decrement operator also define the use of assignment operator like +=, -= ,
*= , /=.
(66)Write a functions which should work like a isnum() ,isalpha() ,ischar() functions .
(67)Write a functions which should work like (1) asc() function which returns an integer value
of given character(2) char() function which returns character value for given integer value.
(68)Write a function to interchange the two value a and b (Call By Reference) witch passes the
2 arguments in form of address of a and b variable with declaration like Void swap(int *, int *).
(69)Write a void function which count the area and perimeter of circle(Call By Reference)
witch passes radius , address of area variable and address of perimeter variable with
declaration like Void count(float , float *, float *)
(70)Write a function to count mean for discrete data. User has to pass only n no of values and
address of first element of an array with declaration like float mean(int *,float *)
(71)Write a function to find out maximum from of n no of values. User has to pass n no of
elements and Address of first variable in an array. With declaration like int findmax(int,int *).
(72) Write a function to arrange integer values in ascending order in an array witch passes n of
elements and address of first element of an array with declaration like void arrange(int,int *)
(73)Write a program that demonstrate the use of gets() and puts() .
(74)Write a program that demonstrate the use of strcmp(), strlen(), strcpy(), strrev(), strupr(),
strlwr() and strcat() built-in function.
(75)Write a program that take input of name of 10 students with gets() and just print them
with puts() function.

67
(76)Write a program or function which should work like a strlen() function.
(77)Write a program or function which should work like a strcmp() function.
(78)Write a program or function which should work like a strcpy() function.
(79)Write a program or function which should work like a strcat() function.
(80)Write a program or function which should work like a strrev() function.
(81)Write a program or function which should work like a strupr() function.
(82)Write a program or function which should work like a strlwr() function.
(83)Write a program that take input names of 10 students. Arrange them in ascending order in
string array.
(84)Write a program that take input paragraph of 10 lines. Count total no of word and total no
of characters (Excluding blank spaces).
(85)Write a pre-processor directives which returns (1) area of circle (2) perimeter of circle
(86)Write a pre-processor directives which checks works like a (1) isdigit() (2) isalpha()
functions
(87)Write a preprocessor directives which demonstrate the use of #ifdef and #ifndef.
(88)Write a preprocessor directives which use some symbolic directives for (&&,||,==) to
operators.
(89)Write a simple program using structure that demonstrate different type of declaration of
structure variable
(90)Write a program using structure that accept rollno,name and percentage of students.
(91)Write a program that demonstrate the use of aray of structure variable
(92)Write a program that demonstrate how one structure variable can be copied into another
(93)Write a program that demonstrate the use of structure and function.
(94)Write a program that access the structure variable using pointer.
(95)Write a program that demonstrate the use of nested structure. For example
struct marks struct student
{ {
int s1; int rollno;
int s2; char name[20];
int s3; struct mark m1;
int tota; }s1;
};
(96)Write a program that demonstrate the use of getch(),getche(),getchar() and putchar()
functions.
(97) Write a program that demonstrate the use of formatted input with
(%[ ]) operator.
(98)Write a program that demonstrate the use of formatted output like
printf("%10d",rollno); ,printf("%10.2f",salary) and printf("%*.*s",10,5,name)
(99)Write a simple program that explain the precedence(priority) and associativity.












68
C THEORY
1. Describe the several features of C language.
2. Explain the structure of c program.
3. Explain why C language is called middle level language.
4. List all the relational operators available in C Explain with suitable example
5. List all the logical operators available in C Explain with suitable example
6. List all the assignment operators available in C Explain with suitable example
7. List all the arithmetic operators available in C Explain with suitable example
8. Explain pre and post increment-decrement operator with suitable example.
9. List all the Bitwise operators available in C Explain with suitable example
10. Explain sizeof() operator with suitable example.
11. Explain conditional opertor or turnery operator with suitable example.
12. Explain precedence and associativity with suitable example.
13. Explain automatic type conversion and casting with suitable some example.
14. List all the basic or primary data-types available in C with their format specifier and size in
bytes and their declaration statement.
15. Explain the differnace between getch(),getche() and getchar() functions.
16. Explain the difference between gets() and scanf() function and printf() and puts function
with suitable example
17. Explain formatted output with suitable example
18. Explain formatted input with % [ ] with suitable example
19. Explain nested if-else control structure with suitable example.
20. Explain Switch-Case with suitable example.
21. Explain Go-To statement with some suitable exmple
22. Explain types of loops with their syntex available in C. Explain any one with suitable
example.
23. Explain break-continue with suitable example.
24. Explain one-dimension array with some example and how elements are allocated with
space in memory.
25. Explain tow-dimension array with some suitable example.
26. List some of the built-in string handling function with some suitable example.
27. Explain the user define function with their structure and with small suitable example.
28. List the advantages or feature of functions.
29. Explain recursion with suitable example.
30. List all the storage class available in c and specify the scope, lifetime,storage and their
default initial value.
31. Explain what is pointer with some small example.
32. Explain call by value and call by reference with suitable example
33. Explain structure and also define how members of structure variable can be accessed and
how they are allocated in memory.
34. Explain what is macro or preprocessor directives.explain the use of # define, # ifdef,#
ifndef and # include with some suitable example.






69

You might also like