Você está na página 1de 69

CONTENTS OF C LANGUAGE

Introduction to C
Importance of C
Sample Program
Basic Structure of C Programs
Constants, Variable, Data types
Operators and expressions
Assignment Operators
Decision making and branching
Simple if statement
if .... else statement
Nested if .... else statement
else if ladder
The Switch Statement
The Conditional Operator(?:)
The goto statement
Decision making and looping
The while statement
The do ... while statement
The for statement
Arrays
One -dimensional arrays
Two -dimensional arrays
Multi -dimensional arrays
Handling of character strings
User -Defined Functions
Cal by value
Call by Reference
Recursion
Structures and Unions
Enum
Pointers
Pre-processor
Macro
File Management in C
Error Handling During I/O Operations

Creator of Such a Wonderful language C

The C programming language was designed by Dennis Ritchie at Bell Laboratories in


the early 1970s.

Its Immediate ancestors and Influenced by

ALGOL 60 (1960),

CPL (Cambridge, 1963),

BCPL (Martin Richard, 1967),

BCPL Reference Manual by Martin Richards, dated July 1967. The language
described here supplied the basis for much of our own work and that of others. The
linked page discusses the circumstances, while the files linked under it have the
manual itself.

B (Ken Thompson, 1970)

Ken Thompson instead ended up developing a compiler for a new highlevel language he called B, based on the earlier BCPL language developed by
Martin Richard. Where it might take several pages of detailed PDP-7 assembly
code to accomplish a given task, the same functionality could typically be
expressed in a higher level language like B in just a few lines. B was thereafter
used for further development of the Unix system, which made the work much
faster and more convenient.
C was not written as a teaching aid, but as an implementation language. C
is a computer language and a programming tool which has grown popular
because programmers like it! It is a tricky language but a masterful one. Sceptics
have said that it is a language in which everything which can go wrong does go
wrong. True, it does not do much hand holding, but also it does not hold anything
back. If you have come to C in the hope of finding a powerful language for writing
everyday computer programs, then you will not be disappointed. C is ideally
suited to modern computers and modern programming.

Traditionally used for systems programming, though this may be changing in favor of
C++

Traditional C:

The C Programming Language, by Brian Kernighan and Dennis Ritchie, 2nd


Edition, Prentice Hall.

Referred to as K&R .

High Levels and Low Levels


Any kind of object that is sufficiently complicated can be thought of as having levels of
detail; the amount of detail we see depends upon how closely we scrutinize it. A computer
falls definitely into the category of complex objects and it can be thought of as working at
many different levels. The terms low level and high level are often used to describe these
onion-layers of complexity in computers. Low level is perhaps the easiest to understand: it
describes a level of detail which is buried down amongst the working parts of the machine:
the low level is the level at which the computer seems most primitive and machine-like. A
higher level describes the same object, but with the detail left out.
C is called a high level, compiler language. The aim of any high level computer language is
to provide an easy and natural way of giving a programme of instructions to a computer (a
computer program). The language of the raw computer is a stream of numbers called
machine code.

Basic ideas about C:


What to do with a compiler. What can go wrong .
Using a compiler language is not the same as using an interpreted language like BASIC or a
GNU shell. It differs in a number of ways. To begin with, a C program has to be created in two
stages:

Firstly, the program is written in the form of a number of text files using a screen
editor. This form of the program is called the source program. It is not possible to
execute this file directly.

Secondly, the completed source file is passed to a compiler--a program which


generates a new file containing a machine code translation of the source text. This
file is called an object file or executable file. The executable file is said to have been
compiled from the source text.

Compiler languages do not usually contain their own editor, nor do they have words like RUN
with which to execute a finished program.

The Compiler
A C program is made by running a compiler which takes the typed source program and
converts it into an object file that the computer can execute. A compiler usually operates in
two or more phases (and each phase may have stages within it). These phases must be
executed one after the other.

This development of Unix in C had two important consequences:

Portability. It made it much easier to port Unix to newly developed computers,


because it eliminated the need to translate the entire operating system to the new
assemble language by hand:

First, write a C-to-assembly language compiler for the new machine.

Then use the new compiler to automatically translate the Unix C language
source code into the new machine's assembly language.

Finally, write only a small amount of new code where absolutely required by
hardware differences with the new machine.

Improvability. It made Unix easy to customize and improve by any programmer that
could learn the high-level C programming language. Many did learn C, and went on to
experiment with modifications to the operating system, producing many useful new
extensions and enhancements.

Standard C:

Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI


C

International standard (ISO) in 1990 which was adopted by ANSI and is known as
C89

As part of the normal evolution process the standard was updated in 1995 (C95) and
1999 (C99)

IMPORTANCE OF C:

A set of built-in functions and operators can be used to write any complex program.
Programs written in C are efficient and fast.
This is,due to its variety of data types and powerful operators. It is many times faster
than BASIC.
Several standard functions are available which can be used for developing programs.
C is highly portable.
C language is well suited for structured programming, thus requiring the
User to think of a problem in terms of modules or blocks.
A proper collection of these modules would make a complete program. This modular
structure makes program debugging, testing and maintenance easier.
Another important feature of C is its ability to extend itself.
A C program is basically a collection of functions that are supported by the C library.
We can continuously add our own functions to the C library.
With the availability of a large number of functions, the programming task becomes
simple.

Programming style
C is actually a free format language. This means that there are no rules about how it must
be typed, when to start new lines, where to place brackets or whatever.
The reasons for choosing a well structured style are that:

Long programs are manageable only if programs are properly organized.

Programs are only understandable if care is taken in choosing the names of variables
and functions.

It is much easier to find parts of a program if a strict ordering convention is


maintained. Such a scheme becomes increasingly difficult to achieve with the size
and complexity of the problem.

Elements of a C Program
A C development environment includes

System libraries and headers: a set of standard libraries and their header files.
For example see /usr/include and glibc.

Application Source: application source and header files

Compiler: converts source to object code for a specific platform

Linker: resolves external references and produces the executable module

C Standard Header Files you may want to use

Standard Headers you should know about:

Stdio.h file and console (also a file) io: perror , printf, open , close , read ,
write , scanf , etc.

stdlib.h - common utility functions: malloc , calloc , strtol , atoi etc

string.h - string and byte manipulation: strlen , strcp y, strcat , memcpy ,


memset , etc.

ctype.h character types: isalnum , isprint , isupport , tolower, etc.

errno.h defines errno used for reporting system errors

math.h math functions: ceil, exp, floor, sqrt, etc.

signal.h signal handling facility: raise, signal, etc

stdint.h standard integer: intn_t, uintn_t, etc

time.h time related facility: asctime, clock, time_t, etc.

User program structure

there must be one main function where execution begins when the program is
run. This function is called main

int main (void) { ... },

int main (int argc, char *argv[]) { ... }

UNIX Systems have a 3rd way to define main(), though it is not POSIX.1
compliant
int main (int argc, char *argv[], char *envp[])

additional local and external functions and variables.

The form of a C program


What goes into a C program? What will it look like?
The basic building block in a C program is the function. Every C program is a collection of
one or more functions, written in some arbitrary order. One and only one of these functions
in the program must have the name main(). This function is always the starting point of a C
program, so the simplest C program would be just a single function definition:
main ()
{
}

The parentheses () which follow the name of the function must be included even though
they apparently serve no purpose at this stage. This is how C distinguishes functions from
ordinary variables.

FORMAT OF A SIMPLE C PROGRAM:


main() Function name
{
// Start of program
----- Program statements

} End of program
/* A program that prints out the sentence This is my first C program. */
#include <stdio.h>
int main (void)
{
printf ("This is my first C program.\n");
return (0);
}

BASIC STRUCTURE OF C PROGRAM


A C program can be viewed as a group of building blocks called functions.
A function is a subroutine that may include one or more statements designed to perform a
specific task. To write a C program, we first create functions and then put them together.
A C program may contain one or more
Sections
Documentation Section (Comments about the program)
Link Section
(Header)
Global Declaration Section
main() Function Section
{
Declaration Part (Variable Declaration)
Executable Part (Statements)
}
Subprogram section

Function1
Function2
.. (User-defined functions)
Function
The documentation section consists of a set of comment lines giving the name of the
program,
the author and other details which the programmer would like to use later.
The link section provides instructions to the compiler to link functions from the system
library.
There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration section
that is outside of all the functions.
Every C program must have one main() function section.
This section contains two parts,
1. declaration part and
2. executable part.
The declaration part declares all the variables used in the executable part. There is at least
one statement in the executable part. These two parts must appear between the opening
and the closing braces.
The program execution begins at the opening brace and ends at the closing brace. The
closing brace of the main function section is the logical end of the program. All the
statements in the declaration and executable parts end with a semicolon. The subprogram
section contains all the user-defined functions that are called in the main function.
User defined -functions are generally placed immediately after the main function,
although they may appear in any order. All sections, except the main function
may be absent when they are not required.
EXECUTING OF A C PROGRAM
Executing a program written in C involves a series of steps. These are:
1.
2.
3.
4.

Creating the program


Compiling the program
Linking the program with functions that are needed from the C library
Executing the program.

The C Character Set:


A character denotes any alphabet, digit or special symbol used to represent information.
The characters in C are grouped into the following categories:
1. Letters
2. Digits
3. Special Characters
4. White Spaces
White spaces may be used to separate words, but are prohibited between
the characters of keywords and identifiers.
1. Letters:
Uppercase AZ
Lowercase az
2. Digits:
All decimal digits 0 ......... 9
Special Characters

Comma (,)
Period (.)
Semi colon (;)
Colon (:)
Question mark (?)
apostrophe ()
Quotation mark ()
Exclamation mark (!)
vertical bar (|)
slash (/)
back slash (\)
tilde (~)
under score (_)
dollar sign ($)
percent sign (%)
number sign (#)

& ampersand(&)
& caret(^)
& asterisk(*)
& minus(-)
& plus sign(+)
& opening angle bracket(<)
& less than sign(<)
& closing angle bracket(>)
& greater than sign(>)
& left parenthesis(( )
& right parentheses ( ))
& left bracket([)
& right bracket(])
& left brace({)
& right brace(})

4. White Space: Blank space


C Tokens (Constants, Variables and Keywords):
A constant is a quantity that doesnt change. This quantity can be stored at a locations in
the memory of the computer. A variable also can be stored in the memory of the computer.
But the contents of the variable can be changed.
Types of C Constants:
C constants can be divided into two major categories:
1. Primary Constants & 2. Secondary Constants
1. Primary Constants we learn Integer Constants, Real Constants, Character
Constants and
2. Secondary Constants we learn Array, Pointers, Structures,
Union, Enum etc.
Rules for constructing Integer Constants:
a) An integer constant must have at least one digit
b) It must not have a decimal point.
c) It can be either positive or negative.
d) If no sign precedes an integer constant it is assumed to be positive.
e) No commas or blanks are allowed within an integer constant.
f) The allowable range for integer constants is -32768 to 32767.
Ex: 426
+782
-8000
-7605
/* program for Integer nos */
# include<stdio.h>
void main()
{
int a, b,c;
clrscr();
c=a+b;
printf(value of c is %d,c);
getch();

10

}
Rules for constructing Real Constants:
a)
b)
c)
d)
e)
f)

A real constant must have at least one digit


It must have a decimal point.
It can be either positive or negative.
If no sign precedes a real constant it is assumed to be positive.
No commas or blanks are allowed within an real constant.
The allowable range for real constants is -3.4e38 to 3.4e38.

Ex: +325.34
+782.0
-80.76
-760.578
#include <stdio.h>
int main (void)
{
/* declarations */
int a;
double x;
/* executable statements */
a = 1000;
x = 100.583665;
printf ("%d\n", a);
printf ("%3d\n", a);
printf ("%4d\n", a);
printf ("%5d\n", a);
printf ("\n");
printf ("%lf\n", x);
printf ("%15lf\n", x);
printf ("%15.4lf\n", x);
printf ("%18.2lf\n", x);
printf ("%12.0lf\n", x);
return (0);
}
Rules for constructing Character Constants:
a) A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
b) The maximum length of a character constant can be 1 character.
Ex:

A
I
5
=
/ * Inputting characters
A program that asks the user for 4 characters and displays them on the screen.
#include <stdio.h>
int main (void)

11

{
/* declarations */
char letter1, letter2, letter3, letter4;
printf ("enter a name: ");
scanf ("%c%c%c%c", &letter1, &letter2, &letter3, &letter4);
printf ("you entered: %c%c%c%c", letter1, letter2, letter3, letter4);
printf (" / backwards: %c%c%c%c\n", letter4, letter3, letter2, letter1);
return (0);
}
output:
enter a name: lucky
you entered : lucky
C Keywords:
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names. There are only 32 keywords available in C.
auto
break
case
char
const
continue
default
do

double
else
enum
extern
float
far
for
goto

if
int
long
near
register
return
short
signed

static
struct
switch
typedef
union
unsigned
void
while

C Instructions:
There are basically four types of instructions in C.
1. Type Declaration Instruction
2. Input/Output Instruction
3. Arithmetic Instruction
4. Control Instruction
1. Type Declaration Instruction:
This instruction is used to declare the type of variables being used in the program. Any
variable used in the program must be declared before using it in any statement. Type
declaration statement is usually written at the beginning of the C program.
Example:
Int bas;
float rs, grossal;
char name, code;
2. Input/Output Instruction:
This instruction is used to perform the function of supplying input data to a program
(scanf() function and obtaining the output results from it ( printf() function).
Trying printf and scanf
A program that asks the user for two numbers and prints out the sum and the product.
#include <stdio.h>
int main (void)
{

12

/* declarations */
double x, y, z;
/* executable statements */
printf ("Enter two integer numbers: ");
scanf ("%lf %lf", &x, &y);
z = x + y;
printf ("\nThe sum of %lf and %lf is %f.\n", x, y, z);
printf ("\nThe product of %lf and %lf is %lf.\n", x, y, x*y);
return (0);
}
3. Arithmetic Instruction:
A C arithmetic instruction consists of a variable name on the left hand side of = and variable
names & constants on the right hand side of =. The variables and constants appearing on
the right hand side of = are connected by arithmetic operators like +, - *, and /.
Example:
int ad;
float kot, data;
ad = 3200;
kot = 0.0056;
data = ad + kot+ 32 +5;
The variables and constants together are called operands and +, -, *, / arecalled operators.
The right hand side is evaluated and this value is then
assigned to the variable on the left hand side. C allows only one variable on left
hand side of =. Character constants are stored in character variable as follows:
char a, b, d;
a = F;
b = G;
d = +;
An Arithmetic
operation between an integer and integer always yields an integer result.
Operation between a real and real always yields a real result.
Operation between an integer and real always yields a real result.
Operation Result Operation Result
5/2 2 2/5 0
5.0/2 2.5 2.0/5 0.4
5/2.0 2.5 2/5.0 0.4
5.0/2.0 2.5 2.0/5.0 0.4
The arithmetic operations are performed an order given below:
1. Multiplication 2. Division 3. Modulo Division 4. Addition
5. Substraction 6. Assignment.
4. Control instruction:
This instruction is used to control the sequence of execution of various statements in a C
program. The control instructions determine the flow of control in a program. There are four
types of control instructions in C.
1. Sequence Control Instruction

13

2. Selection or Decision Control Instruction


3. Repition or Loop Control Instruction
4. Case Control Instruction

OPERATORS AND EXPRESSIONS


C supports a rich set of operators. An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables. They usually form a part of the mathematical of logical
expressions.
C operators can be classified into eight categories as shown below:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
1. ARITHMETIC OPERATORS:
C provides all the basic arithmetic operators (+, -, *, /). The unary minus operator, in effect,
multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes
its sign.
Operator
Meaning
+
Addition
Subtraction
*
Multiplication
/
Division
%
Modulo division
Interger division truncates any fractional part.
/*
Example for Arithmatic operations */
#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z=0;
clrscr();
printf(" enter the values of x and y :");
scanf("%d %d",&x,&y);
z=x+y;
printf("\n the addition of two numbers : %d",z);
z=x-y;
printf("\n the subtraction of two numbers : %d",z);
z=x*y;
printf("\n the multiplication of two numbers : %d",z);
z=x/y;
printf("\n the division of two numbers : %d",z);
z=x%y;
printf("\n the remainder of x/y is : %d",z);
getch();
}

14

RELATIONAL OPERATORS:
We often compare two quantities, and depending on their relation, take certain decisions.
For example, we may compare the age of two persons, or the price of two items, and so on.
These comparisons can be done with the help of relational operators.
C supports six relational operators as shown below:
Relational Operators
Operator
Meaning
<
is less than
<=
is less than or equal to
>
is greater than
>=
is greater than or equal to
!=
is not equal to
==
is equal to
4.5 <= 10
TRUE
4.5 < -10
FALSE
-35 >= 0
FALSE
10 < 7+5 TRUE
a+b = = c+d TRUE (only if the sum of values of a and b is equal to the sum of
values of c and d.)

LOGICAL OPERATORS:
C has the following three logical operators.
1. && meaning logical AND
2. || meaning logical OR
3. ! meaning logical NOT
Some examples of the usage of logical expressions are given below:
1. if(age > 55 && salary < 1000)
2. if(number < 0 || number > 100)

ASSIGNMENT OPERATORS
Assignment operators are used to assign the result of an expression to a
variable. C has a set of shorthand assignment operators as shown below:
v op = exp;
where v is a varible, exp is an expression and op is a shorthand
assignment operator.
It is equivalent to
v = v op (exp);
/* A program that makes a few changes in variable values using the assignment operator. */
#include <stdio.h>
int main (void)
{
/* declarations */
int a, b, c, d, e;

15

/* fill variable a */
a = 10;
/* modify variable a few times*/
a = 20;
a = 10 + a;
a = a + a + 2;
a = 2 + a;
/* a few more assignments */
b = a;
c = b = 5;
c = 10 + a;
d = a + a + 2;
e = 20 + a;
a = a - b + c;
/* the final values are... */
printf ("a:%4d\n b:%4d\n c:%4d\n d:%4d\n e:%4d\n", a, b, c, d, e);
return (0);
}

Shorthand Assignment Operators:


Statement with simple Statement with
assignment operator
shorthand operator
a=a+1
a+=1
a=a-1
a-=1
a=a*a
a * =a
a = a*(n+1)
a* = (n+1)
a = a / (n+1)
a / = (n+1)
a=a%b
a%=b

INCREMENT AND DECREMENT OPERATORS:


C has two very useful operators not generally found in other languages.
These are the increment and decrement operators:
+ + and - Increment and decrement
/ *A program showing the different uses of the increment and decrement operators. */
#include <stdio.h>
int main (void)
{
int a, b;
a = 5;
/* increment (++) */
/* a is incremented by 1 */
++a;
printf ("After ++a, a is now %d\n", a);

16

/* a is once more incremented by 1 */


a++;
printf ("After a++, a is now %d\n", a);
/* a is incremented but b gets the current a */
b = a++;
printf ("After b=a++, a is now %d and b is %d\n", a, b);
/* a is incremented and b gets the incremented a */
b = ++a;
printf ("After b=++a, a is now %d and b is %d\n", a, b);
/* decrement (--) */
/* a is decremented by 1 */
--a;
printf ("After --a, a is now %d\n", a);
/* a is once more decremented by 1 */
a--;
printf ("After a--, a is now %d\n", a);
/* a is decremented but b gets the current a */
b = a--;
printf ("After b=a--, a is now %d and b is %d\n", a, b);
/* a is decremented and b gets the decremented a */
b = --a;
printf ("After b=++a, a is now %d and b is %d\n", a, b);
return (0);
}

CONDITIONAL OPERATOR:
A ternary operator pair ?: is available in C to construct conditional
expressions of the form
exp1 ? exp2 : exp3;
To find out a number which is greater than other number.
This can be done by using if.. else statements as follows:
a = 10;
b = 15;
if (a > b)
x =a;
else
x = b;
These same program can be written as shown below:
x = (a >b)? a: b;
#include<stdio.h>
void main()
{
Int a=5,b=5;
(a>b)?a is greater: b is greater;

17

BITWISE OPERATOR
C has a distinction of supporting special operators known as bitwise operators for
manipulation of data at bit level. These operators are used for testing the bits, or shifting
them right or left. Bitwise operators may not be
applied to float or double.

SPECIAL OPERATORS
C supports some special operators such as comma operator, sizeof operator, pointer
operators (& and *) and member selection operators ( . And ->).
The sizeof Operator
The sizeof is a compile time operator and, when used with an operand, it
returns the number of bytes the operand occupies. The operand may be a
variable, a constant or a data type qualifier.
Example:
m = sizeof(sum);
8. DECISION MAKING AND BRANCHING
INTRODUCTION
In C program, a set of statements which are normally executed sequentially in
the order in which they appear. This happens when no options or no repetitions of
certain calculations are necessary. However, in practice, we have a number of
situations where we may have to change the order of execution of statements based
on certain conditions, or repeat a group of statements until certain specified
conditions are met. This involves a kind of decision making to see whether a
particular condition has occurred or not and then direct the computer to execute
certain statements accordingly. C language provides decision making statements
known as control or decision making statements.
There are four type of such statements.
1.
2.
3.
4.

if statement
switch statement
Conditional operator statement
goto statement

SIMPLE IF STATEMENT
The general form of a simle if statement is
if(test expression)
{
statement-block;
}
statement-x;
The statement-block may be a single statement or a group of statements. If the test
expression is true, the statement-block will be executed; otherwise the statement-block will
be skipped and the execution will jump to the statement-x. Remember, when the condition is
true both the statement-block and the statement-x are executed in sequence.
/* A program is to show the execution of IF Statement */

18

#include<stdio.h>
void main(){
Int raining;
If(raining=true)
Printf( this is rainy season);
Printf(this is too rainy);
Getch();
:

IF ..... ELSE STATEMENT


The if .... else statement is an extension of the simple if statement. The
general form is if(test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x
If the test expression is true, then the true-block statement(s), immediately following the if
statement are executed; otherwise, the false-block statement(s) are executed. In either
case, either true-block or false-block will be executed, not both. In both the cases, the
control is transfered subsequently to statement-x.
Expression is true
x
x
x
x
x
x

if

= = y x is equal to y
!= y x is not equal to y
< y x is less than y
> y x is greater than y
<= y x is less than or equal to y
>= y x is greater than or equal to y

Even vs. odd


/* A program that determines if an integer number is odd or even.
#include <stdio.h>
int main (void)
{
int number, even;

/* ask user for number */

printf ("Enter an integer number: ");


scanf ("%d", &number);
/* determine if number is even and put in variable */
even = (number % 2 == 0);
/* display report */
if (even)
printf ("%d is an even number.\n", number);

19

else
printf ("%d is an odd number. \n", number);
}

return (0);

11. NESTED IF ......... ELSE STATEMENT:


When a series of decisions are involved, we may have to use more than one if ..... else
statement in nested form as follows:
12. ELSE IF LADDER
There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement
associated with each else is an if. It takes the following general form:
An electric power distribution company charges its domestic
consumers as follows:
Consumption Units Rates of charge
0 to 200 Rs. 0.50 per unit
201 to 400 Rs. 100 plus Rs. 0.65 per unit
401 to 600 Rs. 230 plus Rs. 0.80 per unit excess of 400
601 and above Rs. 390 plus Rs. 1.00 per unit
excess of 600
if(units <= 200)
charges = 0.5*units;
else if(unit <= 400)
charges = 100 + 0.65* (units-200);
else if(unit <= 600)
charges = 230 + 0.80*(units-400);
else
charges = 390 + 1.00*(units - 600);

THE SWITCH STATEMENT


We can design a program using if statements to control the selection. However, the
complexity of such a program increases dramatically when the number of alternatives
increases. The program becomes difficult to read and
follow. C has a bult-in multiway decision statement known as a switch. The switch
statement test the value of a given variable (or expression) against a list of case values and
when a match is found, a block of statements associated with that case is executed. The
general form of the switch statement is as shown below:
The expression is an integer expression or characters. Value-1, value-2 ... are constants are
known as case
lables. Each of these values should be unique within a swich statement. block-1, block-2 .....
are statement
lists. There is no need to put braces around these blocks. Note that case labels end with a
colon(:). When the switch is executed, the value of the expression is successively compared
against the values value-1, value-2, .....
If a case is found whose value matches with the value of the expression, then the block of
statements that
follows the case are executed.:
The Switch Statement is shown below:
switch(expression)

20

{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
.........
default:
default-blcok;
break;
} statement-x;
The traffic light program (switch)
A program that displays the recommended actions depending on the color of a traffic light.
Unlike the previous program, this implementation uses the switch statement.

#include <stdio.h>
int main (void)
{
char colour;
/* ask user for colour */
printf ("Enter the colour of the light (R,G,Y,A): ");
scanf ("%c", &colour);
/* test the alternatives */
switch (colour)
{
/* red light */
case 'R':
case 'r':
printf ("STOP! \n");
break;
/* yellow or amber light */
case 'Y':
case 'y':
case 'A':
case 'a':
printf ("CAUTION! \n");
break;
/* green light */
case 'G':
case 'g':
printf ("GO! \n");
break;
/* other colour */
default:
printf ("The colour is not valid.\n");
}
return (0);

21

15. THE GOTO STATEMENT


C supports the goto statement to branch unconditionally from one point to another in the
program. Although it may not be essential to use the goto statement in a highly structured
language like C, there may be occations when the use of goto might be desirable. The goto
requires a label in a order to identify the place where the branch is to be made. A label is
any valid variable name, and must be followed by a colon. The label is placed immediately
before the statement where the control is to transferred. Before goto statement. if condition
must be added. The general forms of goto and label statements are shown below:
Forward jump
if(test expression)
goto label;
...............
...............
...............
label:
statement;

Backward jump
label:
statement;
.............
..............
if(test expression)
goto label;

The label: can be anywhere in the program either before or after the goto label; statement.
During the running of a program when a statement like goto begin; is met, the flow of
control will jump to the statement immediately
following the label begin:.Note that a goto breaks the normal sequential execution of the
program. If the label: is before the statement goto label; a loop will be formed and some
statements will be executed repeatedly. Such a jump is known as backward jump. On the
other hand, if the label: is placed after the goto label; some statements will be skipped and
the jump is known as a forward jump. A goto is often used at the end of a program to direct
the control to go to the input statement, to read further data. Consider the following
example:
main()
{
double x, y;
read:
scanf(%lf, &x);
if(x < 0)
goto read;
y = sqrt(x);
printf(%lf\n, y);
}
16. DECISION MAKING AND LOOPING
INTRODUCTION
It is possible to execute a segment of a program repeatedly by introducing a counter and
later testing it using the if statement and goto statement. It forms a loop. In looping, a
sequence of statements are executed until some conditions for termination of the loop are
satisfied. A program loop consists of two segments, one known as the body of the loop
and the other known as the control statement. The control statement tests certain
conditions and then directs the repeated execution of the statements contained in the body
of the loop. Depending on the position of the control statement in the loop, a control
structure may be classified either as the entry-controlled loop or as the

22

exit-controlled loop. In entry-control loop, the control conditions are tested before the
start of the loop execution. If the conditions are not satisfied, then the body of the loop will
not be executed. In the case of an exit-controlled loop,
the test is performed at the end of the body of the loop and therefore the body is executed
unconditionally for the first time.
A looping process, in general, would include the following four steps:
1. Setting and initialization of a counter.
2. Execution of the statements in the loop.
3. Test for a specified condition for exection of the loop.
4. Incrementing the counter.
The C language provides for three loop constructs for performing loop operations. They are:
1.The while statement 2.The do - while statement 3. The for statement
17. THE WHILE STATEMENT
The simplest of all the looping structures in C is the while statement.
The basic format of the while statement is shown below:
while(test condition)
{
body of the loop
}
The while is an entry-controlled loop statement. The test-condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the body
continues until the test condition finally becomes false and the control is tranferred out of
the loop. On exit, the program continues with the statement immediately after the body of
the loop. The 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.
A simple count from 1 to 100
/* A program that displays the numbers between 1 and 100.
#include <stdio.h>
int main (void)
{
int n;
n = 1; /* loop initialization */
/* the loop */
while (n <= 100) /* loop condition */
{
printf ("%d ", n); /* loop body */
n = n + 1; /* loop update */
}
return (0);
}
18. THE DO ..... WHILE STATEMENT
In while loop a test condition is checked before the loop is executed. Therefoere, the body
of the looop may not be executed at all if the condition is not satisfied at the very first
attempt. On some occations it might be necessary
to execute the body of the loop before the test is performed. Such situations can be handled
with the help of the do statement. The takes the form:

23

do
{
body of the loop
}
while(test-condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the test-condition in the while statement is evaluated. If the condition
is true, the program continues to
evaluate the body of the loop once again. This process continues as long as the condition is
true. When the condition becomes false, the loop will be terminated and the control goes to
the statement that appears immediately after the while statement. Since the test-condition
is evaluated at the bottom of the loop, the do ...
while construct provides an exit-controlled loop and therefore the body of the loop is
always executed at least once.
/* Program to demonstrate do - while
program to print menu */
#include<stdio.h>
#include<conio.h>
main()
{
int choice,x,y;
char c='y';
clrscr();
printf(" enter the two numbers :");
scanf("%d %d",&x,&y);
do{
printf("--------- MENU ----------\n");
printf("
1 . ADD \n");
printf("
2 . SUB \n");
printf("
3 . MUL \n");
printf("
4 . DIV
\n");
printf("
5 . EXIT \n");
printf(" enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n sum= %d ",x+y);
break;
case 2: if(x>y)
printf("\n difference = %d ",x-y);
else
printf("\n difference = %d",y-x);
break;
case 3: printf("\n multiplication = %d ",x*y);
break;
case 4: if(y!=0)
printf("\n division = %d ",x/y);
else
printf("\n infinity ");
break;
case 5: exit(0);
default: printf("\n invalid in-put");
break;

24

}
fflush(stdin);
printf(" do u want to continue (y/n) :");
scanf("%c",&c);
}while(c=='y'||c=='Y');
getch();
}

THE FOR STATEMENT


The for loop is another entry-controlled loop that provides a more
concise loop control structure. The general form of the for loop is shown
below:
for(initialization; test-condition; increment)
{
body of the loop
}
The execution of the for statement is as follows:
1. Initialization of the control variable is done first, using assignment statements such as
i=1. The variable i is known as loop-control variable.
2. The value of the control variable is tested using the test-condition. The test condition is a
relational expression, such as i<10 that determines when the loop will exit. If the condition
is true, the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now, the control variable is
incremented using an assignment statement such
as i = i+1 and the new value of the control variable is again tested to see whether it
saatisfies the loop condition. If the conition is satisfied, the body of the looop is again
executed. This process continues till the value of the
control variable fails to satisfy the test-condition.
#include<stdio.h>
void main()
{
int x;
clrscr();
for(x = 0; x <= 9; x = x + 1)
{
printf(%d, x);
}
printf(\n);
getch();
}
Comparision of the while, do, for loops
While
do
n = 1;
n = 1;
while(n <= 10)
do
{
{
----------n = n + 1;
n = n + 1;
}
}
while(n <= 10);

25

for
for(n = 1; n <= 10; ++n)
{
---------}

ARRAYS
Aset of variables of same type is called array.An array shares a common name. For instance,
we can define an array name salary to represent a set of salries of a group of employees. A
particular value is indicated by writing a
number called index number or subscript in brackets after the array name.
For example,
salary[10]
while the complete set of values is referred to as an array, the individual
values are called elements. Array can be of any variable type.

ONE-DIMENSIONAL ARRAYS
A list of items can be given one variable name using only one subscript
and such a variable is called a single - subscripted variable or onedimensional
array.
In C, single-subscripted variable xi can be expressed as
x[0], x[1], x[2], .............. x[n-1]
The subscript begins with number 0.
That is
x[0]
is allowed. For example, if we want to represent a set of five numbers, say (35,
40, 20, 57, 19) by an array variable number, then we may declare the variable
number as follows
int number[5];
and the computer reserves five storage locations and afterwards numbers are
inserted as shown below:
35
number[0]
40
number[1]
20
number[2]
57
number[3]
19
number[4]

Declaration of Arrays
Like any other variable, arrays must be declared before they are used. The general form of
array declaration is
type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float,
or char and the size indicates the maximum number of elements that can be stored inside
the array. For example,
float height[50];
int group[10];
The C language treats character strings simply as array of characters. The size in a
character string represents the maximum number of characters that the string can hold. For
instance,
char name[10];
declares the name as a character array (string) variable that can hold a maximum of 10
characters. Suppose we read the following string constant into the string variable name.
WELL DONE

Initialization of Arrays:
We can initialize the elements of arrays in the same way as the ordinaryvariables when they
are declared. The general form of initialization of arrays is:

26

static type array-name[size] = {list of values};


The values in the list are separated by commas. For example, the statement
static int number[3] = {0, 0, 0};
will declare the variable number as an array of size 3 and will assign zero to each element. If
the number of values in the list is less than the number of elements, then only that many
elements will be initialized. The remaining
elements will be set to zero automatically. For instance,
static float total[5] = {0.0, 15.75, -10};
#include<stdio.h>
#include<conio.h>
main()
{
int arr[6]={67,78,89,65,69,75},i;
//clrscr();
for(i=0;i<6;i++)
printf("%3d",arr[i]);
return 0;
}
/* A program is to calculate the sum of a array */
main()
{
int arr[6],i,sum=0;
clrscr();
printf("enter the elements into an array :");
for(i=0;i<6;i++)
scanf("%d",&arr[i]);
for(i=0;i<6;i++)
sum=sum+arr[i];
printf("\n total marks = %d ",sum);
getch();
}

TWO - DIMENSIONAL ARRAYS:


The data in a table can be considered as two-dimenstional array.
Two-dimensional arrays are declared as follows:
type array_name [row_size][column_size];
Two dimensional arrays are stored in memory as shown below: As with the singledimensional arrays, each dimension of the array is indexed from zero to its maximum size
minus one; the first index selects the row and
the second index selects the column within that row.

INITIALIZING TWO DIMENSIONAL ARRAYS


Like the one-dimensional arrays, two-dimensional arrays may beinitialized by following their
declaration with a
list of initial values enclosed in braces. For example: static int table[2][3] = {0, 0, 0, 1, 1,
1};
initializes the elements of the first row to zero and the secnd row to one. The initialization is
done row by row.
The above statement can be equivalently written as static int table[2][3] = {{0, 0, 0}, {1,
1, 1}};
by surrounding the elements of each row by braces. We can also initialize a two-dimensional
array in the form of
a matrix asshown as:

27

static int table[2][3] = {


{0, 0, 0},
{1, 1, 1}
};
/* Example for a Double Dimensions */
main()
{
int a[2][2],i,j,b[2][2],c[2][2];
clrscr();
printf("enter the elements into an array a:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("enter the elements into an array b:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<2;i++)
for(j=0;j<2;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nthe elements of an array c :\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%5d",c[i][j]);
printf("\n");
}
getch();
}

/* A program is to find addition of a matrices */


#include <stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int m,n,p,q,i,j;
clrscr();
printf("ENTER THE SIZE OF THE MATRIX A: ");
scanf("%d%d",&m,&n);
printf("ENTER THE SIZE OF THE MATRIX B: ");
scanf("%d%d",&p,&q);
if(m==p && n==q)
{
printf("ENTER THE VALUES INTO MATRIX A: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("ENTER THE VALUES INTO MATRIX B: ");
for(i=0;i<p;i++)

28

for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
printf("THE MATRIX addition is: \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else
printf("ADDITION NOT POSSIBLE");
getch();
}
/* A program is to find multiplication of matrices */
#include<stdio.h>
void main()
{
int a[r1][c1],b[r2][c2],c[r][c],i,j;
printf("\nenter r1,c1,r2,c2");
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
printf("enter the 1 ele");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
printf("\nenter the 2 ele");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",b[i][j]);
if(c1==r2)
{
printf("\nmultiplication is possible");
}
else
printf("multiplication is not possible");
c[i][j]=0;
for(i=0;i<r2;i++)
{
for(j=0;j<c1;j++)
{
for(k=0;k<c1;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
printf("%d",c[i][j]);
getch();
}

MULTI - DIMENSIONAL ARRAYS


29

C allows arrays of three or more dimensions. The general form of a multi-dimensional array
is type
array_name[s1][s2][s3] .......... [sm];
where si is the size of the ith dimension. Some example are:
int survery[3][5][12];
and
float table[5][4][5][3];
survey is a three-dimensional array declared to contain 180 integer type elements. Similarly
table is a four-dimensional array containing 300 elements of floating-point type. The array
survey may represent a survey
data of rainfall during the last three years from January to December in five cities.

HANDLING OF CHARACTER STRINGS


INTRODUCTION:
A string is an array of characters. Any group of characters defined between double
quotation marks is a constant string.
Example:
Man is obviously made to think.
For example,
printf(\Well Done!\ );
will output the string
Well Done!
while the statement
printf(WellDone!);
will output the string
WellDone!

Character strings often used to build meaningful and readable programs.


The common operations performed on character strings are:
Reading and Writing strings
Combining strings together.
Copying one string to another.
Comparing strings for equality.
Extracting a portion of a string.

DECLARING AND INITIALIZING STRING VARIABLES:


A string variable is any valid C variable name and is always declared as an array. The
general form of declaration of a string variable is
char string_name[size];
The size determines the number of characters in the string-name.
Some examples are:
char city[10];
char name[30];
Reading a Line of Text:
In many text processing applications, we need to read in an entire time of text from the
terminal. It is not possible to use scanf function to read a line containing more than one
word. This is because the scanf terminates reading
as soon as a space is encountered in input. We have learned to read a single character from
the terminal, using the

30

function getchar.
WRITING STRINGS TO SCREEN
We have used the printf function with %s format to print strings to the screen. The format
%s can be used to display an array of characters that is terminated by the null character. For
example, the statement
printf(%s, name);
can be used to display the entire contents of the array name.
The following features of the %s specifications.
1. When the field width is less than the length of the string, the entire string is printed.
2. The integer value on the right side of the decimal point specifies the number of characters
to be printed.
3. When the number of characters to be printed is specified as zero, nothing is printed.
4. The minus sign in the specification causes the string to be printed left-justified.
printf(%*.*s\n, w, d, string);

OPERATIONS ON CHARACTERS
C allows us to manipulate characters the same way we do with numbers. Whenever a
character constant or character variable is used in an expression, it is automatically
converted into an integer value by the system. The integer value depends on the local
character set of the system. To write a character in its integer representation, we may write
it as an integer. For example, if the machine uses the ASCII representation, then,
x = a;
printf(%d\n, x);
will display the number 97 on the screen.
In ASCII character set, the decimal numbers 65 to 90 represent upper-case alphabets (A-Z)
and 97 to 122 represent lower-case alphabets (a-z).
The values from 91 to 96 are excluded using an if statement in the for loop.
The C labrary supports a function that converts a string of digits into their integer values.
The function takes the form
x = atoi(string);

STRING - HANDLING FUNCTIONS


The C library supports a large number of string-handling functions that
can be used to carry out many of the string manipulations. Following are the
most commonly used string-handling functions.
Function
Action
strcat()
concatenates two strings
strcmp()
compares two strings
strcpy()
copies one string over another
strlen()
finds the length of a string.
strrev()
reversing the string.
strlwr()
converts upper case to lower case.
strupr()
converts lower case to upper case.

strcat() Function
The strcat function joins two strings together. It takes the following

31

form:
strcat(string1, string2);
C permits nesting of strcat functions. For example, the statement
strcat (strcat (string1, string2), string3);
#include<string.h>
#include<stdio.h>
void main()
{
char destination[25]="This is ",c[8] = " Turbo ", turbo[5]=" C++";
clrscr();
strcat(destination,c);
strcat(destination,turbo);
printf("%s\n",destination);
getch();
}

strcmp() Function
The strcmp function compares two strings identified b the arguments and has a value 0 if
they are equal. If they are not, it has the numeric difference between the first non matching
characters in the strings. It takes the form:
strcmp(string1, string2);
string1 and string2 may be string variables or string constants. Examples are:
strcmp(Rom, Ram);
#include<string.h>
#include<stdio.h>
void main()
{
char buf1[10],buf2[10];
int ptr;
clrscr();
printf("enter two strings :");
scanf("%s %s",buf1,buf2);
ptr=strcmp(buf2, buf1);
printf("diff =%d\n",ptr);
if(ptr==0)
printf("two strings are equal\n ");
else if (ptr > 0)
printf("\nbuffer 2 is greater than buffer 1\n");
else
printf("buffer 2 is less than buffer 1\n");
getch();
}

strcopy() Function
The strcpy function works almost like a string-assignment operator. It takes the form
strcpy(string1, string2);
For example, the statement
strcpy(city, DELHI);

32

#include<stdio.h>
#include<string.h>
void main()
{
char string[10];
char str1[10]="abcdefghi";
clrscr();

strcpy(string,str1);
printf("%s\n", string);
getch();

strlen() Function
This function counts and returns the number of characters in a string.
n = strlen(string);
where n is an integer variable which receives the value of the length of the string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int l=0;
char string[25]="Borland International";
clrscr();
l=strlen(string);
printf("%d\n",l);
getch();
}
/* A program is to find the reverse of a string */
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char forward[10] = "string";
clrscr();
printf("Before strrev(): %s\n",forward);
strrev(forward);
printf("After strrev(): %s\n",forward);
getch();
}
/* A program is to convert upper case to lower case */
#include <stdio.h>
#include <string.h>
void main()
{

33

char string[25] = "BorlandInternational";


clrscr();
printf("string prior to strlwr: %s\n", string);
strlwr(string);
printf("string after strlwr: %s\n", string);
getch();
}

/* A program is to find the converts lower case to upper case */


#include <stdio.h>
#include <string.h>
void main()
{
char string[25] = "BorlandInternational";
clrscr();
printf("string prior to strupr: %s\n", string);
strupr(string);
printf("string after strupr: %s\n", string);
getch();
}

USER-DEFINED FUNCTIONS
INTRODUCTION:
A function is a self-contained block of statements that perform a task of some kind. A
function performs same type of task every time. Every C program can be thought of as a
collection of these functions. Generally we use three primary functions, namely, main,
printf, and scanf. We shall consider in detail how a function is designed, how two or more
functions are put together and how they communicate with one another. C functions can be
classified into two categories, namely,
1. Library functions and
2. user-defined functions.
Note: main is an example of user-defined function.
printf and scanf belongs to the category of library functions.
The main difference between these two categories is that library functions are not required
to be written by us whereas a user-defined function has to be developed by the user at the
time of writing a program.

NEED FOR LIBRARY& USER-DEFINED FUNCTIONS


Every program must have a main function to indicate where the program has to begin its
execution. If only main function is used, then the program may become too big and
complex, and it will be difficult to debug,
test and maintain it. So we use independent functions in main function. These functions are
much easier to understand, debug, and test.

34

The main function calls familier functions from C library. The function of specific type can be
prepared by the user called user-defined function. The user-defined functions are kept
after the main function ends. Whenever
these user-defined functions are required, the main function calls the required function. Then
the main function can be called as calling function and the user-defined function is called
called function.
A user-defined function is a seft-contained block of code that performs a particular task.
Once a function has been designed and packed, it can be treated as a block box that
takes some data from the main program and returns a value. The inner details of operation
are invisible to the rest of the program. All that the program knows about a function is: What
goes in and what comes out. Every C program can be designed using a collection of these
block boxes.

THE FORMAT OF USER-DEFINED FUNCTION:


All user-defined functions have the form given below:
function-name(argument list)
argument declaration;
{
local variable declarations;
executable statement1;
executable statement1;
------------------------return(expression);
}
All parts are not essential. Some may be absent. For example, the argument list and its
associated argument declarartion parts are optional. The declaration of local variable is
required only when any local variable are
used in the function. A function can have any number of executable statements.
The return statement is the mechanism for returning a value to the calling function. This is
an optional statement. Its absence indicates that no value is being returned to the calling
function.

CATEGORY OF USER-DEFINED FUNCTIONS


A user-defined function, depending on whether arguments are present
or not and whether a value is returned or not, may belongs to one of the
following categories.
Category 1: Functions with no arguments and no return values
Category 2: Functions with arguments and no return values
Category 3: Functions with arguments and return values.
Variable Declaration:
Varible declaration can be two types: They are:
Local And Global
Where a program's fingers can't reach.
From the computer's point of view, a C program is nothing more than a collection of
functions and declarations. Functions can be thought of as sealed capsules of program code
which float on a background of white space, and are connected together by means of
function calls. White space is the name given to the white of an imaginary piece of paper

35

upon which a program is written, in other words the spaces and new line characters which
are invisible to the eye. The global white space is only the gaps between functions, not the
gaps inside functions.
Global Variables:
Global variables are declared in the white space between functions. If every function is a
ship floating in this sea of white space, then global variables (data storage areas which also
float in this sea) can enter any ship and also enter anything inside any ship (See the
diagram). Global variables are available everywhere;. they are created when a program is
started and are not destroyed until a program is stopped.
Local Variables:
Local variables are more interesting. They can not enter just any region of the program
because they are trapped inside blocks. To use the ship analogy: if it is imagined that on
board every ship (which means inside every function) there is a large swimming pool with
many toy ships floating inside, then local variables will work anywhere in the swimming pool
(inside any of the toys ships, but can not get out of the large ship into the wide beyond. The
swimming pool is just like a smaller sea, but one which is restricted to being inside a
particular function.

1. NO ARGUMENTS AND NO RETURN VALUES


When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data
from the called function. In effect, there is
no data transfer between the calling function and the called function.
main()
{
printf(I love India.\n);
neha();
shilpa();
}
neha()
{
printf(Do you love India?\n);
} shilpa()
{
printf(I too love India.\n);
}
The output of the above program when executed would be as under:
o/p: I love India.
Do you love India?
I too love India.
2. ARGUMENTS BUT NO RETURNVALUES:
When a function has an argument, it receives data from the terminal and it is
transferred to the called function. If there is no calculations in the calling function, then it
does not return any value to the main function.

36

The mechanism used to convey information to the user-defined function is the


arugument or parameter. The
arugment for parameter may be a variable or
character constant. These arguments must be in parentheses.
Example:
main()
{
char ch;
clrscr();
printf("Enter a character\n");
scanf("%c", &ch);
clrscr();
printline(ch);
printf("\nWelcome to Neha Computers\n");
printline(ch);
printf("\n");
getch();
}
printline(char x)
{
int i;
for(i=1; i <= 25; i++)
printf("%c", x);
}
The output will be under the control of the user, if ch is * then the the output will be as
under:
In this program ch can be called as argument or paramenter. It receives argument from the
terminal. This argument can be called actual argument. This argument is transferred to
the user-defined function. In the
User defined function we find another argument called formal argument which must be
declared in the parenthesis. If you use actual argument in the user defined function, then
the compiler would still treat them as different variable since they are in different function.
In this user-defined function nothing is to be returned. Therefore, it is not necessary to use
the return statement. Immediately after the closing brace the control is returned to the
calling function.

3. ARGUMENTS WITH RETURN VALUES


When a function has arguments, it receives data from the terminal and they are transferred
to the called function. The calculations are done in the calling function, then it returns the to
the main function for further processing
or displaying.
Example:
/* Sending and receiving values between calling and called functions */
main()
{
int a, b, c, sum;
clrscr();
printf("Enter any three numbers\n");
scanf("%d %d %d", &a, &b, &c);
sum = calsum(a, b, c);
printf("Sum = %d\n", sum);
getch();

37

}
calsum(x, y, z)
int x, y, z;
{
int d;
d = x + y + z;
return(d);
}

RETURN VALUES AND THEIR TYPES:


A function may or may not send back any value to the calling function. If it does, it is done
through the return statement. While it is possible to pass to the called function any number
of values, the called function can only return one value per call, at the most.
The return statement can take one of the following forms:
Return ;
or
return (expression);
Example:
main()
{
float a, b, mul();
a = 10.0;
b = 3.0;
clrscr();
printf("%f\n", mul(a, b));
getch();
}
float mul(x, y)
float x, y;
{
return(x*y);
}
In this program it returns a floating value.
FUNTIONS RETURNING NOTHING
We have seen earlier that in many occations, functions do not return any
value. They perform only some printing. This is made possible by making
use of the keyword void.
Example:
main()
{
void gospel();
printf(I want to be your friend\n);
}
void gospel()
{
Printf(What a nice person you are!\n);
}

38

NESTING OF FUNCTIONS
C permits nesting functions freely. main can call function1,
which calls
function2,
which calls function3, ..............
There is in principle no limit as to how deeplly functions can be nested.

RECURSION
When a called function in turn calls another function a processng of chaining occurs.
Recursion is a special case of this process, where a function calls itself. A very simple
example of recursion is the evaluation of
factorials of a given number.
The factorial of a number n is expressed as a series of repetitive multiplications as shown
below:
factorial of n = n(n-1)(n-2) ....................1.
A function to evaluate factorial of n is as follows:
Factorial(n)
int n;
{
int fact;
if(n ==1)
return(1);
else
fact = n*factorial(n-1);
return(fact);
}
Let us see how the recursion works. Assume n = 3. Since the value of n is not
1, the statement
fact = n * factorial(n-1);
will be executed with n = 3. That is,
fact = 3 * factorial(2);
will be evaluated. The expression on the right-hand side includes a call to
factorial with n = 2. This call will return the following value:
2 * factorail(1)
Once again, factorial is called with n = 1. This time, the function returns 1.
The sequence of operations can be summarized as follows:
fact = 3 * factorial(2)
= 3 * 2 * factorial(1)
=3*2*1
=6
Recursion function can be effectively used to solve problems where the solution is expressed
in terms of successively applying the same solution to subsets of the problem. When we
write recursive functions, we must have an if statement somewhere to force the function to
return without the recursive call being executed.

CALL BY VALUE:
39

The changes made in the formal arguments will not reflect to atual arguments.
/* Example for Call by Value */
void main()
{
int a,b;
void swap(int,int);
clrscr();
printf(\n enter the 2 integers);
scanf(%d%d,&a,&b);
printf(\n before swapping a=%d \t b=%d,a,b);
swap(a,b);
printf(\n after swapping a=%d \t =%d ,a,b);
getch();
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}

CALL BY REFERENCE:
The Changes made in the formal arguments will reflect to actual parameters(arguments).
/* Example for call by reference */
#include<stdio.h>
#include<conio.h>
void swap(int*,int*);
main()
{
int i,j;
printf("enter the values of i and j :");
scanf("%d %d",&i,&j);
swap(&i,&j);
printf("values of i and j after function call: i=%d j=%d",i,j);
return 0;
getch();
}
void swap(int* p,int *q)
{
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
printf("values of p and q in function : p=%d q=%d",p,q);
}

40

Swapping program in c using function using Temporary variable


#include<stdio.h>
void swap(int *,int *);
int main(){
int a,b;
printf("Enter any two integers: ");
scanf("%d%d",&a,&b);
printf("Before swapping: a = %d, b=%d",a,b);
swap(&a,&b);

printf("\nAfter swapping: a = %d, b=%d",a,b);


return 0;

void swap(int *a,int *b){


int *temp;
temp = a;
*a=*b;
a=a*b;
*b=*temp;
}

// a=a^b;
// b=a^b;
// a=a^b;
//or a=(a*b)/(b=a); or a=a+b (b=a);
// a^=b^=a^=b;
////a=a*b;b=a/b; a=a/b;or

Sample output:
Enter any two integers: 3 6
Before swapping: a = 3, b=6
After swapping: a = 6, b=6

STORAGE CLASSES
In C programs we declare only type of variable but we dont define its storage class.
Because variable has certain default storage class. The computer stores the variable either
in RAM or CPU register.
A variable in C can have any one of the four storage classes:
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
We shall briefly discuss the scope and longevity of each of the above class of variables. The
scope of variable determines over what parts of the program a variable is actually available
for use (active). Longevity refers to
the period during which a variable retains a given value during execution of a program
(alive). So longevity has a direct effect on the utility of a given variable.
The variables may also be broadly categorized, depending on the place of their declaraton,
as internal (local) or external (global). Internal variables are those which are declared
within a particular function, while external variables are declared outside of any function.
1. AUTOMATIC VARIABLES:

41

Automatic variables are declared inside a function in which they are to be utilized. They are
created when a function is called and destroyed automatically when the function is exited,
hence the name automatic.
Automatic variables are therefore private (or local) to the function in which they are
declared. Becaue of this property, automatic variables are also referred to as local or internal
variables. These variables are stored in RAM.
These variables must be initialized otherwise an unpredictable value is stored in the variable
which is often called a garbage value. It works within the blockuntil the control remains
within the block in which the variable is defined.
For instance, the storage class of the variable number in the example below is automatic.
main()
{
int number;
--------------------}
we may also use the keywords auto to declare automatic variables explicitly.
main()
{
auto int number;
------------------------------------}
One important feature of automatic variables is that their value cannot be changed
accidentally by what happens in some other function in the program.
/* A program is to initialize the automatic variable */
void main()
{
auto int i=1;
clrscr();
{
{
{
printf("\n %d",i);
}
printf("\n %d",i);
}
printf("\n %d",i);
}
getch();
}
void main()
{
int i=1;
clrscr();
{
int i=2;
{
int i=3;
printf("\n %d",i);
}
printf("\n %d",i);
}
printf("\n %d",i);

42

getch();
}
2. 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 the local variables,
global variables can be accessed by any function
in the program. External variables are declared outside the main function. If global
variable is not initialized
then it takes 0 value as default.
In case a local variable and a global variable have the same name, the local variable will
have precedence over the global one in the function where
it is declared.
Extern int y;
/* A program is to initialize the extern variable */
int i;
void increment();
void decrement();
void main()
{
clrscr();
printf("\ni=%d",i);
increment();
increment();
decrement();
decrement();
getch();
}
void increment()
{
i=i+1;
printf("\n on incrementing i= %d",i);
}
void decrement()
{
i=i-1;
printf("\n on decrementing i= %d",i);
}
int x=21;
void main()
{
extern int y;
clrscr();
printf("\n %d %d",x,y);
getch();
}
int y=31;
*/
int x=10;

43

void main()
{
int x=20;
clrscr();
printf("\n%d ",x);
display();
getch();
}
display()
{
printf("\n %d",x);
}

3. STATIC VARIABLES:
As the name suggests, the value of static variables persists 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 place
of declaration.
The scope of internal static variables are extend upto the end of the function in which they
are defined.
internal static variables are similar to auto variables, except that they retain existence
(alive) throughout the remainder of the program.
/* A program is to initialize the static variable */
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
increment()
{
auto int i=1;
printf("%d\n",i);
i=i+1;
} */
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
increment()

44

{
static int i=1;
printf("%d\n",i);
i=i+1;
}
4.REGISTER VARIABLES:
We can tell the compiler that a variable should be kept in one of the machines registers,
instead of keeping in the memory (where normal variables are stored).
Since a register access is much faster than a memory access, keeping the frequenlty
accessed variables (e.g., loop control variables) in the register will lead to faster
execution of programs.
register int count;
/* Program is to initialize the register variable */
void main()
{
register int i;
clrscr();
for(i=0;i<=10;i++)
printf("\n%d",i);
getch();
}

STRUCTURES
We have seen that arrays can be used to represent a group of data items that belongs to
the same type, such as int or float. However, if we want to represent a collection of data
items of different types using a single name, then
we cannot use an array. Fortunately, C supports a constructed data types known as
structure, which is a method of packing data of different types.
The general format of a structure definition is as follows:
struct tag_name
{
data-type member1;
data_type member2;
..........................
...........................
}
Consider a book database consisting of book name, author, number of pages, and price. We
can define a structure to hold this information as follows:
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four fields, namely title,
author, pages, and price. These fields are called structure elements or members. Each
member may belongs to a different type of data.

45

book is the name of the strurcture and is called the structure tag. In defining a structure
you may note the following syntax:
1. The template is terminated with a semicolon.
2. While the entire declaration is considered as a statement, each member is declared
independently for its name and type in a separate inside the template.
3.The tag name such as book can be used.
#include<stdio.h>
#include<conio.h>
struct book
{
char name[10];
float total;
int m1,m2,m3;
};
float sum(struct book b)
{
b.total=(float)b.m1+b.m2+b.m3;
return b.total;
}
void main()
{
struct book b1;
float result;
clrscr();
printf("enter name:");
scanf("%s",b1.name);
printf("enter m1:");
scanf("%d",&b1.m1);
printf("enter m2:");
scanf("%d",&b1.m2);
printf("enter m3:");
scanf("%d",&b1.m3);
result=sum(b1);
printf("\n %s \n %d \n %d \n %d \n %f ",b1.name,b1.m1,b1.m2,b1.m3,result);
getch();

GIVING VALUES TO MEMBERS


We can assign values to the members of a structure in a number of ways. The members
themselves are not variables. They should be linked to the structructure variables in order to
make them meaingful members. The link
between a member and a variable is established using the member operator . which is also
known as dot operator or period operator.
For example:
book1.price
is the variable representing the price of book1 and can be treated like any other ordinary
varible. Here is how we would assign values to the members of book1;
strcpy(book1.title, BASIC);
strcpy(book1.author, Balaguru swamy);
book1.pages = 250;
book1.price = 28.50;
We can also use scanf to give the values through the keyboard.
scanf(%s, book1.title);
scanf(%d, &book1.pages);

46

STRUCTURE INITIALIZATION:
a structrue variable can be initialized. However, a structure must be declared as static if it is
to be initialized inside a function.
main()
{
static struct st_record
{
int weight;
float height;
}
student = {60, 180.75};
------------------------}
This assigns the value 60 to student.weight and 180.75 to student.height.
The following statements initialize two structure variables
main()
{
struct st_record
{
int weight;
float height;
};
static struct st_record student1 = {60, 180.75};
static struct st_record student2 = {53, 170.60};
........
........
}
Another method is to initialize a structure variable outside the function as shown below:
struct st_record
/* No static word */
{
int weight;
float height;
} student1 = {60, 180.75};
main()
{
static struct st_record student2 = {53, 170.60};
.........
.........
}

COMPARISION OF STRUCTURE VARIABLES:


Two variables of the same structure type can be compared the same way as ordinary
variables. If person1 and person2 belong to the same structure, then the following
operations are valid:
Operation
person1 = person2

47

Meaning
Assign person2 to person1

person1 == person2
person2
equal,

Compare all members of person1 and

and return 1 if they are equal, 0 otherwise.


person1 != person2
Return 1 if all the members are not
0 otherwise.

ARRAYS OF STRUCTURES
We use structures to describe the format of a member of related variables. For example,
in analysing the marks obtained by a class of students, we may use a template to describe
student name and marks obtained in various subjects and then declare all the students as
structure variables. In such cases, we may declare an array of structures, each element of
the array representing a structure variable.
For example:

struct class student[100];

defines an array called student, that consists of 100 elements. Each element is defined to be
of the type struct class.
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
static struct marks student[3] =
{{45, 68, 81}, {75, 53, 69}, {57, 36, 71}};
This declares the student as an array of three elements student[0], student[1],
and student[2] and initializes their members as follows:
student [0].subject1 = 45;
student [0].subject2 = 68;
..........
..........
Student [2].subject3 = 71;\
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[10];
float price;
int pages;
};
struct book b[5];
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("\n enter name : ");
scanf("%s",b[i].name);

48

printf("\n enter price : ");


scanf("%f",&b[i].price);
printf("\n enter pages :" );
scanf("%d",&b[i].pages);

}
for(i=0;i<5;i++)
printf("\n %s \n %f \n %d ",b[i].name,b[i].price,b[i].pages);
getch();
}
linkfloat()
{
float a=0,*b;
b=&a;
// cause emulator to be linked
a=*b;
// suppress the warning - variable not used
}

ARRAYS WITH IN STRUCTURES:


C permits the use of arrays as structure members. We have already used arrays of
characters inside a structure. Similarly, we can use single or multi-dimentional arrays of type
int or float.
struct marks
{
int number;
float subject[3];
}student[2];
Here, the member subject contains three elements, subject[0], subject[1], and subject[2].
These elements can be accessed using approprite subscripts.
For example, the name
student[1].subject[2];
would refer to the marks obtained in the third subject by the second student.

STRUCTURES WITHIN STRUCTURES


Structures within a structrue means nesting of structures. Nesting of structures is permitted
in C. Let us consider the following strucutrue defined to store information about the salary of
employees.
struct salary
{
char name[20];
char dept[10];
int basic;
int da;
int ca;
}employee;
This structure defnes name, department, basic pay and three kinds ofallowances. We can
group all the items related to allowance together anddeclare them under a sub structure as
shown below:
struct salary
{
char name[20];

49

char dept[10];
struct
{
int da;
int hra;
int ca;
}
allowance;
}
employee;
The salary structure contians a member named allowance which itself is a structure with
three members. The members contained in the inner structurenamely da, hra, and ca can be
referred to as
employee.allowance.da
employee.allowace.hra
employee.allowance.ca.
An innner-most member in a nested structure can be accessed by chaining all the concerned
structure variables with the member using dot operator.
/* Example for Structure with in structure */
#include<stdio.h>
#include<conio.h>
void main()
{
struct address
{
char phone[10];
char city[25];
int pin;
};
struct emp
{
char name[20];
struct address a;
};
struct emp e={"sunilkumar","531046","nagpur",1238};
clrscr();
printf("\n name = %s phone=%s ",e.name,e.a.phone);
printf("\n city = %s pin=%d ",e.a.city,e.a.pin);
getch();
}

Structure Pointer:
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{

50

char name[10];
float price;
int pages;
};
struct book b1={"basic",130.00,550};
struct book *b2;
clrscr();
b2=&b1;
printf("\n name1 = %s",b1.name);
printf("\n price1 = %f",b1.price);
printf("\n pages1 = %d",b1.pages);
printf("\n name2 = %s",b2->name);
printf("\n price2 = %f",b2->price);
printf("\n pages2 = %d",b2->pages);
getch();
}

UNIONS:
Unions are a concept borrowed from sturectures and therefore follow the same syntax as
structures. However, there is major distinction between them in terms of storage. In
structures, each member has its own storage
location, whereas all the members of a union use the same location. This implies that,
although a union may contain many members of different types, it can handle only one
member at a time. Like structures, a union can be
declared using the keyword union as follows:
union item
{
int m;
float x;
char c;
} code;
This declares a variable code of type union item. The union contains three members, each
with a different data type. However, we can use only one of them at a time. This is due to
fact that only one location is allocated
for a union variable, irrespective of its size. storage of 4 bytes
1000
1001
1002
1003
--c -------------- m -------------------------------------------------------------------- x ------------------In declaration the member x require 4 bytes which is the largest among the members. All
the three variables share the same address.To access a union member, we can use the same
syntax that we use for
structure members. That is,
code.m
code.x
code.c
are all valid member variable. In union any one of its members at a time can be used.
#include<stdio.h>
#include<conio.h>
void main()
{
union book

51

{
char name[10];
float price;
int pages;
};
union book b1,b2;
clrscr();
printf("\n enter name :");
scanf("%s",b1.name);
printf("\n address of name1 = %u",&b1.name);
printf("\n name1 = %s",b1.name);
printf("\n enter price :");
scanf("%f",&b1.price);
printf("\n address of price1 = %u",&b1.price);
printf("\n price1 = %f",b1.price);
printf("\n enter pages :");
scanf("%d",&b1.pages);
printf("\n address of pages1 = %u",&b1.pages);
printf("\n pages1 = %d",b1.pages);
printf("\n\n enter name :");
scanf("%s",b2.name);
printf("\n address of name2 = %u",&b2.name);
printf("\n name2 = %s",b2.name);
printf("\n enter price :");
scanf("%f",&b2.price);
printf("\n address of price2 = %u",&b2.price);
printf("\n price2 = %f",b2.price);
printf("\n enter pages :");
scanf("%d",&b2.pages);
printf("\n address of pages2 = %u",&b2.pages);
printf("\n pages2 = %d",b2.pages);
getch();
}

Enum
It gives you an opportunity to invent your own data type and define what values the
variable of this datatype can take.
The format of the enum definition is similar to that of a structure.
Example:
Enum mar_status{
Single,married,divorced,widowed;
};
Enum mar_status person1,person2;
The first part declares the data type and specifies its possible values. These values are
called enumerators
#include<stdio.h>
#include<conio.h>

52

#include<string.h>
void main()
{
enum emp_dept
{
assembly, manufacturing, accounts, stores
};
struct employee
{
char name[15];
int age;
float bs;
enum emp_dept dept;
};
struct employee e1;
clrscr();
strcpy(e1.name,"poonam bajwa");
e1.age=22;
e1.bs=18765.00;
e1.dept=manufacturing;
printf("\n
printf("\n
printf("\n
printf("\n
}

name = %s ",e1.name);
age= %d ",e1.age);
basic salary = %f",e1.bs);
department = %d",e1.dept);

getch();

POINTERS
INTRODUCTION:
Pointers are another important feature of C language. Although they may appear a little
confusing for beginner, but they are a powerful tool and handy to use once they are
mastered. There are a number of reasons for using pointers.
1. A pointer enables us to access a variable that is defined outside thefunction.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of data storage space in
memory.
The real power of C lies in the proper use of pointers.

UNDERSTANDING POINTERS:
We know that computers use their memory for storing the instructions of a program, as well
as the values of a the variables that are associated with it. The computers memory is a
sequential collection of storage cells. Each cell, commonly known as a byte, has a
number called address associated with it. Typically, the addresses are numbered
consecutively, starting from zero. The last address depends on the memory size. A
computer system
having 1KB memory will have its last address as (1024-1) 1023. Whenever we declare a
variable, the system allocates, somewhere in the memory, an appropriate location to hold
the value of the variable. Since,

53

every byte has a unique address number, this location will have its own address number.
This statement instructs the system to find a location for the integer variable quantity and
puts the value 179 in that location. Let us assume that the system has chosen the address
location 786 for quantity. Since memory addresses are simply numbers, they can be
assigned to some variables which can be stored in memory, like any other variable. Such
variables that hold memory addresses are called pointers. A pointer is, nothing but a
variable in which address of another variable is stored.

ACCESSING THE ADDRESS OF A VARIABLE


The address of a variable can be known by using the operator &. For example, the
statement
p = &qty;
would assign the address 786 to the variable p. The & operator can be remembered as
address of.
The pointer operator availble in C is * , called value at address. It gives the value
stored at a particular address. The value at address operator is also called indirection
operator.

DECLARING AND INITIALIZING POINTERS


The declaration of a pointer variable takes the following form:
data type *pt_name;
This tells the compiler three things about the variable pt_name.
1. The asteris (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
int *p;
declares the variable p as a pointer variable that points to an integer data type. Remember
that the type int refers the data type of the variable being pointed to by p and not the type
of the value of the pointer.
Once a pointer variable has been declared, it can be made to point to a variable using an
assignment statement such as
p = &qty;
which causes p to point to qty. That is, p now contains the address of qty. This is known as
pointer initialization. Before a pointer is initialized, it should not be used.
corresponding type of data.
Assigning an absolute address to a pointer variable is prohibited. For example
p = 5368;
A pointer variable can be initialized in its declaration itself. For
example,
int x, *p = &x;
is perfectly valid.
It declares x as an integer variable and p as a pointer variable and then initializes p to the
address of x. Note carefully that this is an initialization of p, not *p.

ACCESSING A VARIABLE THROUGH ITS POINTER


54

Once a pointer has been assigned the address of a variable, you can access the value of the
variable using the pointer.
int qty, *p, n;
qty = 179;
p = &qty;
n = *p
The first line declares qty and n as integer variables and p as a pointer variable pointing to
an integer. The second line assign the value 179 to qty and the third line assigns the
address of qty to the pointer variable p. The
fourth line contains the indirection operator *. When the operator * is placed before a pointer
variable in an expression, the pointer returns the value of the variable of which the pointer
value is the address. In this case, *p returns the value of the variable qty, because p is the
address of qty. The * can be remembered as value at address. Thus the value of n would
be 179.
The two statements
p = &qty;
n = *p;
are equivalent to
n = *&qty;
which is turn is equivalent to
n = qty;

POINTER EXPRESSIONS
Like other variables, pointer variables can be used in expressions. For example, if p1 and p2
are properly declared and initialized pointers, then the following statements are valid.
y = (*p1) + (*p2);
sum = sum + (*p1);

POINTER INCREMENTS AND SCALE FACTOR


The pointer can be incremented like p1 = p1 + 1; and so on. Remember, however, an
expression like p1++;
will cause the pointer p1 to point to the next value of its type. For example, if p1 is an
integer pointer with an initial value, say 2800, then after the operation p1 = p1 + 1, the
value of p1 will be 2802, and not 2801. That is, when we
increment a pointer, its value is increased by the length of the data type that it points to.
This length is called the scale factor.
For an IBM PC, the length of various data (scale factor) types are as
follows:
characters
1 byte
integer
2 bytes
floats
4 bytes
long integers
4 bytes
doubles
8 bytes
We can find the number of bytes needed for a variable by making use of the sizeof operator.
For example, if x is a variable, the sizeof(x) returns the number of bytes needed for the
variable.

POINTERS AND ARRAYS


55

When an array is declared, the complier allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations. The base
address is the location of the first
element (index 0) of the array. The compiler also defines the array name as a constant
pointer to the first element. Suppose we declare an array x as follows:
static int x[5] = {25, 43, 38, 92, 62};
Suppose the base address of x is 1000 and assuming that each integer requires two bytes,
the five elements will be stored as follows:
Elements
Value
Address

x[0]
25
1000

x[1]
43
1002

x[2]
38
1004

x[3]
92
1006

x[4]
62
1008

The name x is defined as a constant pointer pointing to the first element, x[0] and therefore
the value of x is 1000, the location where x[0] is stored. That is,
x = &x[0] = 1000
If we declare p as an integer pointer, then we can make the pointer p to point to the array x
by the following assignment:
p = x;
This is equivalent to p = &x[0];
we can access every value of x using p++ to move from one element to another. The
relationship between p and x is shown below:
p
= &x[0] (= 1000)
p+1 = &x[1] (= 1002)
p+2 = &x[2] (= 1004)
p+3 = &x[3] (= 1006)
p+4 = &x[4] (= 1008)

POINTERS AND CHARACTER STRINGS


One important use of pointers is in handling of a table of strings.
Consider the following array of strings:
char name[3][25];
This says that the name is a table containing three names, each with a maximum length of
25 characters (including null character). The total storage requirements for the name table
are 75 bytes.
We know that rarely the individual strings will be of equal lengths. Therefore, instead of
making each row a fixed number of characters, we can make it a pointer to a string of
varying length. For example,
static char *name[3] = {
NewZealand,
Australia,
India
};
declares name to be an array of three pointers to characters, each pointer pointing to a
particular name as shown below:
name[0] -------> New Zeeland
name[1] -------> Australia
name[2] --------> India

56

The character arrays with the rows of varying length are called ragged arrays and are
better handled by pointers.

POINTERS AND FUNCTIONS


When we pass addresses to a funtion, the parameters receiving the addresses should be
pointers. The process of calling a function using pointers to pass the addresses of variable is
known as call by reference.
The function which is called by reference can change the value of the variable used in the
call. Consider the following code:
main()
{
int x;
x = 20;
change(&x);
printf(%d\n, x);
}c
hange(p)
int *p;
{
p* = *p + 10;
}
When the function change() is called, the address of the variable x, not its value, is passed
into the function change(). Inside change(), the variable p is declared as a pointer and
therefore p is the address of the variable x.
The statement
*p = *p +10;
means add 10 to the value stored at the address p. Since p represents the address of x, the
value of x is changed from 20 to 30. Therefore, the output of the program will be 30, not 20.

POINTERS AND STRUCTURES


We know that the name of an array stands for the address of its zeroth element. The same
thing is true of the names of arrays of structure variables.
Suppose product is an array variable of struct type. The name product represents the
address of its zeroth element. Consider the following
declaration:
struct inventory
{
char name[30];
int number;
float prince;
} product[2], *ptr;
This statement declares product as an array of two elements, each of the type struct
inventory and ptr as a pointer to data objects of the type struct Inventory.
The assignment
ptr = product;
would assign the address of the zeroth element of product to ptr. That is, the pointer ptr will
now point to product[0]. Its members can be accessed using the following notation.
ptr -> name
ptr -> number

57

ptr -> price


The symbol -> is called the arrow operator and is made up of a minus sign and a greater
than sign. Note that ptr -> is simply another way of writing product[0].
When the pointer ptr is incremented by one, it is made to point to the next record, i.e.,
product[1]. The following for statement will print the values of members of all the elements
of product array.
for(ptr = product; ptr < product+2; ptr++)
printf(%s %d %f\n, ptr -> name, ptr -> number, ptr -> price);
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[10];
float price;
int pages;
};
struct book b1={"basic",130.00,550};
struct book *b2;
clrscr();
b2=&b1;
printf("\n name1 = %s",b1.name);
printf("\n price1 = %f",b1.price);
printf("\n pages1 = %d",b1.pages);
printf("\n name2 = %s",b2->name);
printf("\n price2 = %f",b2->price);
printf("\n pages2 = %d",b2->pages);
getch();
}

Preprocessor
Before a C program is compiled,it is passed through the another proram is called Pre
processor
The Pre processor works on the source code and creates Expanded Source Code, which is
stored in
*.I.
This expanded source code is sent to compiler for compilation.
Pre processor directives begins with a # symbol.
Some of the pre processor directives are:
1. Macro Expansion.
2. File Inclusion.

MACRO
Macro is a Pre-processor directive which is used to declare symbolic constants.
Example: # define UPPER 25
The above statement is called Micro Defination(Macro), UPPER is called MACRO
TEMPLATE
And 25 is called corresponding macro expansion.
It is customary to use capital letters for micro template.
Macro definition never to be terminated by a semicolon.
Macro can have arguments.
Example:

58

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


Main()
{
Float r1=6.25,a;
a=AREA(r1);
printf(Area is =%f,a);
}

MACROS Vs Function
In a micro call preprocessor replaces the micro template with its micro expansion.
In a function call, the control is passed to function along with certain arguments, after
performing the talks in that fun a useful value is returned back.
Macros make the program run faster but increase the program size.
Function make the program smaller and compact but takes time to passing the control
between functions.

File Inclusion
This directive causes one file to be included in another file. There are two ways to write
# include<filename.h>
# include filename.h

The Build Process


C Source code
(PRI.C)
Pre proceesor

Expanded Source
code(PRI.I)

compiler

Assembly code
Assembler

Re locatable Object
code

Object code for library

Linker

Executable code

FILE MANAGEMENT IN C:
INTRODUCTION:
A file is a place on the disk where a group of related data is stored. C supports a number of
functions that have the ability to perform basic file operations, which include:
1. naming a file,

59

2.
3.
4.
5.

opening a file
reading data from a file
writing data to a file
closing a file

The C library uses the following High Level I/O functions:


Function name
Operation
fopen()
Creates a new file for use
Opens an existing file for use
fclose()
Closes a file which has been opend for use
getc()
Reads a character from a file
putc()
Writes a set of data values to a file
fprintf()
Writes a set of values from a file
fscanf()
Reads a set of data values from a file
getw()
Reads an integer to a file
putw()
Writes an integer to a file
fseek()
Sets the position to a desired point in the file
ftell()
Gives the current position in the file
(in terms of bytes from the start)
rewind()
Sets the position to the beginning of the file.
Opening a file:
Before we can write information to a file on a disk or read it, we must open the file. Opening
a file establishes a link between the program and the operating system. We provide the
operating system with the name of the file
and whether we plan to read or write to it. The link between our program and the operating
system is a structure called FILE which has been defined in the header file stdio.h
(standing for standard input/output header file). When we request the operating system to
open a file, we attach a pointer to the Structure
FILE. That is why, we make the following declaration before opening the file,
FILE *fp;
Each file we open will have its own FILE structure. The FILE structure contains information
about the file being used, such as its current size, its location in memory etc. More
importantly it contains a character pointer which
points to the character that is about to get read. Now let us understand the following
statements,
FILE *fp;
fp = fopen(pr1.c, r);
fp is a pointer variable, which contains address of the structure FILE ,which has been
defined in the header file stdio.h.
fopen() will open a file pr1.c in read mode, which tells the C compiler that we would be
reading the contents of the file. Note that r is a string and not a character; hence the
double quotes and not single quotes. In
fact, fopen() performs three important tasks when you open the file in r mode:
1. Firstly it searches on the disk the file to be opened.
2. If the file is present, it loads the file from the disk into memory.
If the file is absent, fopen() returns a NULL. NULL is a macro defind in stdio.h which
indicates that you failed to open the file.
3.It sets up a character pointer which points to the first character ofthe memory where the
file has been loaded.

60

Reading from a file:


Once the file has been opened for reading using fopen(), as we have seen the files contents
are brought into memory and a pointer points to the very first character. The read the files
contents from memory there exists a
function called fgetc(). This has been used in our sample program through,
c = fgetc(fp);
fgetc() reads the character from current pointer position, advances the pointer position so
that it now points to the next character, and returns the character that is read, which we
collected in the variable c.
We have the used the function fgetc() within an indefinite while loop. There has to be a way
to break out of this while. There should be a break whenever we reach the end of the file.
End of the file is signified by a special
character, whose ascii value is 26. This character is inserted beyond the last character in the
file, when it is created. This character can also be generated from the keyboard by typing
ctrl Z. When reading from the file, when fgetc() encounters this special character, instead of
returning the character that it has read, it returns the macro EOF. The EOF macro has been
defind in the file stdio.h.

Trouble in opening a file:


There is a possibility that when we try to open a file using the function fopen(), the file may
not be opened. While opening the file in r mode, this may happen because the file being
opened may not be present on the disk at all. And you obviously cannot read a file which
doesnt exist. Similarly, while opening the file for writing fopen() may fail due to a number of
reasons, like, disk space may be insufficient to open a new file, or the disk may be write
protected and so on.
#include stdio.h
main()
{
FILE *fp;
fp = fopen(pri.c, r);
if(fp == NULL)
{
puts(Cannot open file);
exit();
}
}
Closing the file:
When we have finished reading from the file, we need to close it. This is done using the
function fclose() through the statement,
fclose(fp);

File opening modes:


A file can be opened in one of several modes. The tasks performed byfopen() when a file is
opened in each of these modes are also mentioned. r Searces file. If the file exists, loads it
into memory and sets up a pointer which points to the first character in it. If the file doest
exist it returns

61

NULL.
Operations possible - reading from the file.
w Searches file. If the file exits, its contents are overwritten. If the file doesnt exist, a new
file is created. Returns NULL, if unable to open
file.
Operations possible - writing to a file.
a Searches file. If the file exists, loads it into memory and sets up a pointerwhich points to
the first character in it. If the file doesnt exist, a new file
is created. Returns NULL, if uanble to open file.
Operations possible - appending new contents at the end of file.
r+ Serches file. If the file exists, loads it into memory and sets up a pointer which points to
the first character in it If file doesnt exist it returns
NULL.
Operations possible - reading existing contents, writing new contents, modifying
existing contents of the file.
w+ Serches file. If the file exists, its contents are destroyed. If the file doesnt exists a new
file is created. Returns NULL, if uanble to open
file.
Operation possible - writing new contents, reading them back and modifying
existing contents of the file.
a+ Searches file. If the file exists, loads it into memory and sets up a pointer which points
to the first character in it. If the file doent exists, a new file is created. Returns NULL, if
unable to open file.
Operations possible - reading existing contents, appending new contents to end
of file. Cannot modify existing contents.

DEFINING AND OPENING A FILE


If we want to store data in a file in the secondary memory, we must specify certain things
about the file, to the operating system. They include:
1. Filename
2. Data structure
3. Purpose
Filename is a string of characters that make up a valid filename for the operating system. It
may contain two parts, a primary name and an optional period with the extension.
Examples:
input.data
store
prog.c
student.c
text.out
Data structure of a file is defined as FILE in the library of standard I/O function definitions.
Therefore, all files should be declared as type FILE before they are used. FILE is a defined
data type.

62

When we open a file, we must specify what we want to do with the file.For example, we may
write data to the file or read the already existing data. Following is the general format for
declaring and opening a file:
FILE *fp;
fp = fopen(filename, mode);
The first statement declares the variable fp as a pointer to the data type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type pointer
fp. This pointer which contains all the information about the file and it links between the
system and the program. The second statement also specifies the purpose of opening this
file. The mode does this job. Mode can be one of the following:
r
opens the file for readng only
w
open the file for writing only
a
open the file for appending (or adding) data to it.
Note that both the filename and mode are specified as strings. They should be enclosed in
double quotaton marks.
Consider the following statements:
FILE *pt1, *pt2;
pt1 = fopen(data, r);
pt2 = fopen(results, w);
The file data is opend for reading and results is opend for writing. In case, the results file
already exits, its contents are deleted and the file is opened as a new file. If data file does
not exit, an error will occur.
CLOSING A FILE
A file must be closed as soon as all operations on it have been completed. This ensures that
all outstanding information associated with thefile is flushed out from the buffers and all
links to the file are broken. Look at the following segment of a program to close the opend
files.
...........
FILE *pt1, *pt2;
pt1 = fopen(input, w);
pt2 = fopen(ouput, r);
........
fclose(pt1);
fclose(pt2);
.........
This program opens two files and closes them after all operations onthem are completed.
Once a file is closed, its file pointer can be reused for another file.

INPUT/OUTPUT OPERATIONS ON FILES


Once a file is opend, reading out of or writing to it is accomplished using the standard I/O
routines.
To creat a new file:
In this program we can write strings to a file using the function fputs().
#include <stdio.h>
main()
{
FILE *fp;
char s[80];
fp = fopen(neha.txt, w);
if(fp == NULL)

63

{
puts(Cannot open file);
exit();
}
printf(\nEnter a few lines of text:\n);
printf(Press Enter key at the end of the line\n);
printf(Press two times Enter key to close the file\n);
while(strlen(gets(s)) > 0)
{
fputs(s, fp);
fputs(\n, fp);
}f
close(fp);
}
Note that each string is terminated by hitting enter. To terminate the execution of the
program, hit enter at the beginning of a line. This creates a string of zero length, which the
program recognises as the signal to close the
file and exit.
Explanation: We have set up a character array to receive the string; the fputs() function
then writes the contents of the array to the disk. Since fputs() does not automatically add a
newline character to the end of the string, we must do this explicitly to make it easier to
read the string back from the file.
To copy the contents of a file into another file:
In this program we can copy the contents of one text file into another text file, character by
character.
#include <stdio.h>
main()
{
FILE *fs, *ft;
char c;
fs = fopen(pr1.c, r);
if(fs == NULL)
{
puts(Cannot open source file);
exit();
}f
t = fopen(pr2.c, w);
if(ft == NULL)
{
puts(Cannot open targer file);
fclose(fs);
exit();
}
while(1)
{
c = fgetc(fs);
if(c == EOF);
break;
else
fputc(c, ft);
}f
close(fs);

64

fclose(ft);
}
Explanation: In the above program fgetc() function is used to reads characters from a file
and fputc() function is used to write characters to a file. The ft and fs are pointers for
target file and source file. The fclose() is used
to close the file. It clears any characters remaining in the buffers.
To read strings from the file and displays them on screen:
#include <stdio.h>
main()
{
FILE *fp;
char s[80];
clrscr();
fp = fopen(suhail.txt, r);
if(fp == NULL)
{
puts(Cannot open file);
exit();
}
while(fgets(s, 79, fp) != NULL)
printf(%s, s);
fclose(fp);
getch();
}
Explanation:
The function fgets() takes three arguments. The first is the address where the string is
stored, and the second is the maximum length of the string. This argument prevents fgets()
from reading in too long a string and overflowing the array. This third argument, as usual, is
the pointer to the structure FILE. When all the lines from the file have been read, we
attempt to read one more line, in which case fgets() returns a NULL.

Formatted Disk I/O Functions:


For formatted reading and writing of characters, strings, integers, floats, there exists two
functions, fscanf() and fprintf().
#include <stdio.h>
main()
{
FILE *fp;
char another = Y;
char name[40];
int age;
float bs;
clrscr();
fp = fopen(employee.dat, w);
if(fp == NULL)
{
puts(Cannot open file);
exit();
}
while(another == Y)
{
printf(\nEnter name, age and basic salary\n);
scanf(%s %d %f, name, &age, &bs);

65

fprintf(fp, %s %d %f\n, name, age, bs);


printf(Another employee(Y/N));
fflush(stdin);
another = getche();
}f
close(fp);
getch();
}
Explanation:
The key to this program is the function fprintf(), which writes the values of three variables to
the file. This function is similar to printf(), except that a FILE pointer is included as the first
argument. As in printf(), we can format the
data in a variety of ways, by using fprintf(). In fact all the format conventions of printf()
function work with fprintf() as well. We have used fflush() function. The reason is to get rid of
a pecularity of scanf(). After supplying data for one employee, we would hit the enter key.
What scanf() does is it assign name, age and salary to appropriate variables and keeps the
enter key unread in the keyboard buffer. So when its time to supply Y or N for the question
Another employee (Y/N) getche() will read the enter key from the buffer thinking that user
has entered the enter key. To avoid this problem we use the function fflush(). It is designed
to remove or flush out any
data remaining in the buffer. The argument to fflush() must be the buffer which we want to
flush out. Here we use stdin, which means buffer related with standard input device the
keyboard.
To read formatted file and displays them on screen:
#include <stdio.h>
main()
{
FILE *fp;
char name[40];
int age;
float bs;
clrscr();
fp = fopen(employee.dat, r);
if(fp == NULL)
{
puts(Cannot open file);
exit();
}
while(fscanf(fp, %s %d %f, name, &age, &bs) != EOF)
printf(\n%s %d %f, name, age, bs);
fclose(fp);
getch();
}
Explanation:
This program uses the fscanf() function to read the data from the disk. This function is
similar to scanf(), except that, as with fprintf(), a pointer to FILE is included as the first
argument.
To write records to a file using structure:
#include <stdio.h>
main()
{
FILE *fp;
char another = Y;

66

struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
fp = fopen(employee.dat, w);
if(fp == NULL)
{
puts(Cannot open file);
exit();
}
while(another == Y)
{
printf(\nEnter name, age and basic salary:);
scanf(%s %d %f, e.name, &e.age, &e.bs);
fprintf(fp, %s %d %.2f\n, e.name, e.age, e.bs);
printf(Add another record (Y/N));
fflush(stdin);
another = getche();
}f
close(fp);
getch();
}
Note: In this format numbers would occupy more number of bytes, since the
file is opend in text mode.
To read records from a file using structure:
#include <stdio.h>
main()
{
FILE *fp;
struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
fp = fopen(employee.dat, r);
if(fp == NULL)
{
puts(Cannot open file);
exits();
}
while(fscanf(fp, %s %d %f, e.name, &e.age, &e.bs) != EOF)
printf(\n%s %d %.2f, e.name, e.age, e.bs);
fclose(fp);
getch();
}
The getw and putw Functions:

67

The getw and putw are integer-oriented functions. They are similar to the getc and putc
functions and are used to read and write integer values. These functions would be useful
when we deal with only integer data. The
general forms of getw and putw are:
getw(fp);
putw(integer, fp);
Example:
A file named data contains a series of integer numbers. Code a program to read these
numbers and then write all odd numbers to a file to be called odd and all even numbers to a
file to be called even. In this programwe use three files simultaneously and therefore we
need to define three file pointers f1, f2 and f3.
#include <stdio.h>
main()
{
FILE *f1, *f2, *f3;
int number, i;
printf(Contents of data file\n\n);
f1 = fopen(data, w);
for(i = 1; i <= 30; i++)
{
scanf(%d, &number);
if(number == -1)
break;
putw(number, f1);
}f
close(f1);
f1 = fopen(data, r);
f2 = fopen(odd, w);
f3 = fopen(even, w);
while( (number = getw(f1) ) != EOF)
{
if(number %2 == 0)
putw(number, f3);
else
putw(number, f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen(odd, r);
f3 = fopen(even, r);
printf(\n\nContents of odd file\n\n);
while( (number = getw(f2) ) != EOF)
printf(%4d, number);
printf(\n\nContents of even file\n\n);
while( (number = getw(f3) != EOF)
printf(%4d, number);
fclose(f2);
fclose(f3);
}
ERROR HANDLING DURING I/O OPERATIONS

68

It is possible that an error may occur during I/O operations on a file.


Typical error situations include:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file is opened for
another type of operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.
RANDOM ACCESS TO FILES
We have discussed file functions that are useful for reading and writing data sequentially.
There are occations, 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 functions
fseek, ftell, and rewind available in the I/O library.
ftell takes a file pointer and returns a number of type long, that corresponds to the current
position. This function is useful in saving thecurrent position of a file, which can be used
later in the program. It takes the following form:
n = ftell(fp);
n would give the relative offset (in bytes) of the current position. This means
that n bytes have already been read (or written). 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 0 to n because the file position has been set to the start of the file by rewind.
Rememer, the first byte in the file is numbered as 0, second as 1, and so on. This function
helps us in reading a file more than once, without
having to close and open the file. Remember that whenever a file is opened for reading or
writing, a rewind is done implicity. fseek function is used to move the file position to a
desired location
within the file. It takes the following form:
fseek(file ptr, offset, position);
file ptr is a pointer to the file concerned, offset is a number or variable of type long, and
position is an integer number. The offset specifies the number of positions (bytes) to be
moved from the location specified by position. The position can take one of the following
three values:
Value
0
1
2

69

Meaning
Beginning of file
Current position
End of file

Você também pode gostar