Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
191 views

C-Note (C Programming)

The document discusses an introduction to C programming for the BCA Second Semester program at Tribhuvan University Mechi Multiple Campus. It provides a brief history of C and outlines some key characteristics including portability, efficiency, support for structured programming, and flexibility. It also describes the basic structure of C programs including documentation, linking, definitions, declarations, the main function, and subprograms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views

C-Note (C Programming)

The document discusses an introduction to C programming for the BCA Second Semester program at Tribhuvan University Mechi Multiple Campus. It provides a brief history of C and outlines some key characteristics including portability, efficiency, support for structured programming, and flexibility. It also describes the basic structure of C programs including documentation, linking, definitions, declarations, the main function, and subprograms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

Tribhuvan University

Mechi Multiple Campus


BCA Programme

C Programming

BCA Second Semester

ar :
ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr ot
N

BCA
INTRODUCTION TO C

1. History of C
An ancestor of C is BCPL – Basic Combined Programming Language. Ken Thompson, a Bell
Laboratory scientist, developed a version of BCPL, which he called ‘B’. Dennis Ritchie, another
computer scientist, developed a version called ‘C’ in early 1970s that is modified and improved
BCPL. Ritchie originally wrote the language for programming under UNIX operating system. Later
Bell Laboratories rewrote UNIX entirely in C.

In C, I/O support is provided in the form of library of the object code that can be linked with the
user’s program. In the 1970s and 1980s, many organizations wrote and implemented C
compilers, which differed from one another in their requirements and libraries. One type of
machine might even have several different compilers. To establish uniformity and facilitate
portability, in 1989 ANSI (American National Standards Institute) approved standards for the
language as well as the required libraries. For e.g., ANSI specifies the standard I/O library,
including stdio.h.

2. Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its
popularity as a programming language. We will be studying many of these aspects throughout the

ar :
course.

ch by
ya
 Portability
. A ed
One of the reasons of C’s popularity is its portability. We can easily transform a program
written in C from one computer to another with few or no changes and compile with
Pd ar

appropriate compilers.
a ep

 Faster and efficient


hn pr

C is desirable because it is faster and more efficient than comparable programs in most other
high level languages. For e.g., a program to increment a variable from 0 to 15000 takes about
is e

50 seconds in BASIC while it takes 1 second in C.


Kr Not

 Supports structured programming


It is well suited for structured programming, that means, the problem might be solved in terms
of function modules or blocks. The modular structure makes program debugging, testing and
maintenance easier.

 Extendibility
Another property is extendibility. C is basically a collection of functions that are supported by
C library. We can continuously add our own functions to C library.

 Flexible
C is a flexible language. It permits us to write any complex programs with the help of its rich
set of in-built functions and operators. In addition, it permits the use of low-level language.
Hence it is also called “middle-level language” and therefore it is well suited for both system
software and business package.

3. Basic structure of C programs


C is a group of building blocks called functions, which is subroutine that may include one or more
statements designed to perform a specific task.

Documentation section consists set of comment lines giving the name of program, author, and
other details to be used later by programmer. The compiler ignores any comment so they do not
add to the file size during the time of execution. Comment lines which starts with // for single line
comment OR /*….*/ for multiple line comment.

Link section provides instruction to compiler to link functions from system library.
Definition section defines all symbolic constants.

Global declaration section declares all variables used in executable part globally.

Main function section is a must section and one program contains only one main. Main function
section starts with opening brace ’{’ and ends with closing brace ’}’. It consists declaration and
execution section. Declaration part declares all variables used in executable part. There must be
at least one statement in executable part. Each statement ends with semicolon except for
function definitions, control statements and loops.

Subprogram section contains all user-defined functions that are called in main() function.

Documentation section
Link section
Definition section
Global declaration section
Main() function section
{
Declaration part
Execution part
}
Subprogram section

ar :
Function 1

ch by
ya
Function 2 . A ed
Every C program consists of one or more modules called functions. One- of the functions must be
called main () .The program will always begin by executing the main() function, which may access
Pd ar

other functions. Any other function definitions must be defined separately, either ahead of or after
a ep

main ().
hn pr

The main () function can be located somewhere in the program so that the computer can
determine where to start the execution. This function can be allocated anywhere in the program
is e

but the general practice is to place it as the first function for better readability
Kr Not

Any function in C program consists of valid C statements and is linked together through function
calls. A function is analogous to the subroutine or a procedure in other higher-level languages.
Every function in a program has a unique name and is designed to perform a specific task. Each
function is defined by of a block of statements, which are enclosed within a par and is treated as
one single unit.

Every instruction in C program is written as a separate statement. These statements must appear
in the same order in which we wish them to be executed; unless logic of the problem demands a
deliberate jump or transfer of control to a statement, which is out of sequence.

Rules for statements:


 Generally all C statements are entered in small cases letters.
 Any C statement always ends with a semicolon (;).
 C has no specific rules about the position at which different parts of a statement are to be
written.

Example:-
#include <stdio.h> //header files
#include <conio.h>
void main() //main function
{
clrscr(); // library functiion to Clear the screen
printf(“This is first lecture in C programming”);// library function that prints the given string
getch();
}
4. Steps to execution
Source Preprocessed Object Executable
code source code code code
Editor Preprocessor Compiler Linker

External items

Editor: It is a specialized word processor to create and edit source code and data. Source
code is a program typed into the computer. You write a computer program with words and
symbols that are understandable to human beings. This is the editing part of the development
cycle. You type the program directly into a window on the screen and save the resulting text
as a separate file. This is often referred to as the source. The custom is that the text of a C
program is stored in a file with the extension .c for C programming language.

Preprocessor: It is a program that removes all comments and modifies source code
according to directives supplied in the program. A preprocessor directive begins with ‘#’ and it
is an instruction to the program. For e.g., “#include<stdio.h>” instruct the preprocessor to
replace the directive with the contents of the file stdio.h.

Compiler: You cannot directly execute the source file. To run on any computer system, the

ar :
ch by
source file must be translated into binary numbers understandable to the computer's Central

ya
Processing Unit. Compiler translates the preprocessed source code into machine language
that consists sequences of 0s and 1s. If the compiler finds any error, the compilation may
. A ed
continue in order to detect further error but computer won’t produce any compiled program. If
Pd ar

compiler doesn’t detect any error, then it produces object code, which is machine language
version of source code. This process produces an intermediate object file - with the extension
a ep

.obj. The .obj stands for Object.


hn pr

Linker: It combines all the object code of a program with necessary items (i.e., library files) to
is e

form an executable program. Often a program is so large that it is convenient to break it down
Kr Not

into smaller units, with each part stored in a separate file. Many compiled languages come
with library routines that can be added to your program. Theses routines are written by the
manufacturer of the compiler to perform a variety of tasks, from input/output to complicated
mathematical functions. In the case of C the standard input and output functions are
contained in a library (stdio.h) so even the most basic program will require a library function.
Moreover our program might use features like ‘printf’ that are defined elsewhere, perhaps in a
C library. After compilation of our program files, the computer must somehow link these
separate pieces to form a single executable program. This linking is done by linker. After
linking the file extension is .exe which are executable files.

Executable files: Thus the text editor produces .c source files, which go to the compiler,
which produces .obj object files, which go to the linker, which produces .exe executable file.
You can then run .exe files as you can other applications, simply by typing their names at the
DOS prompt or run using windows menu.
FUNDAMENTALS OF C

1. C character set
The C character sets are used to form words, numbers and expressions. Different categories of
character sets are – letters, digits and special characters.
Letters – upper case: A…Z
Lower case: a…z
Digits – 0…9
Special characters: ‘ “ , . : ; { } [ ] ! # $ & ^ ( ) _ - + * < > ? / \ | !
White spaces: blank, tab, newline

2. Identifiers and keywords


Identifiers
Identifiers are user defined names of variables, functions and arrays. It may be a combination of
character(letter and digits) set with the first character as letter.

Rules for identifiers:


 Legal characters are a-z, A-Z, 0-9, and _.
 Case is significant. Since C is case sensitive, the lower case letters are not equal to
uppercase.

ar :
ch by
 The first character must be a letter or _.

ya
 The blank space is not allowed but can include(_) between two identifiers.
 Identifiers can be of any length (although only the first 31 characters are guaranteed to
. A ed
be significant).
Pd ar

Here are some examples of legal identifiers:


a ep

i
count
hn pr

NumberOfAardvarks
number_of_aardvarks
is e

MAX_LENGTH
Kr Not

Keywords
Keywords are the reserved words having fixed meaning in C. They cannot be used as identifiers.
C makes use of only 32 keywords which combine with the formal syntax to the form the C
programming language. Note that all keywords are written in lower case – C uses upper and
lowercase text to mean different things. If you are not sure what to use then always use
lowercase text in writing your C programs. A keyword may not be used for any other purposes.
For example, you cannot have a variable called auto. If we try to use keyword as variable name,
then we’ll be trying to assign new meaning to the keyword, which is not allowed by the computer.

The following are reserved keywords, and may not be used as identifiers:
auto double int struct break else long switch case enum register
typedef char extern return union const float short for do if continue
signed void default goto sizeof while volatile unsigned static

3. Header files
Header file defines certain values, symbols and operations which is included in the file to obtain
access to its contents. The header file have the suffix ‘.h’. It contains only the prototype of the
function in the corresponding source file. For e.g., stdio.h contains the prototype for ‘printf’ while
the corresponding source file contains its definition. It saves time for writing and debugging the
code.
4. Constants and variables
Constants
ANSI C allows you to declare constants. Constant is an identifier that is always associated with
the same data value nad is taken in its absolute terms. When you declare a constant it is a bit like
a variable declaration except the value cannot be changed. There are two types of constants -
literal constant and symbolic constant.

A literal constant is a value typed directly into your computer and its value must match with the
corresponding data type. A symbolic constant is represented by a name just like as the variable is
represented. Unlike a variable, however a constant is initialized. There are two ways to declare
symbolic constant:

1. The const keyword is to declare a constant, as shown below:


Syntax:
<const><datatype><identifier> = <constant value>

int const a = 1;
const int a =2;
Note:
 You can declare the const before or after the type.

ar :
 It is usual to initialize a const with a value, as it cannot get a value any other

ch by
ya
way.
. A ed
2. The preprocessor #define is another more flexible method to define constants in a
program. #define makes the preprocessor replace every occurrence of the constant. For
Pd ar

e.g., the line #define PI 3.14 appearing at the beginning of the program specifies that the
a ep

identifier PI will be replaced by the 3.14 through out the program.


hn pr

Variables
Variables are the most fundamental part of any programming language. Variable is a symbolic
is e

name which is used to store different types of data in the computer’s memory. When the user
Kr Not

gives the value to the variable, that value is stored at the same location occupied by the variable.
Variables may be of integer, character, string, or floating type.

Variable declaration and initialization


Before you can use a variable you have to declare it. As we have seen above, to do this you state
its type and then give its name. For example, int i; declares an integer variable. You can
declare any number of variables of the same type with a single statement.

To declare a variable in C, do:


<Data type>< list variables >;

For example:
int a, b, c;
float x,y,z;
char ch;
declares three integers: a, b and c, three floating variables: x, y and z and one character: ch. You
have to declare all the variables that you want to use at the start of the program.

Variables are defined in the following way:-


main()
{
short number,sum;
int bignumber,bigsum;
char letter;
}
It is also possible to initialize variables using the = operator for assignment.
For example:-
main()
{
float sum=0.0;
int bigsum=0;
char letter=`A';
}

This is the same as:-


main()
{
float sum;
int bigsum;
char letter;
sum=0.0;
bigsum=0;
letter=`A';
}
...but is more efficient.

ar :
ch by
C also allows multiple assignment statements using =, for example:

ya
a=b=c=d=3;
...which is the same as, but more efficient than:
. A ed
a=3;
Pd ar

b=3;
c=3;
a ep

d=3;
This kind of multiple assignment is only possible if all the variable types in the statement are the
hn pr

same.
is e

Furthermore, you can assign an initial value to a variable when you declare it. For example:
Kr Not

int i=1;
sets the int variable to one as soon as it's created. This is just the same as:
int i;
i=1;
but the compiler may be able to speed up the operation if you initialize the variable as part of its
declaration. Don't assume that an uninitialized variable has a sensible value stored in it. Some C
compilers store 0 in newly created numeric variables but nothing in the C language compels them
to do so.

5. Data types
The first thing we need to know is that we can create variables to store values in. A variable is
just a named area of storage that can hold a single value (numeric or character). C is very fussy
about how you create variables and what you store in them. It demands that you declare the
name of each variable that you are going to use and its type, before you actually try to do
anything with it. Hence, data type can be defined as the storage representation and machine
instruction to handle constants and variables.

There are four basic data types associated with variables:


 Primary or fundamental data type
 User defined data type
 Derived data type
 Empty data set

Primary/fundamental data type


The data type that is used without any modifier is known as primary data type. The primary data
type can be categorized as follows:
1. Integral type
a. signed integer type
i. int
ii. short int
iii. long int
b. unsigned integer type
i. unsigned int
ii. unsigned short int
iii. unsigned long int

2. Character type
a. signed char
b. unsigned char

3. Floating point type


a. float
b. double
c. long double

 int - integer: a whole number. We can think of it as a positive or negative whole number.

ar :
ch by
But, no fractional part is allowed

ya
To declare an int you use the instruction:
int variable name;
. A ed
For example:
Pd ar

int a;
declares that you want to create an int variable called a.
a ep

 float - floating point or real value, i.e., a number with a fractional part.
 double - a double-precision floating point value.
hn pr

 char - a single character.


To declare a variable of type character we use the keyword char. - A single character
is e

stored in one byte.


Kr Not

For example:
char c;
To assign, or store, a character value in a char data type is easy - a character variable is
just a symbol enclosed by single quotes. For example, if c is a char variable you can
store the letter A in it using the following C statement:
c='A'
Notice that you can only store a single character in a char variable. But, a string constant
is written between double quotes. Remember that a char variable is 'A' and not "A".

Here are the list of data types with their corresponding required memory range of value it can
take:

Data type Size (bytes) Range


int 2 -32,768 to 32,737
unsigned int 2 0 to 65,535
short int 1 -128 to +127
unsigned short int 1 0 to 255
long int 4 -2,147,483,648 to +2,147,483,647
unsigned long int 4 0 to 4,294,967,295
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
signed char 1 128 to +127
unsigned char 1 0 to 255

User defined data type


The user defined data type can be later used to declare variable. We can define our own types
using typedef and enum. As an example of a simple use, let us consider how we may define new
type ‘letter’. These new types can then be used in the same way as the pre-defined C types:
Syntax: <typedef> <datatype> <new type>;
<new type> <variable >;

typedef char letter;


letter name, address;
here, a new type ‘letter’ is created whose data type is of char. Later, this ‘letter’ is used as data
type to declare the variables name and address.

Derived data type


Different user defined data type can be created using fundamental data types which are called
derived data type. Array, structure, union and functions are derived data types.

ar :
Empty data set/ Void

ch by
ya
Void means valueless or empty special purpose type, which we will examine closely in later
sections. It is used with function where a function doesn’t return any value.
. A ed
6. Operators
Pd ar

C provides rich set of operator environment. Operators are symbols that tell the computer to
a ep

perform certain mathematical and logical manipulations. They are used to form a part of
mathematical and logical expressions. The variable/quantity on which operation is to be
hn pr

performed is called operand. The operators can be categorized as:


1. Arithmetic operators
is e

2. Relational operators
Kr Not

3. Logical operators
4. Conditional operators
5. Unary operators
6. Assignment operators
7. Special operators

Arithmetic Operators
C provides arithmetic operators found in most languages. These operators work on all data types.
Each operator require at least two operands. There are 5 different arithmetic operators- addition
(+), subtraction (-), multiplication (*), division (/) and remainder or modulus (%). The % (modulus)
operator only works with integers. Division / is for both integer and float division.

There are three modes of arithmetic operations:


 Integer arithmetic: Both operands are integer. Hence the result will also be integer.
For example, if a=11, b=4 then,
a+ b = 15 ; a-b = 7 ; a/b = 2 ; a*b = 44 ; a%b = 3

 Real arithmetic: Both operands are real.


For example, if a=1.0, b=3.0 then,
a+ b = 4.000000 ; a-b = -2.000000 ; a/b = 0.333333 ; a*b = 3.000000

 Mixed mode arithmetic: If both real and integer operands are used. The result will be real.
For example, if a=11.0, b=4 then,
a+ b = 15.0 ; a-b = 7.0 ; a/b = 2.75 ; a*b = 44 .0
Note: The answer to: x = 3 / 2 is 1 even if x is declared a float. But x=3.0/2.0 will give the
result 1.5. also note that x=3.0/2.0 is 1 if X is declared as integer.

Relational operators
Relational operators compare two quantities. The result of comparison is TRUE or FALSE. They
are used for decision-making. The operators < (less than) , > (greater than), <= (less than or
equals), >= (greater than or equals), == (equals to), != (not equal to) are relational operators. The
operators == and != are also known as equality operators.

For example: in the expression x<y, it returns ‘true’ if x is greater than y otherwise returns ‘false’.

warning: Beware of using ``='' instead of ``=='', such as writing accidentally


if ( i = j ) .....
This is a perfectly LEGAL C statement (syntactically speaking), which copies the value in "j" into
"i", and delivers this value, which will then be interpreted as TRUE if j is non-zero. This is called
assignment by value -- a key feature of C.

Assignment operators
The assignment operator us used to assign result of an expression to a variable. The assignment

ar :
ch by
operator ‘=’ assigns the value of right operand to left. For e.g., in an expression x=y, the value of

ya
y is assigned to x.
. A ed
There is also a convenient shorthand way to express computations in C. It is very common to
Pd ar

have expressions like: i = i + 3 or x = x*(y + 2)


a ep

In C (generally) in a shorthand form like this:


hn pr

expr1 <op>= expr2


which is equivalent to (but more efficient than):
is e

expr1 = expr1 <op> expr2


Kr Not

= assignment
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= remainder/modulus assignment

So we can rewrite i = i + 3 as i += 3
and x = x*(y + 2) as x *= y + 2.
NOTE: that x *= y + 2 means x = x*(y + 2) and NOT x = x*y + 2.

Logical Operators
Logical operators are usually used with conditional statements. It performs test on multiple
relations and Boolean operation. It also returns either true or false. The three basic logical
operators are: && for logical AND, || for logical OR , ! for logical NOT. The truth table for AND and
OR is as follows:

Operand1 Operand2 Operand1 && Operand2 Operand1 || Operand2


F F F F
F T F T
T F F T
T T T T
For example,
if(a>=1 && a<=6)
printf(“a lies between 1 and 6”); // prints the message if both conditions are satisfied.

Beware & and | have a different meaning for bitwise AND and bitwise OR.

Unary operators
The two operators that are used frequently are ++ and --. ++ specifies increment, the -- specifies
decrement. You can place these in front or on the back of variables. If the operator is placed in
front, it is prefix if it is placed behind, it is postfix. Prefix means, increment before any operations
are performed, postfix is increment afterwards. These are important considerations when using
these operators.

Increment ++, Decrement -- which are more efficient than their long hand equivalents, for
example:- x++ is faster than x=x+1.

For e.g., if a=5, x=a++, y=++a and z= a--, then the values of x, y, and z will be 5, 7 and 7
respectively.

Conditional operators

ar :
C includes special ternary (3 way) operator that can replace certain if-else statement. The ?:

ch by
ya
operator is called ternary operator. The general form of this operator is:
Expression1 ? expression2 : expression3
. A ed
That means if expression1 is true, then expression2 is executed else expression3 is executed.
Pd ar

For e.g., X= (a<2) ? (a+10) : (a+5);


a ep

This is equivalent to,


if (a<2)
hn pr

X= a+10;
else
is e

X= a+5;
Kr Not

Special operators
 The comma operator
C allows you to put multiple expression in the same statement, separated by a comma. It is
also used in loops. The expressions are evaluated in left-to-right order.
For eg, value = (x=5, y=10, x+y); //comma operator in multiple expression
for(m=0, n=10; m<n; m++) // comma operator in for loop

 sizeof operator
It is a compile time operator that returns the number of bytes the operand occupies. For
example, to determine the number of bytes occupied by the integer, we can use sizeof
operator as:
int x;
printf(“ Size of integer =%d”, sizeof(x));
which is equivalent to,
printf(“ Size of integer =%d”, sizeof(int));

Associativity and Order of Precedence


The precedence of an operator gives the order in which operators are applied in expressions: the
highest precedence operator is applied first, followed by the next highest, and so on. The
associativity of an operator gives the order in which expressions involving operators of the same
precedence are evaluated.
Operators on the same line have the same precedence, and are evaluated in the order given by
the associativity. To specify a different order of evaluation you can use parentheses. In fact, it is
often good practice to use parentheses to guard against making mistakes in difficult cases, or to
make your meaning clear.

It is necessary to be careful of the meaning of such expressions as a + b * c. We may want the


effect as either (a + b) * c or a + (b * c)
All operators have a priority, and high priority operators are evaluated before lower priority ones.
Operators of the same priority are evaluated from left to right, so that
a - b - c is evaluated as ( a - b ) - c
as you would expect.

Thus , a < 10 && 2 * b < c is interpreted as ,


( a < 10 ) && ( ( 2 * b ) < c )

Consider the following calculation:


a=10.0 + 2.0 * 5.0 - 6.0 / 2.0
What is the answer? If you think its 27, then you are wrong! Perhaps you got that answer by
following each instruction as if it was being typed into a calculator. A computer doesn't work like
that and it has its own set of rules when performing an arithmetic calculation. All mathematical
operations form a hierarchy that is shown below. In the above calculation the multiplication and

ar :
ch by
division parts will be evaluated first and then the addition and subtraction parts. This gives an

ya
answer of 17.
. A ed
Note: To avoid confusion use brackets. The following are two different calculations:
Pd ar

a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)


a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
a ep

The following table lists all the operators, in order of precedence, with their associativity:
hn pr

Operator Associativity
is e

-------- -------------
Kr Not

() [] ->> . left-to-right
- ++ -- ! ~ * & sizeof (type) right-to-left
* / % left-to-right
+ - left-to-right
<< >> left-to-right
< <= > >= left-to-right
== != left-to-right
& left-to-right
^ left-to-right
| left-to-right
&& left-to-right
|| left-to-right
?: right-to-left
= += -= *= /= %= &= ^= |= <<= >>= right-to-left
, left-to-right

Note: the - and * operators appear twice in the above table. The unary forms (on the second line)
have higher precedence that the binary forms.
CONTROL STATEMENTS
A program consists of a number of statements, which are usually executed in sequence. A
Statement is an instruction given to the computer to perform any kind of action such as
manipulation of data, reading/writing of data, making decision, repeating action and so on.
Statements fall into three general types;

 Assignment, where values, usually the results of calculations, are stored in variables.
 Input / Output, data is read in or printed out.
 Control, the program makes a decision about what to do next.

Programs can be much more powerful if we can control the order in which statements are run.
Control statements determine the flow of control of a program or an algorithm. The flow of control
of a program is the order in which the computer executes the statements. The sequential control
statements execute one after another. Generally, the statements are executed sequentially which
is known as normal flow of program. To over-ride the sequential flow of program statements, a
programming language uses control statements to advance and branch based on changes to
state of a program. The control statements in C can be used to write powerful programs by;

ar :
Selecting between optional sections of a program – conditional execution/selection.

ch by

ya
Repeating important sections of the program – looping.
. A ed
Selection or decision making statements:
Pd ar

With the help of selection control structure, the computer makes decision by evaluating the logical
expression. It allows our program to choose different path of execution based upon the outcome
a ep

of an expression or the state of the variable. The C supports following type of selection or
decision making statements :
hn pr


is e

If statement

Kr Not

If…else statement
 Switch statement

The segment of the code that is executed repeatedly is known as loop. The loop control
structures are:

 while loop
 do…while loop
 for loop

The if Statement
The if statement is a conditional branch statement. If the condition is true, then the statement
after condition is executed otherwise execution will skip to next statement.
Syntax: Flowchart:

if (condition/ test expression) F


statement; test

OR T
if (condition/ test expression) Statement
{
block of statements;
} Exit

For example:
#include<stdio.h>
void main()
{
int a;
printf(“Enter the value of a:”,);
scanf(“%d”, &a);

ar :
if(a>=0)

ch by
ya
printf(“The number is positive”);
}
. A ed
The if else Statement
Pd ar

The if…else statement consist of an if statement followed by statement or block of statement,


a ep

followed by else keyword which is again followed by another statement or block of statement. In
an if…else statement, the condition is evaluated first. If the condition is true, the statement in the
hn pr

immediate block is executed. If the condition is false, the statement in the else block is executed.
This is used to decide whether to do something at a special point, or to decide between two
is e

courses of action.
Kr Not

Syntax: Flowchart:

if (condition/ test expression) F


statement; test Statement
else
statement; T
Statement
OR

if (condition/ test expression) Exit


{
block of statements;
}
else
{
block of statements;
}

The following test decides whether a student has passed an exam with a pass mark of 45 :
if (result >= 45)
printf("Pass\n");
else
printf("Fail\n");
It is possible to use the if part without the else.

if (temperature < 0)
print("Frozen\n");

Each version consists of a test, (this is the bracketed statement following the if). If the test is true
then the next statement is obeyed. If it is false then the statement following the else is obeyed if
present. After this, the rest of the program continues as normal.

If we wish to have more than one statement following the if or the else, they should be grouped
together between curly brackets. Such a grouping is called a compound statement or a block.

if (result >= 45)


{ printf("Passed\n");
printf("Congratulations\n")
}
else

ar :
{ printf("Failed\n");

ch by
ya
printf("Good luck in the resits\n");
}
. A ed
Pd ar

Sometimes we wish to make a multi-way decision based on several conditions. The most general
way of doing this is by using the else if variant on the if statement. This works by cascading
a ep

several comparisons. As soon as one of these gives a true result, the following statement or block
is executed, and no further comparisons are performed. In the following example we are
hn pr

awarding grades depending on the exam result.


is e
Kr Not

if (result >= 75)


printf("Passed: Grade A\n");
else if (result >= 60)
printf("Passed: Grade B\n");
else if (result >= 45)
printf("Passed: Grade C\n");
else
printf("Failed\n");
In this example, all comparisons test a single variable called result. In other cases, each test may
involve a different variable or some combination of tests. The same pattern can be used with
more or fewer else if's, and the final one else may be left out. It is up to the programmer to devise
the correct structure for each programming problem.

The nested if Statement


Nested ifs are very common in programming. Nested if is a structure which has another if…else
body within its body of structure. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block.
Syntax: Flowchart:

if (condition 1) F
Test 1 Statement 3
{ if (condition 2)
{ statement 1; }
else T
{ statement 2; }
} Test 2 F
else
{ statement 3; }
T

Statement 1 Statement 2

Exit

ar :
ch by
ya
The switch Statement
. A ed
This is another form of the multi way decision. It checks the value of an expression to the list of
constant values. If the condition is matched, the statement/statements associated with it will be
Pd ar

executed. If the expression does not match any of he case statement, and if there is a default
a ep

statement, execution switches to default statement otherwise the switch statement ends. It is
well structured, but can only be used in certain cases where;
hn pr

 Only one variable is tested, all branches must depend on the value of that variable. The
is e

variable must be an integral type. (int, long, short or char).


Kr Not

 You cannot use ranges as an expression i.e. the expression must give as absolute value.
 Each possible value of the variable can control a single branch. A final, catch all, default
branch may optionally be used to trap all unspecified cases.

Syntax: Flowchart:

switch(expression)
Switch(expr)
{ case value1: { statement block 1; }
break;

case value2: { statement block 2; }


break; Case 1 T Statement
…………. Block 1
………….
default: { statement block; } F
}
T Statement
Case 2
Block 2

Default
Statement
Exit
/* Estimate a number as none, one, two, several, many */
void main()
{
int number;
{ switch(number) {

ar :
ch by
case 0 :

ya
printf("None\n");
. A ed
break;
case 1 :
Pd ar

printf("One\n");
a ep

break;
case 2 :
hn pr

printf("Two\n");
is e

break;
Kr Not

case 3 :
case 4 :
case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}
Each interesting case is listed with a corresponding action. The break statement prevents any
further statements from being executed by leaving the switch. Since case 3 and case 4 have no
following break, they continue on allowing the same action for several values of number.

Both if and switch constructs allow the programmer to make a selection from a number of
possible actions.

Loops
The other main type of control statement is the loop. Computers are very good at repeating
simple tasks many times; the loop is C's way of achieving this. Loops allow a statement, or block
of statements, to be repeated a certain number of times. The loop repetition continues while a
condition is true. When the condition becomes false, the loop ends and control passes to the
statement following the loop. Loops can be classified into entry-controlled loops and exit-
controlled loops. In the entry-controlled loops, the user knows the times of repetition before
entering the loop. Whereas in exit-controlled loops, the number of repetition can be known only
after the loop.

C gives you a choice of three types of loop, while, do while and for.

 The while loop keeps repeating an action until an associated test returns false. This is
useful where the programmer does not know in advance how many times the loop will be
traversed.
 The do while loops is similar, but the test occurs after the loop body is executed. This
ensures that the loop body is run at least once.
 The for loop is frequently used, usually where the loop will be traversed a fixed number of
times. It is very flexible, and novice programmers should take care not to abuse the
power it offers.

Every loop constitutes three main parts:

 Initialization: Every loop must have a starting point called initialization


ar :
Test expression: It determines how many times a loop must execute. The loop continues

ch by
ya
as long as the test expression is true.
 Update: A loop must be updated after the execution of certain statements to reach its
. A ed
final destination. We may update the loop by increment, decrement operators or by using
any other arithmetic operators.
Pd ar
a ep
hn pr
is e
Kr Not
The while Loop
The while loop repeats a statement until the test at the top proves false.

Syntax: Flowchart:

Initialization; initialization
while (test expression)
{
body of loop; test Exit
update; F
} T
Body of loop

update

/* a program to print 10 numbers using while loop */

#include<stdio.h>

ar :
void main()

ch by
ya
{
int digit=0;
. A ed
while(digit <= 10)
{
Pd ar

printf(“%d\t”, digit);
a ep

digit++;
}
hn pr

}
is e

The do while Loop


Kr Not

This is very similar to the while loops except that the test occurs at the end of the loop body. This
guarantees that the loop is executed at least once before continuing. Such a setup is frequently
used where data is to be read. The test then verifies the data, and loops back to read again if it
was unacceptable.

Syntax: Flowchart:

Initialization; initialization
do
{
Body of loop
body of loop;
update;
} update
while (test expression);
T F Exit
test

do
{ printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0)
/* a program to print 10 numbers using do…while loop */

#include<stdio.h>
void main()
{
int digit=0;
do
{ printf(“%d\t”, digit);
digit++;
}
while(digit <= 10);

The for Loop


The for loop works well where the number of iterations of the loop is known before the loop is
entered. The head of the loop consists of three parts separated by semicolons.

 The first is run before the loop is entered. This is usually the initialisation of the loop

ar :
ch by
variable.

ya
 The second is a test, the loop is exited when this returns false.

. A ed
The third is a statement to be run every time the loop body is completed. This is usually
an increment of the loop counter.
Pd ar

Syntax: Flowchart:
a ep
hn pr

for (Initialization; test expression; update) initialization


{ F
is e

body of loop;
Kr Not

} test Exit
T

Body of loop

update

/* a program to print 10 numbers using for loop */


#include<stdio.h>
void main()
{
int digit;
for(digit = 0; digit <= 10; digit++ )
printf(“%d\t”, digit);
}

The three statements at the head of a for loop usually do just one thing each, however any of
them can be left blank. A blank first or last statement will mean no initialization or running
increment. A blank comparison statement will always be treated as true. This will cause the loop
to run indefinitely unless interrupted by some other means. This might be a return or a break
statement.

It is also possible to squeeze several statements into the first or third position, separating them
with commas. This allows a loop with more than one controlling variable. The example below
illustrates the definition of such a loop, with variables hi and lo starting at 100 and 0 respectively
and converging.

for (hi = 100, lo = 0; hi >= lo; hi--, lo++)


The for loop is extremely flexible and allows many types of program behavior to be specified
simply and quickly.

The goto Statement


The goto statement transfers control anywhere in the program. Destination of goto statement is
marked by a label or the user defined label. The label is always terminated by a colon. The goto
statement is used for condition and unconditional branching from one location to another location.
Unconditional branching is an unhealthy practice of a program. The goto statement can be used
for the forward jump or backward jump in the program.

Syntax:

goto<label>; label:
……….. statement;
………. ………..

ar :
ch by
label: ……….

ya
statement; goto<label>;
. A ed
Forward jump Backward jump
Pd ar

Example:
a ep

#include<stdio.h>
void main()
hn pr

{
int a;
is e
Kr Not

top: //label name


printf(“Enter the positive value of a:”);
scanf(“%d”, &a);
if(a<0)
goto top;
else
printf(“The entered value = %d”, a)
}

The break Statement


We have already met break in the discussion of the switch statement. It is used to exit from a loop
or a switch, control passing to the first statement beyond the loop or a switch.

With loops, break can be used to force an early exit from the loop, or to implement a loop with a
test to exit in the middle of the loop body. A break within a loop should always be protected within
an if statement which provides the test to control the exit condition.

The following program calculates the sum of entered number only if the value is positive
otherwise it exits from the loop. Here the break statement causes to terminate the loop when we
enter the negative value.

#include<stdio.h>
#include<conio.h>

void main()
{
int i, sum = 0, num;
clrscr();

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


{
printf(“Enter number %d :”, i);
scanf(“%d”, &num);
if(num<0)
break;
sum+= num;
}
printf(“The sum = %d”, sum);
getch();
}

The continue Statement


This is similar to break but is encountered less frequently. It only works within loops where its
effect is to force an immediate jump to the loop control statement.

 In a while loop, jump to the test statement.

ar :

ch by
In a do while loop, jump to the test statement.

ya
 In a for loop, jump to the test, and perform the iteration.
. A ed
Like a break, continue should be protected by an if statement. You are unlikely to use it very
Pd ar

often.
a ep

The following program calculates the sum of entered number only if the value is positive. Unlike
the break statement, the continue statement does not terminate the loop when we enter the
hn pr

negative value, but it skips the following statement and continues the loop.
is e
Kr Not

#include<stdio.h>
#include<conio.h>

void main()
{
int i, sum = 0, num;
clrscr();

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


{
printf(“Enter number %d :”, i);
scanf(“%d”, &num);
if(num<0)
continue;
sum+= num;
}
printf(“The sum = %d”, sum);
getch();
}
INPUT OUTPUT STATEMENTS
The C language comprises of several library functions that carry out various commonly used operation or
calculations. For example, there are library functions that carry out standard input / output operations, functions
that perform operations on the characters, functions that operate on strings, and functions that carry out various
mathematical calculations.

Functionally similar library functions are usually grouped together as object programs in separate library files. In
order to use a library function it may be necessary to include certain specific information within the main portion of
the program. This is accomplished with the following preprocessor directive statement:

#include<Header filename>

The I/O statements can be categorized as unformatted and formatted I/O. The unformatted I/O statements do not
specify how the input and output are carried out. But the formatted I/O statements determine the formats in which
the input and output are executed. The functions such as getc(), putc(), getchar(), putchar() are considered as
unformatted I/O because they do not contain any information about the format specifiers, field width and any
escape sequences. They simply take variable as parameter. Formatted I/O generates output under the control of
a format string (its first argument) which consists of literal characters to be printed and also special character
sequences--format specifiers--which request that other arguments be fetched, formatted, and inserted into the
string.

ar :
ch by
ya
CONVERSION SPECIFICATION
. A ed
Conversion specification specifies to what notation the computer should covert a value for input or output
operations. Conversion specification is also known as format specifier. It uses conversion character ‘%’ and type
Pd ar

specifier. The type conversion specifier does what you ask of it - it convert a given bit pattern into a sequence of
characters that a human can read.
a ep
hn pr

The more frequently used format specifiers for scanf () and printf() functions are listed below:
is e

Format specifiers Meaning


Kr Not

%c data item is displayed as a single character.


%d data item is displayed as a signed decimal integer
%u data item is displayed as an unsigned decimal integer
%e data item is displayed as a floating-point value with an exponent.
%f data item is displayed as a floating-point value without an exponent
%o data item is an octal integer without a leading zero
%x data item is a hexadecimal integer without the leading 0’s
%s data item is displayed as a string

ESCAPE SEQUENCES
The escape sequences comprises of escape character backslash symbol(\) followed by a character with special
meaning. The escape sequences cause an escape form normal interpretation of a string so that the next string is
recognized as having a special meaning. The escape sequences are considered as single character rather than a
string. Here are some of the mostly used escape sequences:

\b backspace
\f formfeed
\n new line
\r carriage return
\t horizontal tab
\' single quote
\” double quote
\\ back slash
\0 null
If you include any of these in the control string then the corresponding ASCII control code is sent to the screen, or
output device, which should produce the effect listed.

SINGLE CHARACTER INPUT-- THE getchar FUNCTION


Single characters can be entered into the computer using the C library function getchar. The function does not
require any arguments, though a pair of empty parentheses must follow the word getchar.

Syntax: character variable=getchar();


Usage: char ch;
ch = getchar();

SINGLE CHARACTER OUTPUT-- THE putchar FUNCTION


Single character output can be displayed using the C library function putchar. The character being transmitted will
normally be represented as a character- type variable. It must be expressed as an argument to the function,
following the word putchar.

Syntax: putchar(character variable)


Usage: char ch;
………
Putchar(c)

ar :
ch by
ya
Following program accepts a single character from the keyboard and displays it on the VDU.
. A ed
#include<stdio.h>
#include<conio.h>
Pd ar
a ep

/* function to accept and display a character*/


void main()
hn pr

{
char ch;
is e

clrscr();
Kr Not

printf("\n Enter any character of your choice:-");


ch = getchar();
printf("\n The character u entered was ");
putchar(ch);
getch();
}

Output:
Enter any character of your choice: - p
The character u entered was p

The above program can also be written as,


#include<stdio.h>
#include<conio.h>
void main()
{ char ch;
clrscr();
printf("\n Enter any character of your choice:- ");
ch = getc(stdin);
printf("\n The character u entered was ");
putc(ch,stdout);
getch();
}
In the above program getc(stdin) is equivalent to getchar() and putc(ch,stdout) is equivalent to putchar(ch);

ar :
ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr Not
More Example of getchar() and putchar():
Following program reads a line of text in lowercase letters and displays them in the upper case.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main()
{ char t, text[80]; // to store the text up to 80 characters long
int i = 0, tag;
printf(" Enter any text below:\n");
do
{ t =getchar();
text[i]=t;
i++;
}
while(t! = '\n');
tag = i; /* to store the maximun number
of characters entered by users*/
for(i=0;i<tag;i++)
putchar ( toupper (text[i])); /* the library function toupper() is used

ar :
to convert the text to upper case */

ch by
ya
getch();
}
. A ed
Output:
Pd ar

Enter any text below:


a ep

my name is harry
MY NAME IS HARRY
hn pr

THE gets AND puts FUNCTION


is e

C provides the functions gets() and puts() for string input-output. Though these operations can be done using the
Kr Not

scanf and printf functions with %s conversion character, but the limitation is that with scanf, a string which has a
blank space within it can never be accepted. The function gets() is the solution then.

The function gets() accepts the string variable into the location where the input string is to be stored. The function
puts() accepts as a parameter, a string variable or a string constant for displayed on the standard output.

Syntax: gets(string variable);


puts(string constant/string variable);

The following program accepts a name and displays it with a message.

#include<stdio.h>
void main()
{
char name[20];
puts(“ Enter your name: ”); gets(name);
puts(“\nHello , How are you? ”);
puts(name);
}

output:
Enter your name: ram
Hello, How are you? Ram
ENTERING INPUT DATA – THE scanf FUNCTION
Input data can be entered into the computer from a standard input device by means of the
C library function scanf. This function can be used to enter any combination of numerical values, single characters
and strings.

Syntax: scanf(control string, argl, arg2, …, argn)

Where control string refers to a string containing certain required formatting information, and argl, arg2… argn are
argument list that represent individual data items. The control string comprises individual groups of characters,
with one character group for each data item. Each character group must begin with a percent sign (%). In this
case the control string specifies how strings of characters, usually typed on the keyboard, should be
converted into values and stored in the listed variables. The most obvious is that scanf has to change the values
stored in the parts of computers memory that is associated with parameters (variables). The scanf function has
to have the addresses of the variables rather than just their values. This means that simple variables have to be
passed with a proceeding &.

The arguments are written as variables or arrays, whose types match the corresponding character groups in
control strings. Each variable name must be preceded by an ampersand (&). However, array names should not
begin with an ampersand because the array name is already a pointer.

Usage: #include <stdio.h>

ar :
ch by
void main ()

ya
{
. A ed
char item [20] ;
int partno ;
Pd ar

float cost ;

a ep

scanf (“%s %d %f”, item, &partno, &cost) ;



hn pr

}
is e
Kr Not

When the program reaches the scanf statement it pauses to give the user time to type something on the
keyboard and continues only when users press <Enter>, to signal that we have finished entering the value. The
scanf processes the control string from left to right and each time it reaches a specifier it tries to interpret what
has been typed as a value. If you input multiple values then these are assumed to be separated by white space -
i.e. spaces, newline or tabs. This means you can type:
3 4 5
or
3
4
5
and it doesn't matter how many spaces are included between items.

For example:
scanf("%d %d",&i,&j);
will read in two integer values into i and j. The integer values can be typed on the same line or on different lines
as long as there is at least one white space character between them. The only exception to this rule is the %c
specifier which always reads in the next character typed no matter what it is. You can also use a width modifier
in scanf. In this case its effect is to limit the number of characters accepted to the width.

For example:
scanf("%lOd",&i)
would use at most the first ten digits typed as the new value for i.
There is one main problem with scanf function which can make it unreliable in certain cases. The reason being
is that scanf tends to ignore white spaces, i.e. the space character. If you require your input to contain spaces
this can cause a problem. Therefore for string data input the function gets() may well be more reliable as it
records spaces in the input text and treats them as an ordinary characters.
WRITING OUTPUT DATA -– THE printf FUNCTION
Output data can be written from the computer into a standard output device using the library function printf (). This
function can be used to output any combination of numerical values, single characters and strings.

Syntax: printf(control string, argl, arg2, …, argn);

Where control string refers to a string that contains formatting information, and argl, arg2 are arguments that
represent the individual output data items. The argument can be written as constants, single variable or array
names, or more complex expressions. A format specifier is used to control what format will be used by the printf()
to print the particular variable.

Usage: #include <stdio.h>


main ()
{
char item [20] ;
int partno ;
float cost ;

ar :
ch by

ya
printf (“%s %d %f”, item, partno, cost) ;
. A ed
}
Pd ar

The control string is all-important because it specifies the type of each variable in the list and how you want it
printed. The way that this works is that printf scans the string from left to right and prints on the screen, or any
a ep

suitable output device, any characters it encounters - except when it reaches a % character. The % character is a
signal that what follows it is a specification for how the next variable in the list of variables should be printed.
hn pr

printf uses this information to convert and format the value that was passed to the function by the variable and
is e

then moves on to process the rest of the control string and anymore variables it might specify.
Kr Not

For example:
printf("Hello World");
only has a control string and, as this contains no % characters it results in Hello World being displayed and
doesn't need to display any variable values.

The specifier %d means convert the next value to a signed decimal integer and so:
printf("Total = %d",total);
will print Total = and then the value passed by total as a decimal integer.

The %d isn't just a format specifier, it is a conversion specifier. It indicates the data type of the variable to be
printed and how that data type should be converted to the characters that appear on the screen. That is %d says
that the next value to be printed is a signed integer value (i.e. a value that would be stored in a standard int
variable) and this should be converted into a sequence of characters (i.e. digits) representing the value in
decimal. If by some accident the variable that you are trying to display happens to be a float or a double then
you will still see a value displayed - but it will not correspond to the actual value of the float or double.

FIELD WIDTH SPECIFIERS


Each specifier can be preceded by a modifier which determines how the value will be printed. The most general
modifier is of the form:

flag width.precision

The flag can be any of:


flag meaning
- left justify
+ always display sign
space display space if there is no sign
0 pad with leading zeros

The width specifies the number of characters used in total to display the value and precision indicates the
number of characters used after the decimal point.
n.m (n) a number specifying minimum field width
. to separate n from m
(m) significant fractional digits for a float

For example, %10.3f will display the float using ten characters with three digits after the decimal point. Notice
that the ten characters includes the decimal point, and a - sign if there is one. If the value needs more space than
the width specifies then the additional space is used - width specifies the smallest space that will be used to
display the value. The specifier %-1Od will display an int left justified in a ten character space. The specifier
%+5d will display an int using the next five character locations and will add a + or - sign to the value.

The scanf() and printf() function gives the programmer considerable power to format the printed output.

ar :
ch by
Let’s explain this by following example:

ya
. A ed
#include<stdio.h>
void main()
Pd ar

{
int rollno=12;
a ep

printf(“ The roll no is %f”, rollno);


hn pr

}
the output for this program is:
is e

The roll no is 12.000000


Kr Not

Now in above example it would be nice to suppress the extra zeros in the output, and the printf function includes a
way to do just that.

Let’s rewrite the above program using the field width specifier:
#include<stdio.h>
void main()
{
int rollno=12;
(“ The roll no is %.2f”, roll);
}

the output for this program is:


The roll no is 12.00

Thus we see that a number following the decimal point in the field width specifier controls how many characters
will be printed following the decimal point. Also the number preceding the decimal point in field width specifier
controls the width of the space to be used to contain the number when it is printed.

Following example demonstrates this:


num = 23;
printf(“ A no is %2d.”,num);

A n o i s 2 3 .
printf(“ A no is %4d.”,num);

A n o i s 2 3 .

printf(“ A no is %5d.”,num);
A n o i s 2 3 .

ar :
ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr Not
ARRAYS AND STRINGS

ARRAYS
In many of the programming situations, we may require the processing of data items that have common
characteristics. Now in such case, it would be easier if we place these data items into one single variable
called array which is capable of storing number of data, sharing common name.

The individual data items can be characters, integers, and floating-point numbers and so on. They must
all, however be of the same type and the same storage class. The individual data items in an array are
called array elements.

Each array element is referred to by specifying the array name followed by one or more subscript
enclosed in square brackets. Each subscript or index must be expressed as non – negative integer.

Thus, we represent array containing n elements as:


x[n]
where, x is array name
n is subscript. &
x[n] has its array element as x[0], x[1], x[2],…......,x[n-1].

ar :
ch by
ya
The value of each subscript can be expressed as an integer constant, integer variable or a more complex
integer expression.The number of subscript determines the dimensionality of the array.
. A ed
Pd ar

Example,
x[i] refers to an element in the one dimensional array x
a ep

y[i] [j] refers to an element in a two – dimensional array y.


hn pr

Other higher dimensional can be formed by adding additional subscripts in the same manner like, z[i] [j]
is e

[k].
Kr Not

Definition of Array
An array can be defined as a group of homogeneous elements sharing a common name.

Each array element is identified by the array name followed by its index enclosed in square bracket.
These elements are stored in consecutive memory locations.

ARRAY DECLARATION
In general terms, a one – dimensional array definition can be expressed as follows:

Syntax:- data – type variable – name [expression]

Where, data - type refers to variable type variable – name is a valid name of
array.
expression refers to the valid positive – valued integer expression and
this indicates the number of array elements.

Examples of one dimensional array are:


int x[10]; 10 – element integer array
char name[20]; 20 – element character array
float list [35]; 35 – element float array

INITIALIZING AN ARRAY:
Array can also be initialized as other variables during its declaration. This means array declarations can
include the initial values as per requirement. But the initial values must appear in the order in which they
will be assigned to the individual array elements, enclosed in braces and separated by commas.

The general form is:

data_type array_name[expression] = {val1,val2…..valn};

Where, val1 refers to the value of first array element, val2 refers to value of
second element and so on.

The appearance of the expression, which includes the number of array elements, is optional when initial
values are present.

Example of array initialization:


int num[5] = { 1,2,3,4,9,12};

Now the result of this assignment, in terms of individual array elements is as follows:
num[0] = 1

ar :
num[1] = 2

ch by
ya
num[2] = 4
num[3] = 9
. A ed
num[4] = 12
Pd ar

The array size need not be specified explicitly when initial values are included as part of array
a ep

declaration. The array size will automatically be set equal to the number of initial values included within
hn pr

the declaration.
is e

Thus the array num can be define and initialized as:


Kr Not

int num[ ] = {1,2,4,9,12};

Other examples:-
float x[4] = {10.5, 15.2, 2.0, -4.5};
or
float x[ ] = {10.5, 15.2, 2.0, -4.5};

ARRAY ELEMENTS IN MEMORY


Let’s consider following array declaration:
int y[8]; // One dimensional array

When we declare this array, the complier reserves 16 bytes of memory in the computer 16, because
each of the 8 integers occupy 2 bytes [82 = 16]

And since the array is not initialized, all eight values present in it would be garbage values. Whatever be
the initial values all the array elements would always be present in the contiguous memory locations. The
arrangement of array elements would be a shown below:

10 24 28 35 40 -2 5 -77
5001 5003 5005 5007 5009 5011 5013 5015

Let’s have little knowledge about 2 – dimensional array:


int x[10] [20]
In above example x is two – dimensional array having 10 rows and 20 columns and this will be capable
of holding 1020 = 200 elements. The two dimensional array can be represented as:

0 1st 2nd 3rd 4th 5th 6th 7th 20th


-------------------
1
----------------
. .
. .
9
-------------------

PROCESSING AN ARRAY:
C does not permit the use of single operation which involves entire arrays. Thus if a and b are two similar
arrays, assignment operations, comparison operations etc must be carried out on an element – by –
element basis. This can be achieved by using loop where each pass or iteration through the loop is used
to process one array element. Thus the no. of iterations through the loop will be equal to the no. of array
elements to be processed.

ar :
ch by
ya
a) Following program inputs the numeric array and prints the entered numbers
. A ed
#define SIZE 4
Pd ar

void main()
{
a ep

int num[SIZE}, i;
hn pr

printf(“please enter %d integers\n”, SIZE);


for(i=0;i<SIZE;i++)
is e

scanf(“%d”,&num[i]);
Kr Not

printf(“\n”);
printf(“the entered array elements are:\n”);
for(i=0;i<SIZE;i++)
{
printf(“%d”,num[i]);
printf(“\n”);
}
getch();
}

Output:
Please enter 4 integers
1
12
75
60
the entered array elements are:
1
12
75
60

b) Following program reverses the entered numbers


#define SIZE 4
void main()
{
int num[SIZE], i;
printf(“please enter %d integers\n”, SIZE);
for(i=0;i<SIZE;i++)
scanf(“%d”,&num[i]);
printf(“\n”);
printf(“the reversed array elements are:\n”);
for( I = SIZE-1; i>=0; i--)
{
printf(“%d”,num[i]);
printf(“\n”);
}
getch();
}
Output:
Please enter 4 integers
1
12

ar :
ch by
ya
75
60
. A ed
the reversed array elements are:
60
Pd ar

75
a ep

12
1
hn pr

c) Following program reads a one – dimensional character array, converts the elements to uppercase
is e
Kr Not

and displays the converted array.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char t, text[80]; //to store the text up to 80 characters long
int i=0, tag;
printf(" Enter any text below:\n");
do
{
t =getchar();
text[i]=t;
i++;
}
while(t!='\n');
tag=i; /* to store the maximun number
of characters entered by users*/
for(i=0;i<tag;i++)
putchar(toupper(text[i])); /* the library function toupper() is
used to convert the text to upper case */
getch();
}
PASSING ARRAYS TO FUNCTIONS
Before, when an array is passed to a function as an argument, only the address of the first element of the
array is passed, but not the actual values of the array elements. For example if a[10] is an array and
sort_a(a) is the function for sorting array, then we are passing the address of a[0] to the function sort.
Thus the function uses this address for manipulating the array elements.

To pass an array to a function, the array name must appear by itself with or without brackets or
subscripts, as an actual argument within the function call. The corresponding formal argument is written
in same, manner but it must be declared as array within formal argument declarations. When one-
dimensional array appears as formal argument in the function the array name is written with a pair of
empty square brackets. The size pf array need not be written within formal argument declaration.

Example:
void diagonal(int a[10][10], int m);
void main()
{ int i,j,n,a[10][10];
clrscr();
printf("enter degree of matrix n=");scanf("%d",&n);
printf("Enter matrix elements below\n");

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

ch by
ya
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
. A ed
diagonal(a,n);
Pd ar

getch();
}
a ep

void diagonal(int a[10][10], int m)


{ int i;
hn pr

float sum=0;
is e

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

sum+=a[i][i];
printf("\nSum of diagonal elements is %.2f",sum);
getch();
}
Output
enter degree of matrix n=3
Enter matrix elements below
1 2 3
1 1 1
4 5 6
Sum of diagonal elements is 8.00

MULTIDIMENSIONAL ARRAY
Multidimensional array consists of more than one subscript or pair of square brackets in their
declarations. That means a two –dimensional array will require two pair of square brackets, and a 3-
dimensional array will require three pairs of such square brackets and so on.

Thus in general a multidimensional array definition can be written as,


data_type array [exp1][exp2]…….[expn];
Where data _type is the data type of the array
array is the array name &
exp1…..expn are positive valued integers.

Examples
1) float table[20][30];
2) double record[100][20][30];
3) double record[x][y][z];

We can initialize the three – dimensional array as following :


int a[3][2[2] = {
{
{2,4},
{2,3},
},

{
{3,5},
{5,7},
},
{
{7,8},
{9, 10},
}

ar :
};

ch by
ya
In above example one-dimensional array is constructed first. Then two such one-dimensional arrays are
. A ed
placed one below another to give a 2D array containing two rows. Then three such 2D arrays are placed
Pd ar

one below another to give a 3D array containing three 2D arrays.


a ep

PROCESSING OF MULTIDIMENSIONAL ARRAYS


hn pr

Multidimensional arrays are also processed in the same manner as one dimensional arrays on the
element by element basis.Suppose we have a 2 matrices as given below:
is e
Kr Not

2 2 3 1
A & B
2 2 3 2

now to add above matrix (which is a 2D array) we need to access every element of matrix A and B and
perform addition by element by element basis and place the sum in third matrix C.

General form of matrix for above case is :

a11 a12 b11 b12 c11 c12

a21 a22 b21 b22 c21 c22

Besides these, we can also perform various arithmetic operation and comparisons of elements of
multidimensional matrices

Two Dimensional Array


The number of subscripts in an array determines its dimensionality. Thus it is possible for arrays to have
two or more dimensions. A two dimensional array is an array having 2 subscripts. It is also known as a
matrix.

Example of 2D array is:


int student[10][20]; This means a 2D array which can hold up to 20*10=200 elements.
Initializing a 2D Array
Example
int a [2] [2]= {
{11, 22 } ,
{99, 20 }
};
OR
int a [ ] [2]= { 11, 22, 99, 20 };

STRINGS
Strings are arrays of characters i.e. they are characters arranged one after another I memory.
To mark the end of string, C uses the null character’\0’. Strings in C are enclosed with double quotes

For e.g. “My name is Peter”

Strings are stored as ASCII (American Standard Codes for Information Interchange) codes of the
characters that make up the string, appended with zero (which is ASCII value for NULL)

For e.g. Alphabets Ascii value

ar :
a 97

ch by
ya
A 65
. A ed
Initializing string J
a
Pd ar

‘String initialization must have following form:


n
a ep

e.g. char month1[ ] = {‘J’, ’a’, ‘n’, ‘u’, ‘a’, ‘r’, ‘y’}; u
hn pr

a
OR r
is e

char month1[ ] = {“January”}; y


Kr Not

Indicating end of string \0


NULL character

Array Of strings
We often use lists of character strings such as names of students in a class, list of names of employees
in an organization, list of places etc. A list of names can be treated as array of strings and a two
dimension character array name[5][6] can be used to store a list of 5 names, each of length not more
than 6 characters which is shown below:
0 1 2 3 4 5
r a m \0
0
1 f a r I \0
2 s a r a d \0
3 p e t e r
4 r i t a \0

Thus in above example name [5][6] id an array of strings.

String handling functions


C library supports large number of string handing functions that can be used to carry out many of the
string manipulations .the definitions for the string handing functions are available in the header files
string.h.
Following are the most commonly used string handling functions:
Function Action
a) strcat() concatenates two strings
b) strcmp() compares two strings
c) strcpy() copies one string to another
d) strlen() finds the length of string

strcat() Function
This function concatenates two strings i.e. appends one string at the end of another. It accepts 2 strings
as parameters and stores the content second string at the end of the first. The first string should be
capable of holding the second string after concatenation.

#include<string.h>
void main()
{
char string1[20]=”Flash”;
char string2[ ]=”Light”;
strcat(string1,string2);
printf(string1);
getch();

ar :
}

ch by
ya
output: FlashLight . A ed
strcmp() function
Pd ar

It compares two strings. It is useful while writing programs for constructing and searching strings
arranged in a dictionary. This function compares the strings on character by character basis.The function
a ep

accepts two strings and returns an integer whose value is:


LESS THAN ZERO if string1< string2
hn pr

EQUAL TO ZERO if string1= string2


is e

GREATER THAN ZERO if string1>string2


Kr Not

void main()
{ char str1[10],str2[10];
int result;
scanf(“%s %s “,str1, str2);
if(result<0)
printf(“str1<str2”);
else if(result==0)
printf(“str1=str2”);
else
printf(“str1>str2”);
getch();
}
output
Hello hello
str1< str2

strcpy() Function
This function copies one string to another. It accepts two strings as parameters and copies the second
string to the first string, character by character into first one, up to the last and including the null character
of second string. Here also the size of first character array should be greater than that of second one.

void main()
{ char str1[10]= “Ram”;
char str2[ ]= “Shyam”;
printf(“before strcpy function\n”);
printf(“%s\n”,str1);
strcpy(str1,str2);
printf(“after strcpy function\n”);
printf(“%s\n”,str1);
}
Output
before strcpy function
Ram
after strcpy function
Shyam

strlen() Function
It returns an integer which denotes the length of string passed. The length of string is the number of
characters present in it, excluding the terminating null character.

void main()
{ char str[ ]= “Hello”;

ar :
printf(“Length=%d \n”,strlen(str));

ch by
ya
getch();
}
. A ed
Output
Length=5
Pd ar
a ep
hn pr
is e
Kr Not
FUNCTIONS
INTRODUCTION
A function is a self-contained program segment or the block of statements that perform some
specific, well- defined task. Every C program comprises of one or more such functions. Among
these functions one must be called main (). The execution of any program always begins by the
executing the instructions in the main () function.

In a program there may be any number of functions and their definition can appear in any order
but they should be independent of one another. We need to access the function (which is
known as calling a function) in order to carry out the intended task.

A single function can be accessed or called from different places within a program. After
execution of the intended task, the control will be returned to the point from which the function
was accessed or called.

Simple C function program:


void message()
{ printf(“\n This is the statement inside the function message”);
}

ar :
ch by
ya
void main()
{ printf(“\n This is the statement in main before a function call”);
. A ed
message();
printf(“\n This is the statement in main after a function call”);
Pd ar

}
a ep

Output: -
hn pr

This is the statement in main before function call


is e

This is the statement inside the function message


Kr Not

This is the statement in main after a function call

In above e.g., we are calling the function message ( ) (which is user defined function) from the
main ( ) function. This means the program control is passed to the function message ( ). The
task of main ( ) function is stopped for a while, and the message ( ) function starts to execute it’s
statements. After the message ( ) function completes its task the control returns back to the
main ( ) function and continues its normal job again by executing its statements at the exact
point where it left off before. Thus here main ( ) becomes a calling function and message ( )
becomes a called function.

Next Example:-
message1()
{ printf(“\n I am in message1”);
}
message2()
{ printf(“\n I am in message2”);
}
main()
{ message1();
message2();
}

Output: -
I am in message1
I am in message2
C supports the use of library functions, which are used to carry out a number of commonly
used operations or calculations. Besides this, C also allows the programmers to define their own
functions to carry out different types of individual tasks called user-defined functions.

LIBRARY FUNCTIONS

C- programming language comprise of no. of library functions that perform some specific task or
operations.

Functions may:
 Return a data item to their access point, or
 Indicate whether the function is true or false by returning 1 or 0, or
 Perform specific operations on data items but return nothing.

There are numerous library functions in C like,


1. library functions that carryout standard input/output (like read write characters, numbers,
etc).
e.g. printf( ), scanf( ), putchar(c)

ar :
2. function that carryout various mathematical calculations

ch by
ya
e.g. log(d) - function that return natural logarithm
sin(d)
. A ed
cos(d)
Pd ar

cosh(d)
sqrt( )
a ep

pow (x1, x2 ) return x1, raised to x2 power.


hn pr

3. function that operats on strings


e.g. strcmp ( strings, strings) ,
is e

tolower (c)
Kr Not

toupper(c)

There may be several other types of such functions. Library functions that are functionary
similar are usually grouped together as object programs in separate library files, which are
supplied as a part of each c compiler.

How to access a library function?


A library function is accessed by writing the function name, followed by a list of arguments that
represent information being passed to the function. The arguments must be enclosed in
parentheses and separated by comma. The arguments can be constants, variables names, or
other complex expressions. There must be parentheses even if there are no arguments.

USER DEFINED FUNCTIONS:


Those functions that are created by user, where the user has the freedom to choose the
function name, return data type and arguments are called user-defined functions.

Need for user defined functions:-


We already know that, main ( ) function is specially recognized by function in c. Every program
must have main function to indicate where the program has begin its execution. We can write
program utilizing only main function. But this may result in too complex or too large program.
Due to this program difficulty, now if program is divided into functional parts, then each part may
be independently coded and later on combined into single unit. Thus such subprograms are
known as functions.
ADVANTAGES OF FUNCTION
1) Saves time and resources
Use of function avoids the writing of same code again and again. For example if we want to
calculate the area of the rectangle in your program, we write a code for it. Again later on, if we
need to calculate the area of some other rectangle we may not want to repeat the same code or
instructions all over again. Inst4ead we may be willing to move to some section in the program
that calculates area and return back to the place from where we left off. Thus this section of
code is the function. Thus it saves time and resource.

2) Easy and efficient program writing


Functions help to keep the track of what is being done. A program can be divided into several
activities and each of these activities can be placed in a different function.

3) Faster testing or debugging


Since separate activities form separate functions, error correction becomes much easier.

4) Functions also make the program easy to understand and use.

ar :
5) They also help in easy modification and design of program.

ch by
ya
. A ed
ACCESSING/CALLING A FUNCTION
We can access or invoke or call a function by specifying function name, followed by a list of
Pd ar

arguments (also called function parameters) enclosed within the parentheses and separated by
a ep

commas.
hn pr

If we do not need to pass any arguments to functions then empty pair of parentheses must
is e

follow the function name.


Kr Not

When function call is encountered, the control is passed to the respective function.

FUNCTION ARGUMENTS OR FUNCTION PARAMETERS


A calling function can send a package of values for the called function to operate on, or to
control how the function is to operate. Each value passed in this manner is called argument or
parameter. There are two types of arguments:
a) Actual argument
b) Formal argument

a) Actual argument
These are arguments that appear in the function call in the calling function. In other
words, when a function is called, the parameter specified within the parentheses of the calling
statement is known as actual arguments or parameters. They are called so because they are
the values that are actually transmitted to the function.

b) Formal or dummy arguments


They appear in the first line of the function definition (or function declarator). There will
be one actual argument for each formal argument. Each of the actual arguments and its
corresponding formal argument should have same data type i.e. if the actual argument is integer
then its corresponding formal argument also should be an integer. The value of each actual
argument will be passed to the function and that will be assigned to or stored int the
corresponding formal argument.
FUNCTION PROTOTYPE AND DEFINITION

Function Prototype
Function prototype is also termed as function declaration. The function prototypes provides
following information:
 It provides the name of the function
 It also specifies the type of value returned by the function (this is optional and default is
integer)
 It also provides the number and type of arguments that must be supplied in the call to a
function.
 Facilitate error checking between calls to a function and the corresponding function
definition.

When we write the user -defined function ahead of the main () function, it is not necessary to
use the function prototype because the user- defined function will have been defined before the
first function access. However, many programmers prefer a “top-down “approach, in which the
main () function appears ahead of the user-defined function. Thus in such case the function call
within main () will precede the function definition. This can be confusing to the compiler, unless
the compiler is first alerted to the fact that the function being called will be defined later in the

ar :
program. Thus a function prototype is used for this purpose

ch by
ya
Syntax for function prototype:
. A ed
return_type function_name( type, type, ………,type);
Pd ar
a ep

Function definition
hn pr

The function definition is similar to the function declaration but there is no semicolon. The first
line of the function definition is known as the function declarator that is followed by the function
is e

body. The declarator and the prototype must use the same function name, number of
Kr Not

arguments, argument types and return type.

Syntax for function definition:


return_type function_name( type 1 arg1, type 2 arg 2, type 3 arg 3,... type n arg n)
{
Body of function;
}

where, return_type represents the data -type of value being returned,


function_name represents the name of function, and
type 1, type 2,…type n represent the data types of the arguments arg1, arg2, …arg n.

Function example:
#include<stdio.h>
#include<conio.h>
int rectangle(int length, int breadth); //function prototype
/* OR int rectangle( int, int); */
void main()
{ int a, l, b;
printf(“\nlength =”); scanf(“%d ”,&l);
printf(“\nbreadth =”); scanf(“%d ”,&b);
a=rectangle(l,b); // function call in which we are passing values of l and b
printf(“\narea of rectangle=%d”,a);
getch();
}
int rectangle(int length, int breadth)
{ int area;
area=length * breadth;
return (area);
}

program output:
length =2
breadth =3
area of rectangle =6

RETURN STATEMENT ( RETURNING A VALUE FROM A FUNCTION)


One of the main feature of the function is that it can return a value to the calling function. In
order for a function to return a value to the calling function, the function should have a return
statement. This statement comprises of the keyword called return, followed by the value to be
returned. This value may be an expression, variable, constant, or even another function call.
The returned expression may be enclosed within a parentheses; this is often done even though
it is not necessary.

ar :
ch by
ya
When a return statement is executed, it immediately transfers the control back to the calling
program. A function call can return only a single value each time it is called. As soon as a return
. A ed
statement is executed, the function terminates.
Pd ar

Like, in the above example, the rectangle () function takes values of length and breadth from the
a ep

main() function, calculates the area of the rectangle and returns the integer value of the
rectangle to the main () function which finally prints the value of area.
hn pr
is e

If the function does not return any value then it is not necessary to include the return statement
Kr Not

in the function.

CALL BY VALUE AND CALL BY REFERENCE

Call by value:
 We pass values of variables to the function from the calling section.
 Each argument is evaluated and its value is used locally in place of the corresponding
formal parameter.
 If a variable is passed into the function, the stored value of that variable in the calling
environment will not be changed.
 Can return only one value

Example:

void change(int a);


void main()
{
int a = 10;
printf(“Before calling function, a = %d”, a);
change(a);
printf(“After calling function, a = %d”, a);
}

void change(int a)
{ a = a + 10;
}

The output will be:


Before calling function, a =10
After calling function, a = 10

Call by reference:
 We pass the address or location number of a variable to the function
 Pointers are used
 If a variable is passed into the function, the stored value of that variable in the calling
environment will be changed.
 Can return more than one value at a time

Example:

void change(int *a);


void main()
{

ar :
int a = 10;

ch by
ya
printf(“Before calling function, a = %d”, a);
change(&a);
. A ed
printf(“After calling function, a = %d”, a);
Pd ar

}
a ep

void change(int *a)


hn pr

{
*a = *a + 10;
is e

}
Kr Not

The output will be:


Before calling function, a =10
After calling function, a = 20

RECURSIVE FUNCTIONS

A recursive function is one which calls itself. This is another complicated idea which we are
unlikely to meet frequently. We shall provide some examples to illustrate recursive functions.
Recursive functions are useful in evaluating certain types of mathematical function. We may
also encounter certain dynamic data structures such as linked lists or binary trees. Recursion is
a very useful way of creating and accessing these structures.

Here is a recursive version of the Fibonacci function.


int fib(int num)
/* Fibonacci value of a number */
{ switch(num) {
case 0:
return(0);
break;
case 1:
return(1);
break;
default: /* Including recursive calls */
return(fib(num - 1) + fib(num - 2));
break;
} }
We met another function earlier called power. Here is an alternative recursive version.

double power(double val, unsigned pow)


{ if(pow == 0) /* pow(x, 0) returns 1 */
return(1.0);
else
return(power(val, pow - 1) * val);
}

Notice that each of these definitions incorporate a test. Where an input value gives a trivial
result, it is returned directly, otherwise the function calls itself, passing a changed version of the
input values. Care must be taken to define functions which will not call themselves indefinitely,
otherwise your program will never finish.

The definition of fib is interesting, because it calls itself twice when recursion is used. Consider
the effect on program performance of such a function calculating the fibonacci function of a

ar :
moderate size number.

ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr Not

CATEGORIES OF FUNCTION

Depending on the presence or absence of arguments and whether the value is returned or not,
the function can be categorized as:
 Function without any arguments and return values
 Function with arguments and but no return values
 Function with both arguments and return values
 Function without arguments and but with return values

Function without any arguments and return values


If we do not want to return a value we must use the return type void and miss out the return
statement. Here we simply call a function without passing arguments and the called function
doesn’t have to return any values to the calling function.

#include <stdio.h> void rect_area() // function definition


void main () {
{ int l, b, area;
void rect_area(); // function declaration printf(“Enter l and b:”); scanf(“%d %d”, &l, &b);
rect_area(); // function call area = l * b;
getch(); printf(“The area of rectangle is %d”, area);
} }
Function with arguments and but no return values
This type of function has one-way communication. Here, an argument is passed from the calling
function to the called function, but there is no need of return statement in the called function.

#include <stdio.h> void rect_area(int l, int b) // function


#include<conio.h> definition
void main () {
{ int area;
void rect_area(int, int); // function declaration area = l * b;
int l, b; printf(“The area of rectangle is %d”, area);
printf(“Enter l and b:”); scanf(“%d %d”, &l, &b); }
rect_area(l, b); // function call
getch();
}

ar :
ch by
ya
Function with both arguments and return values
This type of function has two-way communication. Here, an argument is passed from the calling
. A ed
function to the called function, and there will also be return statement in the called function.
Pd ar

#include <stdio.h> int rect_area(int l, int b) // function


a ep

#include<conio.h> definition
void main () {
hn pr

{ int area;
is e

int rect_area(int, int); // function declaration area = l * b;


Kr Not

int l, b, a; return area;


printf(“Enter l and b:”); scanf(“%d %d”, &l, &b); }
a = rect_area(l, b); // function call
printf(“The area of rectangle is %d”, a);
getch();
}

Function without arguments and but with return values


This type of function also has one-way communication. Here, an argument is not passed from
the calling function to the called function, but there is need of return statement in the called
function.

#include <stdio.h> void rect_area( ) // function definition


#include<conio.h> {
void main ( ) int area;
{ printf(“Enter l and b:”);
int rect_area(void); // function declaration scanf(“%d %d”, &l, &b);
int a; area = l * b;
printf(“Enter l and b:”); scanf(“%d %d”, &l, &b); return(area);
a = rect_area( ); // function call }
printf(“The area of rectangle is %d”, a);
getch();
}
Kr Not
is e
hn pr
a ep
Pd ar
. A ed
ch by
ar :
ya
LOCAL, GLOBAL AND STATIC VARIABLES

Local variables
Local variables are those variables, which are declared inside a function in which they are to be
utilized. They are created when we call a function and destroyed automatically when the
function is exited. Thus such variables are private or local to the function in which they are
declared. The values of such variables cannot be changed by what happens inside the other
functions in the program i.e. the same named variable can be used in some other functions
without creating any confusion.

Following program illustrates this concept:

#include<stdio,h>
modify_n();

void main()
{ int n ; //local variable
n=10;
printf(“the value of n is %d \n”, n);

ar :
modify_n( );

ch by
ya
printf(“the value of n after function call is %d \n”, n);
getch(); }
. A ed
modify_n()
{
Pd ar

int n; //local variable


a ep

n = 20;
return n;
hn pr

}
is e
Kr Not

Output:
the value of n is 10
the value of n after function call is 10

In above example, we have declared a variable n in the function main () and assigned it the
value 10. The program then calls the function modify_n() which creates its own local variable n,
and assigns the value 20 to it. This assignment has no effect, however, on the variable named n
that was created in the main function.

When the control returns to the main function, the variable n- the one local to main function –
still contains the value 10. A function does not terminate its execution when calling another
function; it suspends it. Therefore the variable n local to the main function remains in existence
while the function modify_n is executing.

Global variables
Global variables are those variables which are alive and active throughout the entire program.
Such variables can be accessed and used by any function in the program and their values can
be altered. Thus the global variables help to establish a two- way communication among
different functions. In contrast to the local variables, these variables are not declared within a
specific function, instead they are declared outside of all the functions in the program.

The previous program is modified as follows using n as the global variable

int n; //global variable


modify_n();
void main()
{ n=10;
printf(“the value of n is %d \n”, n);
modify_n( );
printf(“the value of n after function call is %d \n”, n);
getch();
}

modify_n()
{
n = 20;
return n;
}

Output:
the value of n is 10
the value of n after function call is 20

ar :
Here n is declared as the global variable so both main() and modify_n() functions are able to

ch by
ya
change its content. . A ed
Here is another example to illustrate the use of global variable:
Pd ar

int length,breadth,area;
a ep

get_number();
void calc_area();
hn pr
is e

void main()
Kr Not

{
clrscr();
printf(" \nEnter length of rectangle:");
length=get_number();
printf(" \nEnter breadth of rectangle:");
breadth=get_number();
calc_area();
printf("\n The area is %d",area);
getch();
}

get_number()
{
int a;
scanf("%d",&a);
return(a);
}

void calc_area()
{
area=length*breadth;
}

Output:
Enter length of rectangle: 3
Enter breadth of rectangle: 4
The area is 12
In the above program, three global variables are declared- length, breadth, and area. The
values of length and breadth are read through the get_number() function. The get_number()
function does not refer to any global variables, because it is called twice. During the execution,
there is no way the function can know for which variable a particular value is being read. There
fore, it uses the one way communication power of the return statement.

The area is calculated by the calling the calc_area() function. This function uses the values that
already have been placed in the length and breadth in order to calculate area. The result is
placed in the global variable area. This variable is accessible by the main function, so its value
can be printed by the printf statement located in the main function.

Static variables
Like the local variables Static variables are also local to the block in which they are declared.
The basic difference is that they don’t disappear when the function is no longer active. Their
values persist. if the control comes back to the same function again the static variables have the
same values they had last time around.Let us illustrate this by following example:

ar :
ch by
ya
increase(); increase();
void main() void main()
. A ed
{ clrscr(); { clrscr();
increase(); increase();
Pd ar

increase(); increase();
a ep

increase(); increase();
getch(); getch();
hn pr

} }
is e

increase() increase()
Kr Not

{ int i=1; //local variable { static int i=1; // static variable


printf(“ \n i = %d”,i); printf(“\n i = %d”,i);
i++; i++;
} }
output: output:
i=1 i=1
i=1 i=2
i=1 i=3

In above example when i is declared as local variable, each time the increase () function is
called it is re- initialized to 1.when the function terminates, I vanishes and it new value i.e. 2 is
lost. So the result remains 1 no matter how many times a function increase is called.

But when the variable i is declared as the static variable, it is initialized to 1 only once. It is never
initialized again. During the first call of increase(), i is incremented to 2. Since i is static, this
value persists. Now when the increase() is called next time, i is not re-initialized to 1, but its old
value 2 is retained. Thus the current value of i (i.e. 2) is printed and i is incremented to 3. When
the increase() is called for the third time , the current value of i i.e. 3 is printed and once again i
is increased to 4. Hence the statement static int i=1 is executed only once irrespective of how
many times the same function is accessed.

Basic Rules associated with static variables are:-


1) Initial values must be constants not expressions.
Like, static float i=3.0;
2) The initial value is assigned to the variable at the beginning of the program execution.
The variables retain these values throughout the life of the program, unless different
value is assigned during the computation process.
3) The static variables will have there default values equal to zero if their declarations do not
include explicit initial values.

ar :
ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr Not
STRUCTURES AND UNIONS

INTRODUCTION TO STRUCTURES

A structure is a collection of one or more variables, possibly of different data types, grouped together under a
single name for convenient handling. Structures help to organize data, particularly in large programs, because they
allow a group of related variables to be treated as a single unit.

Consider an example . In an organization, an employee’s details (i.e., his name , address, designation, salary etc.)
have to be maintained. One potential method would be to create a two-dimensional array, which would contain all
the details. But in this case, this is not possible because the parameters are of different types, i.e., name is of type
char, salary is of type float , and so on. There is a simple solution to this problem- structures.

STRUCTURE DECLARATION

Let us create a structure to illustrate the above-mentioned example

struct employee {
char *name;
char *address;

ar :
char *desig; ch by
ya
float salary;
} emp1, emp2;
. A ed

The keyword struct introduces a structure declaration, which is a list of declarations enclosed in braces. The
Pd ar

variables declared within the structure declaration are called its members. The struct declaration defines a datatype,
a ep

and the variables emp1 and emp2, which follows the struct declaration, is defined as variables of this type and
storage space is set-aside for them. This is equivalent to declaring variables of type int or char.
hn pr
is e

A structure declaration that is not followed by a list of variables reserves no storage space, it merely describes the
Kr ot

template. In other words, the structure is only defined, not declared.


N

The word following the keyword struct (employee in this case) is called a structures tag, and is optional. It is
optional because it only names this type that has been defined by the structure declaration, and can be used as a
substitute later. For example, at a later stage, if a new variable emp3 of type struct employee has to be declared, it
could be declared as

struct employee emp3;

There is no need to define the entire structure all over again.

The structure below is also equivalent to above-example:


struct {
char *name;
char *address;
char *desig;
float salary;
} emp1, emp2, emp3;
INITIALIZATION OF STRUCTURE

Like other variables and arrays, structure variables can also be initialized where they are declared. The format is
quite similar to that used to initiate arrays. Let us initialize a structure variable emp3 in the above-mentioned
example:

struct employee { char *name;


char *address;
char *desig;
float salary;
} emp1, emp2;
struct employee emp3 = {“George”, “Massachusetts”, “15000”, };

ACCESSING STRUCTURE ELEMENTS

After the declaration of structure name and structure variables, let us see how the elements of the structure can be
accessed. A member of a structure is always referred to and accessed using the structure name.

Structure name. member name

This structure member access operator “.”, connects the structure name and the member name. For example, to

ar :
print the name of the employee, ch by
printf(“The employee’s name is %s”,emp1.name);
ya
. A ed

NESTED STRUCTURES
Pd ar
a ep

Nested structures are nothing but structures within structures. Let us take the same example discussed above- the
address in the employee structure can be a structure by itself, which stores the house number, the street name, the
hn pr

area name and the pincode.


is e
Kr ot

struct emp_add { int no;


N

char *street;
char *area;
int pincode;
};

The above definition could be used as a template to declare a variable address in the employee structure

struct employee { char *name;


struct emp_add address;
char *desig;
float salary;
} emp1, emp2;

or, the two definitions could even be consolidated as:


struct employee { char *name;
struct emp_add { int no;
char *street;
char *area;
int pincode;
} address;
char *desig;
float salary;
}emp1,emp2;
ARRAYS OF STRUCTURE

Let us consider the above-mentioned example (of employees in an organization) to illustrate this concept. Assume
there are five employees in an organization whose records are to be maintained. The declaration goes like this
struct employee { char *name;
char *roll_no;
int salary;
} emp1[5];

This declaration defines five instances of the variable emp1, of type struct employee. They could be initialized as:

struct employee { char *name;


char *roll_no;
int salary;
} emp1[5] =
{
{“James”, “e01”, 10000},
{“Mark”, “e02”, 9000},
{“David”, “e03”, 11000},
{“Victoria”, “e04”, 15000},
{“Jeffery”, “e05”, 13000}

ar :
}; ch by
ya
As in the case of other datatypes, the index 5 does not have to be specified, as the initialization by itself will
. A ed

determine its size.


Pd ar

Note that in the initialization part of the above declaration, every particular employee’s details have been enclosed
a ep

in braces. This is not necessary, but it improves clarity of code. In case a member is not to be initialized , the value
for it can be omitted. For example, assume the name and salary of an employee are not known, the declaration will
hn pr

be
is e

{ , e06, }
Kr ot
N

Any member of the structure can be accessed using the index number along with the structure name. For example,
if one wants to print the name of the first employee,
Printf(“The name of the first employee is %s”, emp1[0].name);

We can declare as many structures variables as we want to fulfill our requirement. Now when we need to store
huge number of information like storing information of 100 or more students, employees etc, we can use structure
variables of type array.

For example,
struct student
{
char name[20];
int rollno;
int grade;
}
struct student s[50];

In above example, the structure variable s is an array of structure that may contain as many as 50 elements. Each
element is a structure of type student.

Thus if we want to access the name of 1st student i.e. s[0] , we would write s[0].name.
And to access rollno and grade we would write:
s[0].rollno
s[0].grade
Similarly to access the information of 2nd student we would write
s[1].name
s[1].rollno
s[1].grade

The syntax used to reference each element of array s is similar to the syntax used for normal arrays. The only
difference is that every element of array s is a structure.

In an array of structure all elements of the array are stored in adjacent memory locations. Since each element of
this array is a structure, and since all structure elements are always stored in adjacent locations we can easily guess
the arrangement of array of structures in memory.

For example, s[0]’ s name, rollno and grade in the memory would be immediately followed by s[1]’s name, rollno
and grade and so on.

POINTERS TO STRUCTURES

Pointers to structures are just like pointersto other ordinary variables. The declaration
struct employee {
……

ar :
…… ch by
ya
……
} *emp1;
. A ed

declares a pointer of type struct employee. If emp1 points to a structure, then emp1 is the pointer to the structure,
Pd ar

and either (emp1).name or emp1->name might be used to access the structure members. Here, -> is the member
a ep

access operator for pointers, which is nothing but a hyphen ‘-‘ followed by the greater than symbol ‘>’.
hn pr

The arithmetic for a pointer of this type is same as for any other datatype, and any manipulation that can be done
is e

through pointers to variables of other types is also possible for structures.


Kr ot
N

STRUCTURES AND FUNCTIONS

Structures may be passed to functions either by value or by reference. However , they are usually passed by
reference, i.e., the address of the structure is passed to the function. Let us consider the employee example for
instance. Given the structure declaration below

struct employee { char *name;


float basic;
float bonus;
} emp1;
assume that the gross salary has to be calculated by adding basic with bonus. The following function takes the
address of the structure as its parameter, adds up the two (basic and bonus) and sends the gross salary as output.

Example:

#include<stdio.h>

struct employee {
char name[20];
float basic;
float bonus;
}emp1;

main()
{ float gross, grosscalc();
printf(“\n Enter the employee’s name “);
scanf(“%s”,emp1.name);
fflush(stdin);
printf(“\n Enter the employee’s basic”);
scanf(“%f”,&emp1.basic);
fflush(stdin);
printf(“\n Enter the employee’s bonus”);
scanf(“%f”,&emp1.bonus);
fflush(stdin);
gross=grosscalc(&emp1); /*the address of the array is passed to the function, call by reference */
printf(“The employee’s %s’s gross is Rs. %0.0f”,emp1.name,gross);
}

float grosscalc(struct employee *emp)


/*emp is a pointer of type struct employee */
{
return(emp->basic +emp->bonus);
}

The following function reads input from the user , initializes each of the members and returns the entire structure.

ar :
ch by
ya
struct employee init()
/* returns a value of type struct employee */
. A ed

{ struct employee emp;


printf(“\n Enter the employee’s name”);
Pd ar

scanf(“%s”,emp.name);
a ep

fflush(stdin);
printf(“\n Enter the employee’s basic”);
hn pr

scanf(“%f”,&emp.basic);
is e

fflush(stdin);
Kr ot

printf(“\n Enter the employee’s bonus”);


N

scanf(“%f”,&emp.bonus);
fflush(stdin);
return emp;
}

USER- DEFINED DATATYPES

C allows programmers to define new datatypes equivalent to the existing system datatypes using the typedef
statement. Let us take the employee structure for example. Assume that the employee’s date of birth has to be
included in the existing structure. The declaration would be
Typedef struct {
int dd; /* date */
int mm; /* month */
int yy; /* year */
} dob;
Given this declaration, dob can be used in the structure just as if it were another datatype, like int, char and so on.
For example,

Dob emp_date_of_birth;
UNIONS

Consider a situation. “Silicon Info Solution” is a computer related company offering many courses to students. It
offers two major courses, and a lot of minor ones. The major courses are classified as majors 1 and 2, and the
minors are classified into ‘others’. When a student enrolls for a particular course, his details are entered into a file
and maintained till he completes the courses. The student structure looks like this
struct student { char *name;
int rollno;
};

Apart from this, in the students’ register, one more detail has to be included – the course the particular student is
enrolled for. But this poses a problem, since the two major courses are represented by numbers(1 and 2) and the
minor courses by a string. The solution to this problem is-union

A union is a variable which may hold (at different times) objects of different types and sizes, with the compiler
keeping track of size and alignment requirements. A union declaration is similar to a structure declaration.
Union courses { int major;
char *minor;
} course1;

Here , course1 will be large enough to hold the largest of the two types, int or char. Any one of these variables

ar :
might be stored in course1 and then used in expressions. Only condition is that the usage must be consistent, the
ch by
ya
type retrieved must be the type stored last.
. A ed

In the students’ register, the structure declaration would be


struct student { char *name;
Pd ar

int rollno;
a ep

Union course course_no;


} student1;
hn pr
is e

This would represent no storage problems as the member course_no has been declared as a union. Course_no can
Kr ot

now contain any value – char or int. the following program illustrates the usage of unions.
N

#include<stdio.h>
union course { int major;
char minor[10];
};
struct student { char name[20];
int rollno;
union course course_no;
} student1;
main()
{ char c_name;
printf(“\n Enter the name of the student”); scanf(“%s”,student1.name);
printf(“\n Enter the roll no . of the student”); scanf(“%d”,&student1.rollno);
printf(“\n Enter the course (‘M’ for major or ‘m’ for minor)”); scanf(“%c”,&c_name);
if(c_name==’M’)
{ printf(“\n Enter the course (‘1’ or ‘2’)”);
scanf(“%d”, &student1.course_no.major);
}
else
strcpy(student1.course_no.minor, “others”);
}

SUMMARY
A structure is a collection of one or more variables, possibly of different types, grouped together for convenient
handling.
Structures help to organize data because they allow a group of variables to be treated as a single unit.
A structure declaration starts with the keyword struct, which introduces the declaration.
The structure tag, which follows the keyword, is optional. It is only a label and not an actual structure in memory.
The declaration then follows with a list of variables enclosed within curly braces. These variables are called
members.
Members can be accessed using the member access operator ‘.’ .
The struct declaration defines a new datatype.
Nested structures are nothing but structures within structures.
The ‘typedef’ statement is used to define a new datatype.
Pointers to structures are just like pointers to other variables.
Members can be accessed through the pointer variable using the member access operator ‘->’
Structures may be passed to functions either by value or by reference.
A union is a variable that may hold objects of different types at different times.
A union declaration is similar to a structure declaration.

ar :
ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr ot
N
POINTERS

Pointers are basically the same as any other variable. However, what is different about them is that instead of
containing actual data, they contain a pointer to the memory location where information can be found. This is a very
important concept, and many programs and ideas rely on pointers as the basis of their design.

Variable names are not sufficient to provide the manipulations C requires. Local variables are meaningful only
within their declaring functions. However, memory addresses are global to all functions. One function can pass the
address of local variable to another function, and the second function can use this address to access the contents
of first function’s local variable. Hence, we use pointer variable, which can store the address or memory location
and points to whatever that memory location contains.

USES OF POINTER
 Pointers enable us to access a variable that is defined outside the function.
 Pointers reduce length and complexity of program and increase execution speed.
 Pointers are more efficient in handling data tables.
 The use of pointer array to character string results in saving data storage space in memory.

POINTER DECLARATION AND OPEARATIONS


In C we also give our pointer a type which, in this case, refers to the type of data stored at the address we will be

ar :
storing in our pointer. Imagine that we have an int called i. Its address could be represented by the symbol &i. If the

ch by
ya
pointer is to be stored as a variable, it should be stored like this.
int *ip = &i;
. A ed
int * is the notation for a pointer to an int. Address or ampersand (&) is the operator which returns the address of its
Pd ar

argument. When it is used, as in &i we say it is referencing i.


a ep

The opposite operator, which gives the value at the end of the pointer, is indirection operator (*). An example of
hn pr

use, known as de-referencing ip, would be


i = *ip;
is e
Kr Not

We may think of setting a pointer variable to point to another variable as a two-step process: first we generate a
pointer to that other variable, then we assign this new pointer to the pointer variable. We can say (but we have to
be careful when we're saying it) that a pointer variable has a value, and that its value is ``pointer to that other
variable''. This will make more sense when we see how to generate pointer values.

Pointers (that is, pointer values) are generated with the ``address-of'' operator &, which we can also think of as the
``pointer-to'' operator. We demonstrate this by declaring (and initializing) an int variable i, and then setting ip to
point to it:
int i = 5;
ip = &i;

The assignment expression ip = &i; contains both parts of the ``two-step process'': &i generates a pointer to i, and
the assignment operator assigns the new pointer to (that is, places it ``in'') the variable ip. Now ip ``points to'' i,
which we can illustrate with this picture:

i is a variable of type int, so the value in its box is a number, 5. ip is a variable of type pointer-to-int, so the ``value''
in its box is an arrow pointing at another box. Referring once again back to the ``two-step process'' for setting a
pointer variable: the & operator draws us the arrowhead pointing at i's box, and the assignment operator =, with the
pointer variable ip on its left, anchors the other end of the arrow in ip's box.
We discover the value pointed to by a pointer using the operator, *. Placed in front of a pointer, the * operator
accesses the value pointed to by that pointer. In other words, if ip is a pointer, then the expression *ip gives us
whatever it is that's in the variable or location pointed to by ip.
For example, we could write something like
printf("%d\n", *ip);
which would print 5, since ip points to i, and i is (at the moment) 5.

The contents-of operator * does not merely fetch values through pointers; it can also set values through pointers.
We can write something like
*ip = 7;
which means ``set whatever ip points to to 7.'' Again, the * tells us to go to the location pointed to by ip, but this
time, the location isn't the one to fetch from--we're on the left-hand sign of an assignment operator, so *ip tells us
the location to store to.

The result of the assignment *ip = 7 is that i's value is changed to 7, and the picture changes to:

If we called printf("%d\n", *ip) again, it would now print 7.

ar :
ch by
Let’s notice the difference between changing a pointer (that is, changing what variable it points to) and changing

ya
the value at the location it points to. When we wrote *ip = 7, we changed the value pointed to by ip, but if we
. A ed
declare another variable j:
int j = 3;
Pd ar

and write
a ep

ip = &j;
hn pr

We’ve changed ip itself. The picture now looks like this:


is e
Kr Not

We have to be careful when we say that a pointer assignment changes ``what the pointer points to.'' Our earlier
assignment
*ip = 7;
changed the value pointed to by ip, but this more recent assignment
ip = &j;
has changed what variable ip points to. It's true that ``what ip points to'' has changed, but this time, it has changed
for a different reason. Neither i (which is still 7) nor j (which is still 3) has changed. (What has changed is ip's value.)
If we again call
printf("%d\n", *ip);
this time it will print 3.

We can also assign pointer values to other pointer variables. If we declare a second pointer variable:
int *ip2;
then we can say ip2 = ip;
Now ip2 points where ip does; we've essentially made a ``copy'' of the arrow:

Now, if we set ip to point back to i again:


ip = &i;
the two arrows point to different places:

We can now see that the two assignments


ip2 = ip;
and
*ip2 = *ip;
do two very different things. The first would make ip2 again point to where ip points (in other words, back to i
again). The second would store, at the location pointed to by ip2, a copy of the value pointed to by ip; in other
words (if ip and ip2 still point to i and j respectively) it would set j to i's value, or 7.

It's important to keep very clear in your mind the distinction between a pointer and what it points to. You can't ``set
ip to 5'' by writing something like
ip = 5; /* WRONG */
5 is an integer, but ip is a pointer. You probably wanted to ``set the value pointed to by ip to 5,'' which you express
by writing

ar :
ch by
*ip = 5;

ya
. A ed
Similarly, you can't ``see what ip is'' by writing
printf("%d\n", ip); /* WRONG */
Pd ar

Again, ip is a pointer-to-int, but %d expects an int. To print what ip points to, use
a ep

printf("%d\n", *ip);
hn pr

Finally, a few more notes about pointer declarations. The * in a pointer declaration is related to, but different from,
is e

the contents-of operator *. After we declare a pointer variable


Kr Not

int *ip;
the expression
ip = &i
sets what ip points to (that is, which location it points to), while the expression
*ip = 5
sets the value of the location pointed to by ip.

If you have a pointer declaration containing an initialization, and you ever have occasion to break it up into a simple
declaration and a conventional assignment, do it like this:
int *ip3;
ip3 = &i;
Don't write
int *ip3;
*ip3 = &i;
POINTER ARITHMATIC

Pointers do not have to point to single variables. They can also point at the cells of an array. For example, we can
write
int *ip;
int a[10];
ip = &a[3];
and we would end up with ip pointing at the fourth cell of the array a (remember, arrays are 0-based, so a[0] is the
first cell). We could illustrate the situation like this:
We'd use this ip just like the one in the previous section: *ip gives us what ip points to, which in this case will be the
value in a[3].

Once we have a pointer pointing into an array, we can start doing pointer arithmetic. Given that ip is a pointer to
a[3], we can add 1 to ip:
ip + 1

What does it mean to add one to a pointer? In C, it gives a pointer to the cell one farther on, which in this case is
a[4]. To make this clear, let's assign this new pointer to another pointer variable:
ip2 = ip + 1;
Now the picture looks like this:

If we now do
*ip2 = 4;

ar :
ch by
We’ve set a[4] to 4. But it's not necessary to assign a new pointer value to a pointer variable in order to use it; we

ya
could also compute a new pointer value and use it immediately:
*(ip + 1) = 5;
. A ed
In this last example, we've changed a[4] again, setting it to 5. The parentheses are needed because the unary
Pd ar

``contents of'' operator * has higher precedence (i.e., binds more tightly than) the addition operator. If we wrote *ip +
a ep

1, without the parentheses, we'd be fetching the value pointed to by ip, and adding 1 to that value. The expression
*(ip + 1), on the other hand, accesses the value one past the one pointed to by ip.
hn pr

Given that we can add 1 to a pointer, it's not surprising that we can add and subtract other numbers as well. If ip
is e

still points to a[3], then


Kr Not

*(ip + 3) = 7;
sets a[6] to 7, and
*(ip - 2) = 4;
sets a[1] to 4.

Up above, we added 1 to ip and assigned the new pointer to ip2, but there's no reason we can't add one to a
pointer, and change the same pointer:
ip = ip + 1;

Now ip points one past where it used to (to a[4], if we hadn't changed it in the meantime). The shortcuts we learned
in a previous chapter all work for pointers, too: we could also increment a pointer using
ip += 1;
or
ip++;

Of course, pointers are not limited to ints. It's quite common to use pointers to other types, especially char. Here is
the innards of the mystrcmp function we saw in a previous chapter, rewritten to use pointers. (mystrcmp, you may
recall, compares two strings, character by character.)
char *p1 = &str1[0], *p2 = &str2[0];
while(1)
{
if(*p1 != *p2)
return *p1 - *p2;
if(*p1 = = '\0' || *p2 = = '\0')
return 0;
p1++; p2++;
}
The auto-increment operator ++ (like its companion, --) makes it easy to do two things at once. We've seen idioms
like a[i++] which accesses a[i] and simultaneously increments i, leaving it referencing the next cell of the array a.
We can do the same thing with pointers: an expression like *ip++ lets us access what ip points to, while
simultaneously incrementing ip so that it points to the next element. The preincrement form works, too: *++ip
increments ip, then accesses what it points to. Similarly, we can use notations like *ip-- and *--ip.

Hence we can summarize that:


 A pointer variable can be assigned address of any ordinary variable. (ip = &i)
 A pointer variable can be assigned value of another pointer variable provided both point the same data
type. (ip = ix )
 A pointer variable can be assigned NULL value. (ip = NULL where NULL is symbolic constant having value
0)
 An integer quantity can be added or subtracted from pointer variable.( ip + 3, ++ip, ip--)
 Two pointer variables can be compared provided both point to object of same data type.
 Two pointer variables can be subtracted provided both point to elements of same array.

POINTERS AND FUNCTIONS


Up to this point we have been discussing pointers to data objects. C also permits the declaration of pointers to
functions. Access to address in C allows a called function to communicate more than one piece of information back

ar :
ch by
to the calling function. With pass by value, the value of an argument is copied into the parameter. Any change in

ya
parameter does not affect the corresponding argument. When we pass the address to a called function, the called
function can alter the contents at that location. Pointers to functions have a variety of uses and some of them will
. A ed
be discussed here.
Pd ar

Consider the following real problem. You want to write a function that is capable of sorting virtually any collection of
a ep

data that can be stored in an array. This might be an array of strings, or integers, or floats, or even structures. The
sorting algorithm can be the same for all. For example, it could be a simple bubble sort algorithm, or the more
hn pr

complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration purposes.
is e

/* Program bubble.c */
Kr Not

#include <stdio.h>

int arr[10] = { 3,6,1,2,3,8,4,1,7,2};


void bubble(int a[ ], int N);

int main(void)
{
int i;
putchar('\n');
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
bubble(arr,10);
putchar('\n');

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


{
printf("%d ", arr[i]);
}
return 0;
}

void bubble(int a[], int N)


{
int i, j, t;
for (i = N-1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (a[j-1] > a[j])
{
t = a[j-1];
a[j-1] = a[j];
a[j] = t;
}
}
}
}

The bubble sort is one of the simpler sorts. The algorithm scans the array from the second to the last element
comparing each element with the one that precedes it. If the one that precedes it is larger than the current element,
the two are swapped so the larger one is closer to the end of the array. On the first pass, this results in the largest
element ending up at the end of the array. The array is now limited to all elements except the last and the process
repeated. This puts the next largest element at a point preceding the largest element. The process is repeated for a

ar :
number of times equal to the number of elements minus 1. The end result is a sorted array.

ch by
ya
Here our function is designed to sort an array of integers. Thus in line 1 we are comparing integers and in lines 2
. A ed
through 4 we are using temporary integer storage to store integers. What we want to do now is see if we can
convert this code so we can use any data type, i.e. not be restricted to integers.
Pd ar
a ep

If our goal is to make our sort routine data type independent, one way of doing this is to use pointers to type void to
point to the data instead of using the integer data type. As a start in that direction let's modify a few things in the
hn pr

above so that pointers can be used. To begin with, we'll stick with pointers to type integer.
is e

/* Program bubble.c using pointers */


Kr Not

#include <stdio.h>
int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
void bubble(int *p, int N);
int compare(int *m, int *n);

int main(void)
{
int i;
putchar('\n');

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


{
printf("%d ", arr[i]);
}
bubble(arr,10);
putchar('\n');

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


{
printf("%d ", arr[i]);
}
return 0;
}
void bubble(int *p, int N)
{
int i, j, t;
for (i = N-1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (compare(&p[j-1], &p[j]))
{
t = p[j-1];
p[j-1] = p[j];
p[j] = t;
}
}
}
}

int compare(int *m, int *n)


{
return (*m > *n);
}

ar :
Note the changes. We are now passing a pointer to an integer (or array of integers) to bubble(). And from within

ch by
ya
bubble we are passing pointers to the elements of the array that we want to compare to our comparison function.
And, of course we are dereferencing these pointer in our compare() function in order to make the actual
. A ed
comparison. Our next step will be to convert the pointers in bubble() to pointers to type void so that that function
will become more type insensitive.
Pd ar
a ep

POINTER AND ARRAY


There are a number of similarities between arrays and pointers in C. If you have an array
hn pr

int a[10];
you can refer to a[0], a[1], a[2], etc., or to a[i] where i is an int. If you declare a pointer variable ip and set it to point
is e

to the beginning of an array:


Kr Not

int *ip = &a[0];


you can refer to *ip, *(ip+1), *(ip+2), etc., or to *(ip+i) where i is an int.

There are also differences, of course. You cannot assign two arrays; the code
int a[10], b[10];
a = b; /* WRONG */
is illegal. As we've seen, though, you can assign two pointer variables:
int *ip1, *ip2;
ip1 = &a[0];
ip2 = ip1;

Pointer assignment is straightforward; the pointer on the left is simply made to point wherever the pointer on the
right does. We haven't copied the data pointed to (there's still just one copy, in the same place); we've just made
two pointers point to that one place.

The first such operation is that it is possible to (apparently) assign an array to a pointer:
int a[10];
int *ip;
ip = a;

What can this mean? C defines the result of this assignment to be that ip receives a pointer to the first element of a.
In other words, it is as if you had written
ip = &a[0];

The second facet of the equivalence is that you can use the ``array subscripting'' notation [i] on pointers, too. If you
write
ip[3]
it is just as if you had written
*(ip + 3)
So when you have a pointer that points to a block of memory, such as an array or a part of an array, you can treat
that pointer ``as if'' it were an array, using the convenient [i] notation. In other words, at the beginning of this section
when we talked about *ip, *(ip+1), *(ip+2), and *(ip+i), we could have written ip[0], ip[1], ip[2], and ip[i].

The third facet of the equivalence (which is actually a more general version of the first one we mentioned) is that
whenever you mention the name of an array in a context where the ``value'' of the array would be needed, C
automatically generates a pointer to the first element of the array, as if you had written &array[0]. When you write
something like
int a[10];
int *ip;
ip = a + 3;
it is as if you had written
ip = &a[0] + 3;
which (and you might like to convince yourself of this) gives the same result as if you had written
ip = &a[3];
DYNAMIC MEMORY ALLOCATION
In many programs, we have dimensioned arrays to some maximum size. This technique can waste memory if

ar :
amount of data is much less than the maximum. Unfortunately, we cannot always predict what the array size will

ch by
ya
be. A similar situation occurs with character strings. In certain implementations of other structures that hold data,
we should be able to activate and free memory locations as needed, or employ dynamic memory allocation.
. A ed
There are times when it is convenient to allocate memory at run time using malloc(), calloc(), or other allocation
Pd ar

functions. Using this approach permits postponing the decision on the size of the memory block need to store an
a ep

array, for example, until run time. Or it permits using a section of memory for the storage of an array of integers at
one point in time, and then when that memory is no longer needed it can be freed up for other uses, such as the
hn pr

storage of an array of structures.


is e

Allocating memory
Kr Not

When memory is allocated, the allocating function (such as malloc(), calloc(), etc.) returns a pointer. The type of
this pointer depends on whether you are using an older compiler or the newer ANSI type compiler. With the older
compiler the type of the returned pointer is char, with the ANSI compiler it is void.

If you are using an older compiler, and you want to allocate memory for an array of integers you will have to cast
the char pointer returned to an integer pointer. For example, to allocate space for 10 integers we might write:
int *iptr;
iptr = (int *)malloc(10 * sizeof(int));
if (iptr == NULL)

{ .. ERROR ROUTINE GOES HERE .. }

If you are using an ANSI compliant compiler, malloc() returns a void pointer and since a void pointer can be
assigned to a pointer variable of any object type, the (int *) cast shown above is not needed. The array dimension
can be determined at run time and is not needed at compile time. That is, the 10 above could be a variable read in
from a data file or keyboard, or calculated based on some need, at run time.

Because of the equivalence between array and pointer notation, once iptr has been assigned as above, one can
use the array notation. For example, one could write:

int k;
for (k = 0; k < 10; k++)
iptr[k] = 2;
to set the values of all elements to 2.
Even with a reasonably good understanding of pointers and arrays, one place the newcomer to C is likely to
stumble at first is in the dynamic allocation of multi-dimensional arrays. In general, we would like to be able to
access elements of such arrays using array notation, not pointer notation, wherever possible. Depending on the
application we may or may not know both dimensions at compile time. This leads to a variety of ways to go about
our task.

ar :
ch by
ya
. A ed
Pd ar
a ep
hn pr
is e
Kr Not
Freeing Memory

Memory allocated with malloc lasts as long as you want it to. It does not automatically disappear when a function
returns, as automatic-duration variables do, but it does not have to remain for the entire duration of your program,
either. Just as you can use malloc to control exactly when and how much memory you allocate, you can also
control exactly when you deallocate it.

In fact, many programs allocate some memory, use it for a while, but then reach a point where they don't need that
particular piece any more. Because memory is not infinite, it's a good idea to deallocate (that is, release or free)
memory you're no longer using. Dynamically allocated memory is deallocated with the free function. If p contains a
pointer previously returned by malloc, you can call
free(p);
which will ``give the memory back'' to the stock of memory from which malloc requests are satisfied. Calling free is
sort of the ultimate in recycling: it costs you almost nothing, and the memory you give back is immediately usable
by other parts of your program.

(Freeing unused memory is a good idea, but it's not mandatory. When your program exits, any memory which it has
allocated but not freed should be automatically released. If your computer were to somehow ``lose'' memory just
because your program forgot to free it, that would indicate a problem or deficiency in your operating system.)

ar :
Naturally, once you've freed some memory you must remember not to use it any more. After calling

ch by
ya
free(p);
it is probably the case that p still points at the same memory. However, since we've given it back, it's now
. A ed
``available,'' and a later call to malloc might give that memory to some other part of your program. If the variable p
is a global variable or will otherwise stick around for a while, one good way to record the fact that it's not to be used
Pd ar

any more would be to set it to a null pointer:


a ep

free(p);
p = NULL;
hn pr

Now we don't even have the pointer to the freed memory any more, and (as long as we check to see that p is non-
NULL before using it), we won't misuse any memory via the pointer p.
is e
Kr Not
Data Files

Introduction
Data stored on a medium, such as disk, are called a file. A computer file is analogous to the customary office file,
which stores related information according to title or some other convenient label. In many programming situations,
it is convenient to access a file than to enter a succession of individual data items from the keyboard.

Many applications require that information be written to or read from an auxiliary memory device in the firm of a
data files. Thus, data files allow us to store information permanently, and to access and after that information
whenever necessary.

There are two different types of data files, called stream–oriented (or standard) data files and system–oriented (or
low–level) data files. Stream oriented data files are easier to work with and are therefore more commonly used. The
basic difference between High level and Low-level disk I/O functions is that High level disk I/O functions do their
own buffer management, whereas in low level disk I/O functions, buffer management has to be done explicitly by
the programmer. Low-level disk I/O is more efficient both in term of operation and the amount of memory used by
the program but high level disk I/O functions are more commonly used in C programs, since they are easier to use
than low level disk I/O functions. The high-level file I/O functions are further categorized into text and binary file.

ar :
End-Of-File:

ch by
ya
It is important to understand that EOF is not a character. It is actually an integer value sent to the program
by the operating system and is defined in a header file stdio.h to have a value of 1. No character with this value is
. A ed
stored in a file in a disk. While creating a file, when the operating system finds the last character to the file has been
sent, it transmits the EOF signal. Both in text as well as in binary mode, the system keeps track of the total length of
Pd ar

the file and will signal an EOF when this length has been reached.
a ep
hn pr

File –Modes explanation


is e

File type Meaning


Kr Not

“r” read only mode specifies that the file can only be read from not written into.

“w” the file is opened in the write only mode. This means that the file can only be written into. Nothing
can be read from it. If the file is already certain data in if, the data is erased, and if no file in the specified name
exists, it is created and opened in the read only mode.

“a” append mode. The file is opened in the write only mode, the only difference being that the data that
is being written into the file gets appended at the end of the file (if the file certain data, it is not truncated or deleted)

“r+” the file is opened in the read + write mode. The file must first be read form, and then it can be
written into.

“w+” the file is opened in the write + read mode. The file can first be written into and then read from.

“a+” allows existing data to be read, and new data to be added at the end of file.

A Null value is returned, if the file cannot be opened where fopen() function is used. Eg. When an existing data file
cannot be found.

File Handling Functions


Function Description Syntax
fopen() create or opens a file fopen(“filename”, “mode”)
fclose() closes a file fclose(fileptr)
getc() reads a character from a file c = getc(fileptr)
putc() writes a character to a file putc(c,fileptr)
fprintf() writes a set of data values to a file fprintf(fileptr,“ctrl str”, list)
fscanf() reads a set of data from a file fscanf(fileptr,“ctrl str”, list)
getw() reads an integer from a file getw(fileptr)
putw() writes an integer to a file putw(integer,fileptr)
fseek() sets the position to a desired point in a file fseek(fileptr, offset, position)
ftell() gives the current position in the file ftell(fileptr)
rewind() sets the position to the beginning of a file rewind(fileptr)

where, c is a character. fileptr is a pointer to a data file. ctrl str is a conversion specification for the items in the list.
offset specifies number of bytes to be moved from the location specified by the position. mode specifies manner in
which the data file will be utilized.

Processing a data files


Most data files application requires that a data file be altered as it is being processed. For e.g. in an application
involving the processing of customer records, it may be desirable to add new records to the file, to delete existing
records, to modify the contents of existing records or to rearrange the records.
The processing of a file involves following steps.
Opening a file

ar :
Reading from / writing on to a file and

ch by
ya
Closing the opened file . A ed
Defining and opening a file
Pd ar

We must specify certain things about a file, if we want to store the file in the secondary memory. They include –
a ep

filename, data structure and purpose. Filename is a string of characters that make up valid filename for the operating
system. Data structure is a framework for storing data and algorithms that implement and perform operations on the
hn pr

structure. Data structure of a file is defined as FILE in the library of standard I/O function definition. All files
is e

should be declared as FILE before they are used. Finally we must also specify what we want to do with the file.
Kr Not

The temporary space (buffer) allows information to be read from or written to the data files, ore rapidly them would
otherwise be possible.

FILE * fp;

Where FILE is a special structure type that establishes buffer area and fp is a pointer variable that indicates the
beginning of the buffer area (storage area). This file pointer fp contains all the information about the file and is used
as communication link between the system and the program.

A data file must be opened before it can be created or processed. This gives the file name with the buffer area. It also
specifies how the data file will be utilized i.e. read only, write only or read/write file. The library function fopen() is
used to open a file. This is written as:

fp = fopen (“file name”, “file mode”);

Here, file name and file modes are strings that represent the name of the data file and the manner in which the data
file will be utilized.
Closing a Data file
Although you can open multiple files, there's a limit to how many you can have open at once. If your program will
open many files in succession, you'll want to close each one as you're done with it; otherwise the standard I/O
library could run out of the resources it uses to keep track of open files. Closing a file simply involves calling library
function fclose() with the file pointer as its argument:
fclose(fp);
Calling fclose() arranges that (if the file was open for output) any last, buffered output is finally written to the file,
and that those resources used by the operating system (and the C library) for this file are released. If you forget to
close a file, it will be closed automatically when the program exits. But, it is good programming practice to close a
data file explicitly using the fclose() function, though most ‘c’ compilers will automatically close a data file at the
end of program execution if a call to fclose() is not present.

Example:
void main()
{ char c;
FILE *fileptr;
fileptr=fopen(“myfile.dat”,”w+”);
-----------
-----------
fclose(fileptr); }

I/O with File Pointers


For each of the I/O library functions we've been using so far, there's a companion function that accepts an additional
file pointer argument telling it where to read from or write to. The companion function to printf is fprintf, and the
file pointer argument comes first. To print a string to the myfile.dat file we opened in the previous example, we

ar :
might call

ch by
ya
fprintf(fileptr, "Hello, world!\n"); . A ed
The companion function to getchar is getc, and the file pointer is its only argument. To read a character from the
myfile.dat file we opened in the previous section, we might call
Pd ar

int c;
a ep

c = getc(fileptr);
hn pr

The companion function to putchar is putc, and the file pointer argument comes last. To write a character to
is e

myfile.dat, we could call


Kr Not

putc(c, fileptr);

Basic file manipulation


When a C program begins execution, it has access to three predefined streams or standard files – stdin, stdout, and
stderr. stdin is a constant file pointer corresponding to standard input, and stdout is a constant file pointer
corresponding to standard output. Both of these can be used anywhere a file pointer is called for; for example,
getchar() is the same as getc(stdin) and putchar(c) is the same as putc(c, stdout). The third predefined stream is
stderr. Like stdout, stderr is typically connected to the screen by default. The difference is that stderr is not
redirected when the standard output is redirected. Anything printed to stdout is redirected to the file filename, but
anything printed to stderr still goes to the screen. The intent behind stderr is that it is the ``standard error output'';
error messages printed to it will not disappear into an output file.
For example, a more realistic way to print an error message when a file can't be opened would be
if((fp = fopen(filename, "r")) = = NULL)
{ printf("can't open file %s\n", filename);
exit or return }
where filename is a string variable indicating the file name to be opened. Not only is the error message printed to
stderr, but it is also more informative in that it mentions the name of the file that couldn't be opened.
Creating a file
A data file must be created before it can be processed. A stream oriented data file can be created in two ways; one is
to create the file directly, using a text editor or a word processor. The other is to write a program that enters
information into the computer and then writes it out to the data file. When creating a new data file with a specially
written program the usual approach is to enter the information from the keyboard and then write it out to the data
file. If the data file consists of individual characters, the library function getchar()/getc() and putchar()/putc() can be
used to enter the data form the keyboard and to write it out to the data file.
Example : creating a data file ( to convert lowercase to upper case)
#include<stdio.h>
#include<ctype.h>
void main()
{ FILE *fp1;
Char c;
fp1=fopen(“sample.dat”, “w”);
do
putc(toupper(c=getchar()),fp1);
while(“c!=’\n’);
fclose(fp1); }

1. Character Input/Output:
Using character I/O data can be read or written one character at a time. This is analog to the way functions putchar
(), and getch (); write data to screen and read data from the keyboard.

Writing to a file:
Once the program has established the line of communication with a particular file by opening it, then it can write to

ar :
the file. The syntax of function that writes one character at a time is

ch by
ya
fputc( ch, fptr );
Where ch is character variable or constant and ‘fptr’ is a file pointer.
. A ed
The fputc () is similar to the putchar () function the only difference is that a putchar function always
writes to screen unless redirection employed.
Pd ar
a ep

Reading from a file:


If the program can write to a file, it should also be able to read from a file. The syntax of the function that reads and
hn pr

returns one character at a time is


is e

Ch= fgetc ( fptr );


Kr Not

Where ch is character variable and fptr is file pointer. The fgetc ( ) funtion is similar to getchar ( ), getche( ), and
getch ( ); functions, the only difference is that the later functions always read from the keyboard unless redirection
is employed.
// Writing to a file // reading from a file
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
FILE *fp; FILE *fp;
char ch; char ch;
fp=fopen("ex2.dat", "w"); fp=fopen("ex2.dat", "r");
if(fp==NULL) if(fp==NULL)
{ printf("Unable to create file"); { printf("Unable to read file");
getch(); getch();
exit(1); exit(1);
} }
printf("Enter set of characters\n"); printf("\n Characters from file\n");
while((ch=getchar())!='\n') while((ch=fgetc(fp))!=EOF)
{ {
fputc(ch, fp); putchar(ch);
} }
fclose(fp); getch();
} fclose(fp);
}
2. String Input/ Output:
Using string I/O data can be read or written in the form of string of characters. Reading and writing strings of
character is as easy as individual characters. This is analogous to puts (),and gets() functions that write data to screen
and read data from the keyboard.

Writing to a file:
The syntax of the function that writes a string of characters at a time is
fputs (str, fptr );
Where str is an array of characters or a string constant, and fptr is a file pointer.
The fputs() functon is similar to puts() function, the only difference is that the put() function always writes to the
screen unless redirection is employed.

Reading from a file:


The syntax of the function that reads strings from a file is
fgets ( str, n, fptr );
where str is an array of characters and specifies the address where the string is to be stord , n is the maximum length
of the input string, and fptr is a file pointer. The fgets ( ) function is similar to gets ( ) function, the only difference is
that the gets ( ) function always reads from keyboard unless redirection is employed. The fgets ( ) function returns

ar :
NULL value when it reads EOF.

ch by
ya
// Writing to a file // reading from a file
. A ed
#include<stdio.h> #include<stdio.h>
Pd ar

#include<string.h> #include<string.h>
void main() void main()
a ep

{ {
FILE *fp; FILE *fp;
hn pr

char str[80]; char str[80];


is e

fp=fopen("ex1.dat", "w"); fp=fopen("ex1.dat", "r");


Kr Not

if(fp==NULL) if(fp==NULL)
{ {
printf("Unable to create file"); printf("Unable to open file");
getch(); getch();
exit(1); exit(1);
} }
printf("Enter set of strings\n"); printf("Set of strings from file\n");
while(strlen(gets(str))>0) while(fgets(str, 80,fp)!=NULL)
{ {
fputs(str, fp); puts(str);
} }
fclose(fp); getch();
} fclose(fp);
}
3. Formatted Input/Output:
So far we have considered reading and writing of characters and strings. What about numbers? Let us suppose that
we want to store information about an agent comprising his name ( a string) code number ( an integer number ), and
height ( a real number ). We want to create a data file for a given list of agents.

Writing to a file:
The syntax of the function that writes formatted data to a file is
fprintf ( fptr, “ format-string”, ditems );
Where fptr is a file pointer and ditems is a lists of variables to be written to a file. The fprintf ( ), is similar to printf (
) function, the only difference is that printf ( ) function writes formatted data on to the screen instead of file.

Reading from a file:


The syntax of the function that reads formatted data from a file is
fscanf ( fptr, “ format-string”, ditems );
Where fptr is a file pointer and ditems is a lists of variables to be written to a file. The fscanf ( ), is similar to scanf (
) function, the only difference is that scanf ( ) function reads formatted data from the keyboard.

// Writing to a file //reading from a file


#include<stdio.h> #include<stdio.h>

ar :
#include<string.h> #include<string.h>

ch by
ya
void main() void main()
{ {
. A ed
FILE *fp; FILE *fp;
Pd ar

char name[80]; char name[80];


int roll; int roll;
a ep

fp=fopen("ex3.dat", "w"); if((fp=fopen("ex3.dat", "r"))= =NULL)


if(fp==NULL) {
hn pr

{ printf("Unable to read file");


is e

printf("Unable to create file"); getch();


Kr Not

getch(); exit(1);
exit(1); }
} printf("\n Name and roll\n");
printf("Enter name and roll\n"); while(fscanf(fp, "%s%d",name,&roll)!=EOF)
scanf("%s%d", name, &roll); printf("%s %d", name, roll);
fprintf(fp," %s %d", name, roll); getch();
fclose(fp); fclose(fp);
} }

4. Record Input/Output:
We have seen that character I/O and string I/O permits reading and writing of character data only. Whereas the
formatted I/O permit reading and writing of character data as well as numeric data. However, the arrays and
structures are stored as sequence of values. So these are handled as block of data instead of processing one data at a
time.

Writing to a file:
The syntax of the function that writes block of data at a time is
fwrite(ptr, m, n, fptr)
where ptr is an address of array or structure to be written, m is the size of an array or a structure, n is the number of
such arrays or structures to be written and fptr is a file pointer.
Reading from a file:
The syntax of the function that writes block of data at a time is
fread(ptr, m, n, fptr)
where ptr is an address of array or structure where block will be stored after reading, m is the size of an array or a
structure, n is the number of such arrays or structures to be read and fptr is a file pointer opened for reading.

5. Array Input/Output:
// Writing to a file //reading from a file
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp; FILE *fp;
int a[10], i; int a[10], i;
if((fp=fopen("ex4.dat", "w"))==NULL) if((fp=fopen("ex4.dat", "r"))==NULL)
{ {
printf("Unable to create file"); printf("Unable to open file");
getch(); getch();
exit(1); exit(1);
} }
printf("\n Enter array elements\n"); printf("\n Array elements are\n");
for(i=0; i<10; i++) fread(&a,sizeof(a),1,fp);
scanf("%d",&a[i]); for(i=0; i<10; i++)

ar :
fwrite(&a,sizeof(a),1,fp); printf("%d\t",a[i]);

ch by
ya
fclose(fp); fclose(fp);
} getch();
. A ed
}
Pd ar

6. Structure Input/Output:
a ep
hn pr

// Writing to a file //reading from a file


#include<stdio.h> #include<stdio.h>
is e

void main() void main()


Kr Not

{ {
FILE *fp; FILE *fp;
struct student struct student
{ char name[20]; { char name[20];
int roll; int roll;
}s; }s;
if((fp=fopen("ex5.dat", "w"))==NULL) if((fp=fopen("ex5.dat", "r"))==NULL)
{ {
printf("Unable to create file"); printf("Unable to open file");
getch(); exit(1);
exit(1); }
} printf("\n structure members are\n");
printf("\n Enter name,roll of student\n"); fread(&s,sizeof(s),1,fp);
scanf("%s%d",s.name,&s.roll); printf("%s%d\t",s.name, s.roll);
fwrite(&s,sizeof(s),1,fp); fclose(fp);
fclose(fp); getch();
} }
Program that appends one file to another

#include<stdio.h>
void main()
{ char c;
FILE *fp1, *fp2;

/*assume that two files exam1.dat and exam2.dat exist already*/


fp1=fopen(“exam1.dat”,”a”);
fp2=fopen(“exam2.dat”,”r”);

c=fgetc(fp2);
while(c!=EOF)
{
fputc(c,fp1);
c=fgetc(fp2);
}
fclose(fp1);
fclose(fp2);

ar :
}

ch by
ya
Program that displays the contents of a file in reverse order
. A ed
#include<stdio.h>
Pd ar

void main()
a ep

{ char c;
long int pos;
hn pr
is e

FILE *fp;
Kr Not

/*assume that two files exam.dat exist already*/

fp=fopen(“exam.dat”, “r”);
pos=ftell(fp);
fseek(fp,-1,2);
while(ftell(fp)>pos)
{
c=fgets(fp);
fseek(fp,-2,1);
printf(“%c”,c);
}
c=fgets(fp);
printf(“%c”,c);
fclose(fp);
}
An Introduction to Dynamic Memory Allocation
Up until this time, we have used what is referred to as static memory. Static memory means we
reserve a certain amount of memory by default inside our program to use for variables and such.
While there is nothing wrong with this, it means that once we reserve this memory, no other
program can use it, even if we are not using it at the time. So, if we have two programs that
reserve 1000 bytes of memory each, but neither program is running, then we have 2000 bytes of
memory that is being completely wasted. Suppose we only have 3000 bytes of memory, but we
already have our two programs that take 1000 bytes each. Now we want to load a program that
needs 1500 bytes of memory. Well, we just hit a wall, because we only have 3000 bytes of
memory and 2000 bytes are already reserved. We can't load our third program even though we
have 2000 bytes of memory that isn't even being used. How could we possibly remedy this
situation?
If you said Dynamic Memory Allocation, then you must have read the title of this lesson. That's
right. We are going to use dynamic memory to share the memory among all three programs.
Dynamic memory won't fix everything. We will always need an amount of finite static memory,
but this amount is usually much less than we need. This is why we still have static memory.
So, let us imagine a new scenario. We have changed our first two programs to use dynamic
memory allocation. Now they only need to reserve 100 bytes of memory each. This means we

ar :
ch by
are now only using 200 bytes of our 3000 total memory bytes available. Our third program,

ya
which requires 1500 bytes of memory can now run fine.
. A ed
C dynamic memory allocation functions are defined in stdlib.h header
Pd ar

Function Description
malloc allocates the specified number of bytes
a ep

realloc increases the size of the specified block of memory. Reallocates it if needed
hn pr

calloc allocates the specified number of bytes and initializes them to zero
free releases the specified block of memory back to the system
is e
Kr Not

malloc( number of element * size of each element);


int * ptr;
ptr = malloc(10*sizeof(int));
Where size represents the memory required in bytes .The memory which is provided is
contiguous memory.
But malloc function return void pointer so it needed type casting of that pointer.
(type cast)malloc( number of element * size of each element);
int * ptr;
ptr =(int*) malloc(10*sizeof(int));
calloc()
In malloc requested memory is provided a block of contiguous memory . calloc() function is
similar to the malloc rather then calloc() function
allocated the memory block for an array of elements. Memory for a group of objects used
calloc() function. If calloc() function is executed
succesfully then its allocated memory is set as zero and a pointer returned and if the function
failed then a NULL pointer return.
Example:
void *calloc(size_t number,size_t size);
size_t used for unsigned on most compilers.The number is the number of objects which is
allocate, and size is the size (in bytes) of each object.

Scenario:
We have used variable which requires all variables to be declared before we use it. So if we need
to store 100 students roll no then we need to declare 100 individual integer variables. This
problem can be solved with the help of array; single array declaration can store 100 or more
integer values. One of the biggest limitation is array size cannot be increased or decreased during
execution of a program. To get this better consider the following C program statement:
int roll_no[100];
Suppose we want to store roll_no of 100 students (200 bytes of memory occupied due to above
declaration) and above C language statement will do the same task. During C program execution
I thought that I will enter only 40 students’ roll_no. This decision of entering only 40 students’
roll_no will use 80 bytes out of 200 bytes (2 bytes per integer*40 students) of memory and
remaining 120 bytes of memory will be useless.
If we want to store 150 students’ roll_no using same program, we cannot do so because we have
declared array to store only 100 students’ roll_no. To overcome this memory allocation problem
we need to dynamically allocate memory according to user input. We can do this with C’s two

ar :
ch by
inbuilt functions calloc, malloc and a pointer. Calloc and malloc is two functions which help to

ya
dynamically allocate memory at runtime (during program execution) and this can reduce
. A ed
memory wastage problem.
#include<stdio.h>
Pd ar

#include<conio.h>
a ep

#include<stdlib.h>
void main()
hn pr

{
int no, *pt,i;
is e

clrscr();
Kr Not

printf("Enter no of Students :");


scanf("%d",&no);
pt=(int *)malloc(no*2);
if(pt== NULL)
{
printf("\n\nMemory allocation failed!");
getch();
exit(0);
}
printf("* * * * Enter roll no of students. * * * *\n");
for (i=0;i<no;i++)
{
printf("-->");
scanf("%d",(pt+i));
}
printf("\n* * * * Entered roll no. * * * *\n");
for (i=0;i<no;i++)
{
printf("%d, ",*(pt+i));
}
getch();
}
Code Explanation:
Let’s dig out the above program; this is a simple c program example which uses integer pointer
to dynamically allocate memory according to user’s input at runtime. As I told you earlier that
we can do this either with malloc() or calloc(). In this example I am using malloc() and calloc()
is explained below. To use malloc() or calloc() function we must include stdlib.h or alloc.h
header file otherwise you will get malloc prototype error at compilation. Line no. 3 includes the
stdlib.h header file. In line no. 7 an integer pointer pt and some other integer is declared which
we will need later in input and loop. Line no. 11 stores integer number in no variable which is
used as number of students whose roll number we are going to input. Next line (line no. 12) is
most important one in this program; it does all allocation jobs. If malloc function is able to
allocate memory then it returns address of memory chunk that was allocated else it returns
NULL.
pt=(int *)malloc(no*2);
As you already know that malloc is a function, it requires one parameter or argument i.e. number
of bytes to reserve. In our program we provided no*2 as parameter. The variable no holds the
number of students whose roll no we are going to enter. But why we are multiplying no with 2?
Here is answer, suppose we want to store roll number of 10 students. We stored 10 in no variable
and passed this no variable in malloc function. But do you think it will work? Because integer
occupies 2 bytes and we wanted to store 10 students information. And if we pass 10 to malloc

ar :
ch by
then compiler will reserve 10 bytes only which can store only 5 students’ information. To solve

ya
this issue I have multiplied no with 2 so if you enter 10 then it will reserve 20 bytes of memory.
. A ed
If you don’t remember which data type occupies how much memory then you can use sizeof()
which return data type size.
Pd ar

pt=(int *)malloc(no*sizeof(int));
a ep

Just before malloc() I have used (int *), this is called type casting (means converting from one
hn pr

data type to other compatible data type). If memory allocation is successful then malloc() by
default returns pointer to a void and we type cast that to integer pointer and stores the address in
is e

pt integer pointer variable. So pt pointer contains starting address of memory allocated using
Kr Not

malloc().
If, due any reason, malloc() fails to allocate memory it returns NULL. Line no. 13 – 18 does the
same job, if malloc() fails to allocate memory the it will show error and exit from program.
Line no 21 – 25 is used to take roll no of student and store it in memory. Look at line no. 24 and
particularly at (pt + i) statement. Integer pointer pt contains starting address of memory which is
allocated by malloc() and by adding i variable value we are instructing it to move further to store
value in that memory chunk. For example, if pointer starting address is 1002 then (pt+1) would
mean 1004, (pt+2) = 1006 and so on.
Line no. 28 – 31 prints the value stored in the memory and thing is simple.
C Program to show Dynamic Memory Allocation using Calloc()
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int no, *pt,i;
clrscr();
printf("Enter no of Students :");
scanf("%d",&no);
pt=(int *)calloc(no,2);
if(pt== NULL)
{
printf("\n\nMemory allocation failed!");
getch();
exit(0);
}
printf("* * * * Enter roll no of students. * * * *\n");
for (i=0;i<no;i++)
{
printf("-->");
scanf("%d",(pt+i));
}

printf("\n* * * * Entered roll no. * * * *\n");


for (i=0;i<no;i++)
{
printf("%d, ",*(pt+i));
}
getch();
}
Code Explanation:
Above is the same example what we have explained in malloc(), the only difference is here we

ar :
ch by
used calloc(). As you all know calloc() malloc() function does the same job but calloc() is a bit

ya
differ from malloc(). Calloc() takes two values as its parameter whereas malloc() takes one
. A ed
parameter. In line no 12 calloc() has two arguments 10,2. Here 2 indicates that we want to store
integer value so make per block 2 bytes and 10 indicates that we want to store 10 integer values.
Pd ar

One more important difference between calloc() and malloc() is that by default memory
a ep

allocated by malloc() contains garbage values where as memory allocated by calloc() contains
hn pr

all 0 (zero). Rest code is explained earlier in malloc explanation section.


is e

Few c Examples program:


Kr Not

/*Wtite a program to read data from the keyboard,write it to a file


called myfile again read the same data from myfile and display it on
the screen
*/
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char c;
printf("Data Input\n\n");
fp=fopen("myfile.txt","w");

while((c=getchar())!=EOF)
putc(c,fp);
fclose(fp);
printf("\n data output\n\n");
fp=fopen("myfile.txt","r");
while((c=getc(fp))!=EOF)
printf("%c",c);
fclose(fp);
getch();
return 0;
}
/*Write a program to read name,address and telephone number of 10
Student,write them on the student.txt file and display them reading
from file
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char name[20],add[45];
int tno,i;
FILE *fp;
fp=fopen("student.txt","a");

ar :
ch by
for(i=0;i<10;i++)

ya
{
. A ed
fflush(stdin);
Pd ar

printf("\n Enter Name:");


gets(name);
a ep

printf("\n Enter Address:");


hn pr

gets(add);
printf("\n Enter TelephoneNo:");
is e

scanf("%d",&tno);
Kr Not

fprintf(fp,"%s %s %d\n",name,add,tno);
}
fclose(fp);
fp=fopen("student.txt","r");
printf("\nName\tAddress\tTelephoneNo\n");
while(fscanf(fp,"%s %s %d",name,add,&tno)!=EOF)
printf("%s\t %s\t%d\n",name,add,tno);
fclose(fp);
getch();
return 0;
}
/*Write a program to reading from data file
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char name[20],add[45];
int tno,i;
FILE *fp;
fp=fopen("student.txt","r");
printf("\nName\tAddress\tTelephoneNo\n");
while(fscanf(fp,"%s %s %d",name,add,&tno)!=EOF)
printf("%s\t %s\t%d\n",name,add,tno);
fclose(fp);
getch();
return 0;
}
/*Write a program to read name,address and telephone number of 10
Student,write them on the student.txt file and display them reading
from file
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()

ar :
ch by
{

ya
char name[20];
. A ed
int std_no,marks,i,n;
Pd ar

FILE *fp;
printf("how many student?\n");
a ep

scanf("%d",&n);
hn pr

fp=fopen("student1.txt","a");
is e

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

{
fflush(stdin);
printf("\n Enter Name:");
gets(name);
printf("\n Enter Student No:");
scanf("%d",&std_no);
printf("\n Enter Marks:");
scanf("%d",&marks);
fprintf(fp,"%s %d %d\n",name,std_no,marks);
}
fclose(fp);
fp=fopen("student1.txt","r");
printf("\nName\tStudentNo\tMarks\n");
while(fscanf(fp,"%s %d %d",name,&std_no,&marks)!=EOF)
printf("%s\t %d\t %d\n",name,std_no,marks);
fclose(fp);
getch();
return 0;
}
/*Write a program to read name,address and telephone number of 10
Student,write them on the student.txt file and display them reading
from file
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char name[20];
int std_no,marks,i,n;
FILE *fp;
printf("how many student?\n");
scanf("%d",&n);
fp=fopen("student1.txt","a");
for(i=0;i<n;i++)
{
fflush(stdin);

ar :
ch by
printf("\n Enter Name:");

ya
gets(name);
. A ed
printf("\n Enter Student No:");
scanf("%d",&std_no);
Pd ar

printf("\n Enter Marks:");


a ep

scanf("%d",&marks);
hn pr

fprintf(fp,"%s %d %d\n",name,std_no,marks);
}
is e

fclose(fp);
Kr Not

fp=fopen("student1.txt","r");
printf("\nName\tStudentNo\tMarks\n");
while(fscanf(fp,"%s %d %d",name,&std_no,&marks)!=EOF)
printf("%s\t %d\t %d\n",name,std_no,marks);
fclose(fp);
getch();
return 0;
}
/*Write a program taht read 100 integer for a file and read every integer\
from file to store in odd file if number is odd and even file if even number then
finally prints all the file in the console.
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int i,n;
FILE *fp,*fod,*fev;
fp=fopen("data.txt","w");
printf("Enter 100 integer one by one\n");
for(i=0;i<10;i++)
{
scanf("%d",&n);
putw(n,fp);
}
fclose(fp);
fp=fopen("data.txt","r");
fev=fopen("even.txt","w");
fod=fopen("odd.txt","w");
for(i=0;i<10;i++)
{
n=getw(fp);
if(n%2==0)
putw(n,fev);
else

ar :
ch by
putw(n,fod);

ya
}
. A ed
fclose(fp);
fclose(fod);
Pd ar

fclose(fev);
a ep
hn pr

printf("\nContent of even file\n\n");


fev=fopen("even.txt","r");
is e

while((n=getw(fev))!=EOF)
Kr Not

printf("%d\n",n);
fclose(fev);
printf("\nContent of odd file\n\n");
fod=fopen("odd.txt","r");
while((n=getw(fod))!=EOF)
printf("%d\n",n);
fclose(fod);
getch();
return 0;
}
/*develop a menu driven program to create a sequential data file
called employee.txt with ecmpcode,empname,salary. the program should
display works on option as given bellow*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct employee
{
char name[25],empcode[50];
int salary;
};
int main()
{
struct employee e;
FILE *fp,*fp1;
char tname[25],tempcode[50];
int n,i,j,k,salary;
while(1)
{
printf("\n\n\n\n");
printf("1. Data Entry\n");
printf("2. View Records\n");
printf("3. Search Record\n");
printf("4. Delete Record\n");
printf("5. Update Record\n");
printf("6. Exit\n");

ar :
ch by
printf("Enter Your Choice[1-6]");

ya
scanf("%d",&n);
. A ed
switch(n)
{
Pd ar

case 1:
a ep

{
hn pr

fp=fopen("test1.txt","a");
fflush(stdin);
is e

printf("\n Enter First Name:");


Kr Not

gets(e.name);
printf("\n Enter Employee code:");
gets(e.empcode);
printf("\n Enter Salary:");
scanf("%d",&e.salary);
fwrite(&e,sizeof(e),1,fp);
fclose(fp);
}
break;
case 2:
{
fp=fopen("test1.txt","r");
printf("\nName\t\t Emp.Code \tSalary\n");
printf("------\t\t----------\t------\n");
while(fread(&e,sizeof(e),1,fp)==1)
printf("%s \t%s \t\t%d\n",e.name,e.empcode,e.salary);
fclose(fp);
}
break;
case 3:
{
i=0;
fp=fopen("test1.txt","r");
fflush(stdin);
printf("Enter name for Search:");
gets(tname);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(tname,e.name)==0)
{
printf("%s \t%s \t%d\n",e.name,e.empcode,e.salary);
i++;
}
}
if(i==0)
printf("Record not Exist\n");
fclose(fp);

ar :
ch by
}

ya
break;
. A ed
case 4:
{
Pd ar

j=0;
a ep

fp=fopen("test1.txt","r");
hn pr

fp1=fopen("temp.txt","w");
fflush(stdin);
is e

printf("Enter name for Delete:");


Kr Not

gets(tname);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(tname,e.name)==0)
j++;
else
fwrite(&e,sizeof(e),1,fp1);
}
if(j==0)
printf("Record not Exist\n");
else
printf("Such Record is deleted.");

fclose(fp);
fclose(fp1);
remove("test1.txt");
rename("temp.txt","test1.txt");
}
break;
case 5:
{
k=0;
fp=fopen("test1.txt","r");
fp1=fopen("temp.txt","w");
fflush(stdin);
printf("Enter Employee Name for Update:");
gets(tname);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(tname,e.name)==0)
{
fflush(stdin);
printf("\n Enter Employee Name:");
gets(tname);
strcpy(e.name,tname);
printf("\n Enter Salary:");
scanf("%d",&salary);

ar :
ch by
e.salary=salary;

ya
fflush(stdin);
. A ed
printf("\n Enter Employee code:");
gets(tempcode);
Pd ar

strcpy(e.empcode,tempcode);
a ep

fwrite(&e,sizeof(e),1,fp1);
hn pr

k++;
}
is e

else
Kr Not

fwrite(&e,sizeof(e),1,fp1);
}
if(k==0)
printf("Record not Exist\n");
else
printf("Record has been updated.");
fclose(fp);
fclose(fp1);
remove("test1.txt");
rename("temp.txt","test1.txt");
}
break;
case 6:
exit(1);
default:
printf("Worng Choice!! option are [1-6]");
}
}
getch();
return 0;
}
----
/*Write a program to input a charater from key board into file called input.txt
and read all charecter one by one*/

#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char c;
printf("Data Input\n\n");
fp=fopen("input.txt","w");

while((c=getchar())!=EOF)
putc(c,fp);
fclose(fp);

ar :
ch by
ya
printf("\n data output\n\n");
. A ed
fp=fopen("input.txt","r");
Pd ar

while((c=getc(fp))!=EOF)
a ep

printf("%c",c);
hn pr

fclose(fp);
getch();
is e

return 0;
Kr Not

}
/*WAP to illustrate the add/view/delete/update and Exit record form file*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct employee
{
char name[25];
int salary;
};

int main()
{
struct employee e;
FILE *fp,*fp1;
char name[50],ch='y';
int n,i,j,k,salary;
while(ch=='y')
{
printf("\n\n\n\n");
printf("1. Data Entry\n");
printf("2. View Records\n");
printf("3. Search Record\n");
printf("4. Delete Record\n");
printf("5. Update Record\n");
printf("6. Exit\n");
printf("Enter Your Choice[1-6]");
scanf("%d",&n);
switch(n)
{
case 1:
{
fp=fopen("test1.txt","a");
fflush(stdin);
printf("\n Enter First Name:");
gets(e.name);

ar :
ch by
printf("\n Enter Salary:");

ya
scanf("%d",&e.salary);
. A ed
fwrite(&e,sizeof(e),1,fp);
fclose(fp);
Pd ar

}
a ep

break;
hn pr

case 2:
{
is e

fp=fopen("test1.txt","r");
Kr Not

printf("\nName\t\tSalary\n");
printf("-----\t\t------\n");
while(fread(&e,sizeof(e),1,fp)==1)
printf("%s \t%d\n",e.name,e.salary);
fclose(fp);
}
break;
case 3:
{
i=0;
fp=fopen("test1.txt","r");
fflush(stdin);
printf("Enter name for Search:");
gets(name);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(name,e.name)==0)
{
printf("%s \t%d\n",e.name,e.salary);
i++;
}
}
if(i==0)
printf("Record not Exist\n");
fclose(fp);
break;
}
case 4:
{
j=0;
fp=fopen("test1.txt","r");
fp1=fopen("temp.txt","w");
fflush(stdin);
printf("Enter name for Delete:");
gets(name);
while(fread(&e,sizeof(e),1,fp)==1)
{

ar :
ch by
if(strcmp(name,e.name)==0)

ya
j++;
. A ed
else
fwrite(&e,sizeof(e),1,fp1);
Pd ar

}
a ep

if(j==0)
hn pr

printf("Record not Exist\n");


else
is e

printf("Such Record is deleted.");


Kr Not

fclose(fp);
fclose(fp1);
remove("test1.txt");
rename("temp.txt","test1.txt");
}
break;
case 5:
{
k=0;
fp=fopen("test1.txt","r");
fp1=fopen("temp.txt","w");
fflush(stdin);
printf("Enter name for Update:");
gets(name);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(name,e.name)==0)
{
fflush(stdin);
printf("\n Enter First Name:");
gets(name);
printf("\n Enter Salary:");
scanf("%d",&salary);
strcpy(e.name,name);
e.salary=salary;
fwrite(&e,sizeof(e),1,fp1);
k++;
}
else
fwrite(&e,sizeof(e),1,fp1);
}
if(k==0)
printf("Record not Exist\n");
else
printf("Record has been updated.");
fclose(fp);
fclose(fp1);

ar :
ch by
remove("test1.txt");

ya
rename("temp.txt","test1.txt");
. A ed
}
break;
Pd ar

case 6:
a ep

{
hn pr

exit(1);
break;
is e

}
Kr Not

default:
printf("Worng Choice!! option are [1-6]");
}
}
getch();
return 0;
}
--------------
/*Program sturucture passing to a fuction*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct personal
{
char name[20];
int jdt;
int salary;
} p[100];
void printdetail( struct personal pt[])
{
int i;
for(i=0;i<2;i++)
printf("\nName: %s \t \nPrice: %d \t \nPage: %d \t\n",pt[i].name,pt[i].jdt,pt[i].salary);
}
int main()
{
int i;
printf("Enter persional details (Name,Jdt,Salaru)\n");
for(i=0;i<2;i++)
scanf("%s%d%d",p[i].name,&p[i].jdt,&p[i].salary);
printdetail(p);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>

ar :
ch by
#include<string.h>

ya
#include<stdlib.h>
. A ed
struct employee
{
Pd ar

char empid[20],name[25],post[25];
a ep

int salary;
hn pr

} e[100];
is e

int main()
Kr Not

{
int i,j,n,tmp;
char temp[25],temp1[25],temp2[25];
printf("How many Student\n");
scanf("%d",&n);

printf("Enter Employee details (EmployeeID,Name,Post,Salary)\n");


for(i=0;i<n;i++)
//scanf("%s%d",p[i].name,&p[i].age);
scanf("%s%s%s%d\n",e[i].empid,e[i].name,e[i].post,&e[i].salary);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(e[i].empid,e[j].empid)>0)
{
/*empid*/
strcpy(temp,e[i].empid);
strcpy(e[i].empid,e[j].empid);
strcpy(e[j].empid,temp);
/*Name*/
strcpy(temp1,e[i].name);
strcpy(e[i].name,e[j].name);
strcpy(e[j].name,temp1);
/*Post*/
strcpy(temp2,e[i].post);
strcpy(e[i].post,e[j].post);
strcpy(e[j].post,temp2);
/*salary*/
tmp=e[i].salary;
e[i].salary=e[j].salary;
e[j].salary=tmp;
}
}
}
for(i=0;i<n;i++)
printf("\nEmpID: %s \t \nName: %s \t \nPost: %s \t

ar :
ch by
\nSalary:%d\n",e[i].empid,e[i].name,e[i].post,e[i].salary);

ya
getch();
. A ed
return 0;
}
Pd ar

/*
a ep

WAP that illustrate the reading/writinng operaton in structre of two employee


hn pr

*/
#include<stdio.h>
is e

#include<conio.h>
Kr Not

#include<string.h>
#include<stdlib.h>
struct personal
{
char name[20];
int jdt;
int salary;
} p[100];
int main()
{
int i;
printf("Enter persional details (Name,Jdt,Salaru)\n");
for(i=0;i<2;i++)
scanf("%s%d%d",p[i].name,&p[i].jdt,&p[i].salary);

for(i=0;i<2;i++)
printf("\nName: %s \t \nPrice: %d \t \nPage: %d \t\n",p[i].name,p[i].jdt,p[i].salary);
getch();
return 0;
}

/*
WAP to input student details(Name,Age) for five student then sort them
on the base of name in alphabetic order with use of structre
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
char name[20];
int age;
} p[100];
int main()
{
int i,j,tmp;

ar :
ch by
char temp[25];

ya
printf("Enter student details(Name,Age) for five student\n");
. A ed
for(i=0;i<5;i++)
scanf("%s%d",p[i].name,&p[i].age);
Pd ar
a ep

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

{
for(j=i+1;j<5;j++)
is e

{
Kr Not

if(strcmp(p[i].name,p[j].name)>0)
{
strcpy(temp,p[i].name);
strcpy(p[i].name,p[j].name);
strcpy(p[j].name,temp);

tmp=p[i].age;
p[i].age=p[j].age;
p[j].age=tmp;
}
}
}

for(i=0;i<5;i++)
printf("\nName: %s \t \nAge: %d \t \n",p[i].name,p[i].age);
getch();
return 0;
}
/*
write a menu driven program with following option
1. Add Record
2. Display Records
3. Exit
Enter your choice[1..4]
if user select option 1 it should add record like studeent_name,class,roll
into file called 'myfile.txt'
if user select option 2 then
program should display all record in files
if user select option 3 then
close the program
*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
FILE *fp;

ar :
ch by
int n,roll,clas;

ya
char name[25];
. A ed
while(1)
{
Pd ar

printf("*****Main Menu******\n");
a ep

printf("1.Add Record\n");
hn pr

printf("2.Display Record\n");
printf("3.Exit\n");
is e

printf("Enter Your Choice[1-3]");


Kr Not

scanf("%d",&n);
switch(n)
{
case 1:
{
fp=fopen("myfile.txt","a");
fflush(stdin);
printf("Enter Student Name\n");
gets(name);
printf("Enter Class\n");
scanf("%d",&clas);
printf("Enter Rollno\n");
scanf("%d",&roll);
fprintf(fp,"%s %d %d\n",name,clas,roll);
fclose(fp);
}
break;
case 2:
{
fp=fopen("myfile.txt","r");
printf("Name:\tClass:\t%RollNo:\n");
while(fscanf(fp,"%s%d%d",name,&clas,&roll)!= EOF)
printf("%s\t%d\t%d\n",name,clas,roll);
fclose(fp);
}
break;
case 3:
exit(1);
default:
printf("Wrong Choice..\n");
}
}
getch();
return 0;
}

/*wrie a program that read a line of text and

ar :
ch by
count

ya
No. of Vowels
. A ed
No. of Consonants
No. of Digit
Pd ar

No. of White Spaces;


a ep

No. of Special Charater


hn pr

With use of Pointer


*/
is e

#include<stdio.h>
Kr Not

#include<conio.h>
#include<string.h>
int main()
{
int vow=0,cons=0,digit=0,wspace=0,other=0;
char text[100],*text1;
printf("Line of Text\n");
gets(text);
text1=&text[0];
while(*text1 !='\0')
{
if( (*text1=='A'|| *text1=='a') ||
(*text1=='E'|| *text1=='e') ||
(*text1=='I'|| *text1=='i') ||
(*text1=='O'|| *text1=='o') ||
(*text1=='U'|| *text1=='u')
)
vow++;
else if ((*text1>='A' && *text1 <= 'Z') ||
(*text1>='a' && *text1 <= 'z')
)
cons++;
else if ((*text1>='0') && (*text1<='9'))
digit++;
else if (*text1== ' ' || *text1=='\t')
wspace++;
else
other++;
text1++;
}
printf("No. of Vowels:%d\n",vow);
printf("No. of Consonants:%d\n",cons);
printf("No. of Digit:%d\n",digit);
printf("No. of White Spaces:%d\n",wspace);
printf("No. of Special Charater:%d\n",other);
getch();
return 0;

ar :
ch by
}

ya
. A ed
/*Write a program input 10 integers and calculate sum reading from file then display result.
*/
Pd ar

#include<stdio.h>
a ep

#include<conio.h>
hn pr

#include<string.h>
int main()
is e

{
Kr Not

int i,n,sum=0;
FILE *fp,*fod,*fev;
fp=fopen("mdata.txt","w");
printf("Enter 10 integer one by one\n");
for(i=0;i<10;i++)
{
scanf("%d",&n);
putw(n,fp);
}
fclose(fp);
fp=fopen("mdata.txt","r");
while((n=getw(fp))!=EOF)
sum=sum+n;
fclose(fp);
printf("Sum=%d",sum);
getch();
return 0;
}
Arc function in c
Declaration :- void arc(int x, int y, int stangle, int endangle, int radius);
arc function is used to draw an arc with center (x,y) and stangle specifies starting angle, endangle specifies
the end angle and last parameter specifies the radius of the arc. arc function can also be used to draw a circle
but for that starting angle and end angle should be 0 and 360 respectively
#include<graphics.h>
#include<conio.h>
main()
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
arc(100, 100, 0, 135, 50);
getch();
closegraph();
return 0;
}
Declaration :- void bar(int left, int top, int right, int bottom);
#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
bar(100, 100, 200, 200);
getch();
closegraph();

ar :
return 0; ch by
ya
}
Declaration :- void circle(int x, int y, int radius);
. A ed

circle function is used to draw a circle with center (x,y) and third parameter specifies the radius of the circle.
The code given below draws a circle.
Pd ar

#include<graphics.h>
a ep

#include<conio.h>
main()
hn pr

{
int gd = DETECT, gm;
is e

initgraph(&gd, &gm, "C:\\TC\\BGI");


Kr ot

circle(100, 100, 50);


N

getch();
closegraph();
return 0;
}
line function in c
line function is used to draw a line from a point(x1,y1) to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points
of the line.The code given below draws a line.
Declaration :- void line(int x1, int y1, int x2, int y2);
C programming code for line
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
line(100, 100, 200, 200);
getch();
closegraph();
return 0;
}
setbkcolor function in c
Declaration :- void setbkcolor(int color);
setbkcolor function changes current background color e.g. setbkcolor(YELLLOW) changes the current
background color to YELLOW.
Remember that default drawing color is WHITE and background color is BLACK.
C programming code for setbkcolor

Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]


#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
outtext("Press any key to change the background color to GREEN.");
getch();
setbkcolor(GREEN);
getch();
closegraph();
return 0;
}
setcolor function in c
Declaration :- void setcolor(int color);
In Turbo Graphics each color is assigned a number. Total 16 colors are available. Strictly speaking number
of available colors depends on current graphics mode and driver.For Example :- BLACK is assigned 0, RED
is assigned 4 etc. setcolor function is used to change the current drawing color.e.g. setcolor(RED) or
setcolor(4) changes the current drawing color to RED. Remember that default drawing color is WHITE.
C programming code for setcolor
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
ar :
circle(100,100,50);
ch by
/* drawn in white color */

ya
setcolor(RED);
. A ed

circle(200,200,50); /* drawn in red color */


getch();
Pd ar

closegraph();
return 0;
a ep

}
hn pr

setfillstyle function in c
setfillstyle function sets the current fill pattern and fill color.
is e

Declaration :- void setfillstyle( int pattern, int color);


Kr ot

Different fill styles:


N

enum fill_styles
{
EMPTY_FILL,
SOLID_FILL,
LINE_FILL,
LTSLASH_FILL,
SLASH_FILL,
BKSLASH_FILL,
LTBKSLASH_FILL,
HATCH_FILL,
XHATCH_FILL,
INTERLEAVE_FILL,
WIDE_DOT_FILL,
CLOSE_DOT_FILL,
USER_FILL
};
C programming source code for setfillstyle
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
setfillstyle(XHATCH_FILL, RED);
circle(100, 100, 50);
floodfill(100, 100, WHITE);
getch();
closegraph();

Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]


return 0;
}
settextstyle function in c
Settextstyle function is used to change the way in which text appears, using it we can modify the size of text,
change direction of text and change the font of text.
Declaration :- void settextstyle( int font, int direction, int charsize);
font argument specifies the font of text, Direction can be HORIZ_DIR (Left to right) or VERT_DIR
(Bottom to top).
Different fonts
enum font_names
{
DEFAULT_FONT,
TRIPLEX_FONT,
SMALL_FONT,
SANS_SERIF_FONT,
GOTHIC_FONT,
SCRIPT_FONT,
SIMPLEX_FONT,
TRIPLEX_SCR_FONT,
COMPLEX_FONT,
EUROPEAN_FONT,
BOLD_FONT
};
programming source code for settextstyle
#include <graphics.h>

ar :
#include <conio.h> ch by
ya
main()
{
. A ed

int gd = DETECT, gm, x = 25, y = 25, font = 0;


initgraph(&gd,&gm,"C:\\TC\\BGI");
Pd ar

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


a ep

{
settextstyle(font, HORIZ_DIR, 1);
hn pr

outtextxy(x, y, "Text with different fonts");


y = y + 25;
is e

}
Kr ot

getch();
closegraph();
N

return 0;
}
ellipse function in c
Declarations of ellipse function :-
void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);
Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, stangle is the starting angle,
end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse. To
draw a complete ellipse strangles and end angle should be 0 and 360 respectively.
C programming code for ellipse
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
ellipse(100, 100, 0, 360, 50, 25);
getch();
closegraph();
return 0;
}
rectangle function in c
Declaration :- void rectangle(int left, int top, int right, int bottom);
rectangle function is used to draw a rectangle. Coordinates of left top and right bottom corner are required to
draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top

Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]


left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of
right bottom corner. The code given below draws a rectangle.
c programming code for rectangle
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;

initgraph(&gd, &gm, "C:\\TC\\BGI");


rectangle(100,100,200,200);
getch();
closegraph();
return 0;
}
outtextxy function in c
outtextxy function display text or string at a specified point(x,y) on the screen.
Declaration :- void outtextxy(int x, int y, char *string);
x, y are coordinates of the point and third argument contains the address of string to be displayed.
C programming code for outtextxy
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");

ar :
outtextxy(100, 100, "Outtextxy function");
ch by
ya
getch();
. A ed

closegraph();
return 0;
Pd ar

}
ellipse function in c
a ep

Declarations of ellipse function :-


hn pr

void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);
Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, stangle is the starting angle,
is e

end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse. To
Kr ot

draw a complete ellipse strangles and end angle should be 0 and 360 respectively.
N

C programming code for ellipse


#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
ellipse(100, 100, 0, 360, 50, 25);
getch();
closegraph();
return 0;
}
#include<stdio.h>
#include<conio.h>
main()
{
textbackground(RED);
cprintf("C program to change background color.");

getch();
return 0;
}
drawpoly function in c
Drawpoly function is used to draw polygons i.e. triangle, rectangle, pentagon, hexagon etc.
Declaration :- void drawpoly( int num, int *polypoints );

Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]


num indicates (n+1) number of points where n is the number of vertices in a polygon, polypoints points to a
sequence of (n*2) integers . Each pair of integers gives x and y coordinates of a point on the polygon. We
specify (n+1) points as first point coordinates should be equal to (n+1)th to draw a complete figure.
To understand more clearly we will draw a triangle using drawpoly, consider for example the array :-
int points[] = { 320, 150, 420, 300, 250, 300, 320, 150};
points array contains coordinates of triangle which are (320, 150), (420, 300) and (250, 300). Note that last
point(320, 150) in array is same as first. See the program below and then its output, it will further clear your
understanding.
C program for drawpoly
#include <graphics.h>
#include <conio.h>
main()
{
int gd=DETECT,gm,points[]={320,150,420,300,250,300,320,150};
initgraph(&gd, &gm, "C:\\TC\\BGI");
drawpoly(4, points);
getch();
closegraph();
return 0;
}
fillpoly function in c
Fillpoly function draws and fills a polygon. It require same arguments as drawpoly.
Declaration :- void drawpoly( int num, int *polypoints );
For details of arguments see drawpoly.
ar :
ch by
fillpoly fills using current fill pattern and color which can be changed using setfillstyle.
C programming code
ya
. A ed

#include <graphics.h>
#include <conio.h>
Pd ar

main()
{
a ep

int gd=DETECT,gm,points[]={320,150,440,340,230,340,320,150};
hn pr

initgraph(&gd, &gm, "C:\\TC\\BGI");


fillpoly(4, points);
is e

getch();
Kr ot

closegraph();
return 0;
N

}
traffic light program in c, traffic light simulation
Traffic light Simulation: Traffic light program in c presents what happens in our daily life at traffic light
signals. Firstly user will press a key to start the traffic light simulation.
C programming code
#include<graphics.h>
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
main()
{
int gd = DETECT, gm, midx, midy;
initgraph(&gd, &gm, "C:\\TC\\BGI");
midx = getmaxx()/2;
midy = getmaxy()/2;
setcolor(RED);
settextstyle(SCRIPT_FONT, HORIZ_DIR, 3);
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy-10, "Traffic Light Simulation");
outtextxy(midx, midy+10, "Press any key to start");
getch();
cleardevice();
setcolor(WHITE);
settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy-50, 22);
setfillstyle(SOLID_FILL,RED);
floodfill(midx, midy-50,WHITE);
Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]
setcolor(BLUE);
outtextxy(midx,midy-50,"STOP");
delay(2000);
graphdefaults();
cleardevice();
setcolor(WHITE);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy, 20);
setfillstyle(SOLID_FILL,YELLOW);
floodfill(midx, midy,WHITE);
setcolor(BLUE);
outtextxy(midx-18,midy-3,"READY");
delay(2000);
cleardevice();
setcolor(WHITE);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy+50, 22);
setfillstyle(SOLID_FILL,GREEN);
floodfill(midx, midy+50,WHITE);
setcolor(BLUE);
outtextxy(midx-7,midy+48,"GO");
setcolor(RED);
settextstyle(SCRIPT_FONT, HORIZ_DIR, 4);
outtextxy(midx-150, midy+100, "Press any key to exit...");
getch();
closegraph();
return 0;

ar :
}
ch by
ya
C program to move a car
. A ed

Program in c using graphics move a car. A car is made using two rectangles and two circles which act as
tyres of car. A for loop is used to move the car forward by changing the rectangle and circle coordinates and
Pd ar

erasing the previous contents on screen using clearviewport, you can also use cleardevice. Speed of car can
a ep

be adjusted using delay function, more the delay lesser will be the speed or lesser the delay your car will
move fast. In this program color of the car also keeps on changing, this is accomplished by incrementing the
hn pr

color value by one each time in for loop, you can also use random function for this purpose. Before you see
is e

a car moving you will be asked to press a key.


Kr ot

C programming code
N

#include <graphics.h>
#include <dos.h>
#include <conio.h>
main()
{
int i, j = 0, gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
outtextxy(25,240,"Press any key to view the moving car");
getch();
setviewport(0,0,639,440,1);
for( i = 0 ; i <= 420 ; i = i + 10, j++ )
{
rectangle(50+i,275,150+i,400);
rectangle(150+i,350,200+i,400);
circle(75+i,410,10);
circle(175+i,410,10);
setcolor(j);
delay(100);
if( i == 420 )
break;
clearviewport();
}
getch();
closegraph();
return 0;
}
Program to see ip address in client program
#include<stdlib.h>
Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]
main()
{
system("C:\\Windows\\System32\\ipconfig");
system("pause");
return 0;
}
C programming code for Windows XP
#include <stdio.h>
#include <stdlib.h>
main()
{
char ch;
printf("Do you want to shutdown your computer now (y/n)\n");
scanf("%c",&ch);
if (ch == 'y' || ch == 'Y')
system("C:\\WINDOWS\\System32\\shutdown -s");
return 0;
}
C programming code for Windows 7
#include <stdio.h>
#include <stdlib.h>
main()
{
char ch;
printf("Do you want to shutdown your computer now (y/n)\n");
scanf("%c",&ch);

ar :
if (ch == 'y' || ch == 'Y') ch by
ya
system("C:\\WINDOWS\\System32\\shutdown /s");
return 0;
. A ed

}
To shutdown immediately use "C:\\WINDOWS\\System32\\ shutdown /s /t 0". To restart use /r instead of /s.
Pd ar
a ep
hn pr
is e
Kr ot
N

Note prepared By Krishna Prasad Acharya[MCA/BCA/B.Ed]


LAB SHEET:- 1
1.WAP to print the “Hello world” on the screen.

2.WAP to print the name, address and roll no. on the screen. (Use different escape sequences to format the output on the

screen like: \n, \t).

3. WAP to find sum, difference, product and division (quotient & remainder) of two any numbers and display the results.

4.WAP to convert temperature given in Fahrenheit to Celsius. [C/100= (F-32)/180].

5.WAP to calculate the area of circle.(without taking input from the user)

6. WAP to input the radius of a circle, and calculate the area and circumference of the circle.

7. WAP to input the length & breadth of a rectangle, and calculate the area of the rectangle.

8. WAP to input principle amount, no. of years and rate of interest from user and calculate the simple

interest.[SI=PNR/100]

9.WAP to input the temperature from the user and convert temperature given in Fahrenheit to Celsius. [C/100= (F-

ar :
ch by
ya
32)/180].
. A ed
10. WAP to input the values of a & b and calculate the cube of (a + b).
Pd ar

11. WAP to input the radius and height of the cylinder and find the total surface area.[S=2 * PI * r * (r + h)]
a ep

12. WAP to read three sides of a triangle. Calculate the area.


hn pr

[Hint: ∆2= s(s-a) (s-b) (s-c), 2s= (a + b + c)]


is e

13. Find the square root of a number given by user.


Kr Not

[Hint: Use function sqrt (variable name) and #include<math.h>]

14. WAP to read and b. Calculate (ab), a to the power b.

[Hint: Use function pow(variable name, power), and #include<math.h>]

15. WAP to calculate compound interest for the given principle, no. of years and rate of interest.[Hint:

n
C=P[(1 + r/100) -1] ]
16. WAP to exchange two numbers.

17. WAP to calculate: [A] (a + b) / (c + d) [B] √(a b) / ( c + d ) [C] 5


( (a-b) /(c*c*d) )
[D] ( ( a + b ) / c ) / ( a-( b / d ) )
18. A computer manufacturing company has the following monthly compensation policy to their sales person:
Minimum base salary=1500.00

Bonus for every computer sold=200.00

Commission on the total monthly sales=2%

Since the prices of computers are changing, the sales price of each computer is fixed at the beginning of

every month.

Given the base salary, bonus and commission rate, the inputs necessary to calculate the gross salary are, the price

of each computer and the number sold during the month.

The gross salary is given by the equation:

Gross salary = Base salary + (quantity * bonus rate) + (quantity * price) * commission rate.

19. In inventory management, the economic order quantity for a single item is given

by: EOQ =√ (2* demand rate * setup costs)/ (holding cost per item per unit time)

ar :
ch by
ya
And the optional time between orders is given by:
. A ed
TBO = √ (2 * setup costs)/ (demand rate * holding cost per item per unit time)
Pd ar

WAP to compute EOQ and TBO, given demand rate, setup costs and the holding cost.
a ep

20. The straight- line method of computing the yearly depreciation of the value of an item is given by: Depreciation
hn pr

= (Purchase price-salvage value) / Years of service.


is e
Kr Not

21. Solve the quadratic equation A x 2+ b x + c=0. [Assume all roots are real only]

LAB SHEET:-
2

1. WAP to read a 3 digit no. and print each digit separately.

2. WAP to read four digit no. & print the sum of each digit.

3. WAP to read 3 digit no. & find sum of square of digits.

4. WAP to read 3 digit no. & find if it is palindrome or not. Hint: use ternary operator.

5. WAP to read no. of days & print in terms of year, months & days.

6. WAP to read total no. of seconds and print it in hours, minutes and second.

7. WAP to read a no. & find out if it is Armstrong no. or not. Hint: N=a3+b3+c3

8. WAP to input two points A(x1,y1) & B(x2,y2) and find the distance between them. Hint: AB= sqrt [ (x1-x2)2 - (y1-

y2)2 ] .

9. WAP to input the coefficient of simultaneous equation and find the values of x, y.
a1x+b1y+c1=0, a2x+b2y+c2=0 ,

x=(b2*c1-b1*c2)/(b2*a1-a2*b1) and y=(c2*a1-c1*a2)/(b2*a1-a2*b1).

10. WAP to read a no. and find if the no. is even or odd.

11. WAP to read 3 no. and display the greatest no. (use ternary operator).

12. WAP to read 2 no.s , if the first no. is greater than second no. ,display the sum else display the product of two no.s
(use ternary operator).

13. WAP to input four no.s and display the greatest no.

14. WAP to prnt the absolute value of a no. input by the user.

15. WAP to find if the given no. is positive or negative (use ternary operator).

LAB SHEET:- 3

1. WAP that identifies whether the given number is odd or even.

2. WAP that takes three numbers and prints the largest number.

ar :
ch by
ya
3. Solve the quadratic equation: Ax2+Bx+C. (print imaginary roots also)
. A ed
4. WAP to print the day depending upon the number inputted by the user.
Pd ar

5. WAP that asks the user to enter his/her marks of subjects and prints the corresponding grade.
a ep

Grade Table: >=80: A, >=60: B, >=50: C, >=40: D, <40: F.


hn pr

6. WAP that reads a year from user and find if the year is a leap year. (Year%4)
is e
Kr Not

7. WAP to calculate sum, difference, multiple, division of two numbers. (Use if else statement)

8. WAP to print day depending on the number input by user. (Use switch case)

9. A program should be able to calculate sum, difference, product, division of two numbers. Your program should

display the list of options from which user selects one of them. (Use switch case)

a. Add b. Subtract c. Product d. Division

Enter your choice: 2

10. WAP to read three sides of triangle and check the validity of triangle, also decide the type of triangle.

(Isosceles, equilateral, right angle) [If a, b, c are sides of a triangle then, a+b>c or b+c>a or a+c>b ]

11. WAP that read one character and convert it into upper character case, if it is in lower case and vice versa.

(ASCII code for A=65, Z=90, a=97, z=122)

12. WAP to read a character and check if it is a digit, alphabet or special character.

13. WAP to read five numbers and find the largest number.

14. WAP to read three numbers and print the middle number.
15. WAP to read Annual Salary of an employee and decide tax withheld as follows:

Salary tax

Up to 100000 0%
Up to 150000 15%
Above 150000 25%
LAB SHEET:-4 (Looping)

1. WAP that prints the numbers from 201 to 300(use while loop, do while loop, for loop).

2. WAP that finds the sum of odd numbers from 0 to 100.(use do- while loop)

i.e. sum=1+3+….+99

3. WAP which display the average & sum of nth no input by the user.

4. WAP to read a number and display the multiplication table of that number.

5. WAP that reads two numbers x and y from user and calculates the value of x to the power y. (while loop, for

loop)

ar :
ch by
6. WAP that reads a number (n) from user and calculates the factorial of that number.(using while, for)

ya
. A ed
7. WAP that checks whether the given number(x) is prime or not.[Hint: prime no. is that number which is NOT
Pd ar

divisible by numbers other than 1 and itself. (Using while, for)


a ep

8. WAP to solve the quadratic equation.


hn pr

9. WAP to input the number and find the sum of each digits of number.
is e

10. WAP to read number and find whether the given number is Armstrong or not.
Kr Not

11. WAP to read a number and find whether the given number is palindrome or not.

12. WAP to find the leap year between 1900 and 2000.

13. WAP to accept any number „n‟ and print the cube of all numbers from 1 to n which is exactly

divisible by 3.

14.WAP to find all the prime numbers between 1 to 100.

15.WAP to find all the Armstrong number between 100 to 500.

16.WAP to read the age of 20 persons and count the number of persons in the age group 50 to 60.

17.WAP to generate the Fibonacci series.[0 1 1 2 3 5 8………….]

18. WAP that generates the multiplication as shown below. [Use nested looping] (Using while, for)

1 2 3 4 5 6 7 8 9 10

2 4 6 7 8 10 14 16 18 20

…………………………………
…………………………………

10 20 30 40 50 60 70 80 90 100

19. WAP to generate the following output

a) b)

1 1

12 22

123 333

1234 4444

12345 55555

c) d)

1 *****

ar :
ch by
ya
10 ****
. A ed
101 ***
Pd ar

1010 **
a ep

*
hn pr

e)
is e

*
Kr Not

**

***

****
20. WAP to find the result of following series.

 Sum = 11 + 22 + 33 + 44 + …………..till „n‟ terms

 Sum = 1/x + 2/x2 + 3/x3 + 4/x4……….till “n” terms

 Sum = 1/x + 2/x3 + 3/x5 + 4/x7……….till “n” terms

 Sum = 1/2 + 3/4 + 5/6 +7/8 + ………till “n” terms

LAB SHEET:-5 (Function)

1. WAP to read a number „n‟ and calculate its cube using function:

a. No argument and no return type. b.

Argument and no return type.

c. Argument and return type.

2. WAP that calls a function called getarea(). This function is responsible for reading two integer

ar :
ch by
numbers(length and breadth) and print the area of rectangle.

ya
. A ed
a. Argument and no return type. b.
Pd ar

Argument and return type.


a ep

3. WAP that calls a function named interest(). This function takes the values of principal, number of years and
hn pr

rate of interest as argument and returns the calculated interest.


is e

4. WAP to read a no. „n‟ and print its square using function.
Kr Not

5. WAP to read l,b,h of a rectangle and print its volume using all four category of function.

6. WAP to read two no. and print the largest no. using function.

7. WAP to read a character and convert it into upper case if it is lowercase and vice versa.

8. WAP that calls a function named as area(). This function takes the radius of the circle and returns the area

of the circle.

9. WAP to read a no. „n‟ from user and print your name „n‟ times using function.

10. WAP to read a no. „n‟ and print the sum of natural numbers from 1 to n using function.

11. WAP to read a no. „n‟ and print its multiplication table using function(mul).

12. Write a menu driven program and perform the following operation:

a) reverse the number.

b) to find if given no. is prime or not.

c) to get the sum of digit of a given no.


Lab Sheet for BCA II Sem. for GM College Prepared by Krishna Acharya[BCA/MCA] 2011

d) to find if the given no. is palindrome or not.


13. WAP that calls a function whose name is power(). This function takes two arguments(x and y) and returns the

value of x to the power y.

14. WAP that use a function called isprime(). This function takes a no. as an argument and returns either 0 or

1. The function returns 1 if the given argument is prime otherwise 0.

15. WAP that calls a function whose name is mul(). This function takes one argument(x) and prints the

multiplication table of that no.

16. WAP that use a function called factorial(). This function takes a no. as an argument and returns the

factorial value of that no.

17. WAP that use function swap two given values. The swap() should returns nothing (void). Hint:

use (a)call by value and (b) call by reference.

Recursive Method

ar :
ch by
18. WAP to find the factorial of the no. using recursive function.

ya
. A ed
19. WAP to find the sum of given non-negative integer using a recursive function.
Pd ar

20. WAP to find the value of x to the power y using recursive function.
a ep

21. WAP to print “Hello” „n‟ times using recursive function.


hn pr

LAB SHEET:-6 (array)


is e
Kr Not

1.WAP to enter values in array called myarray of size 15 and display the elements of array.

2.WAP to sum and average of all the elements of array.

3.WAP to add two arrays and put in third array.

4.WAP to find largest and smallest element in an array.

5.WAP to print Fibonacci series.

6.WAP to separate odd and even elements of array.

7.WAP that initialize ten numbers and search the key (a number given by the user)from the list .If the key is

found then it displays the index(subscript of an array)otherwise it displays the proper message

i.e. "key is not found".

8.WAP to sort the given list of numbers.

9.WAP that reads two matrices of size N*N and prints the sum and difference of those matrices.

10.WAP that reads two matrices of size N*N and prints the product of those matrices.
11.WAP that reads a matrix and identify if the given matrix is symmetric or not.
(array contd with functions)

1.WAP to read arry of 10 no.s and display it using array and function.

2.WAP to read array of 5 no.s and display:

(a) the largest no. using function and array.

(b) the smallest no. using function and array.

3.WAP to read two arrays, add two array and store the result in third array and print it using function.

4.WAP to read an array and sort it in ascending order.

5.WAP to read age of 'n' students and display the second lowest age.
(array contd. with 2d and 3d matrix)

1.WAP to input a 2d matrix and print it.

2.WAP to input two 2d matrix, add, subtract and print it.


3.WAP to input two 2d matrix, multiply and print it.

ar :
ch by
4.WAP to find transpose of 2d matrix.

ya
5.WAP to input a 3d matrix and print it
. A ed
LABSHEET-7(Pointers)
Pd ar
a ep

1.WAP using pointer to compute sum and average of elements of array.


hn pr

2.(a)WAP that takes two numbers from user and evalutes the sum,difference and product using pointer.
is e

(b)WAP that takes two numbers from user and evalutes the sum,difference and product using pointer and
Kr Not

function.

3.WAP using DMA and pointer to read n numbers from user and display sum and average.

4.(a)WAP to find largest and smallest number from list of number using pointer.

(b)WAP to find second and third largest number using pointer.

5.(a)WAP to sort n numbers in ascending order using pointer.

(b)WAP to sort n numbers in ascending order using pointer and function.

6.WAP to sort n numbers in ascending order using DMA and function.

7.WAP to merge two sorted array into third array using pointer.

1.WAP to read 2D-array (size 3*3) using pointer and diaplay it.

2.WAP to read two matrix of(size 3*3),add it and store in 3rd marix using pointer& function.

3.WAP to read two matrix of(size 3*3),multiply it and store in 3rd marix using pointer& function.

4.WAP to read 3D-array of size 2*2*2 and print it.


//WAP to check palindrome of string using pointer.

//WAP to count vowels and constants in a line of text using pointer.

pointer and string

1.WAP to read an array of integers and print its element in reverse order.

2.WAP to find the length of given string.

3.WAP to find total number of vowels present in the string.

4.WAP that read two matrices and use pointer to sum them.

5.Using a pointer, WAP that finds out the largest number from the given list of numbers.
6.WAP using recursion and pointer that prints the given string in reverse order.

7.WAP that uses pointer to check whether a given string is a palindrome.


Labsheet-8(string)

1.WAP that accepts a line from user & prints it in upper case.(use gets to read line)

ar :
ch by
ya
2.WAP to check if two string are equal or not.(do not use strcmp)
. A ed
3.WAP to read a string & find out the length of string.(do not use strlen)
Pd ar

4.WAP to input a string & reverse the string.


a ep

5.WAP to read a line of text & count the no. of words & characters in the line.
hn pr

6.WAP to read a line of text & count the no. of digits,uppercase & lowercase characters in the line.
is e

7.WAP that reads a string & checks if it is a palindrome.


Kr Not

8.WAP to sort an array of string.

9.WAP to read a line of text & print each character of the text in reverse case. i.e. print lowercase if it is in

uppercase & viceversa.

1.WAP to read a string & find the length using strlen().

2.WAP to check if two string are equsl or not.

3.WAP to read 2 strings, join it and display it using strcat().

4.WAP to read name of 10 persons,sort it & display it.

5.WAP to read a line of text & print each character,print in reverse case (use toupper() & tolower(),<ctype.h>).

LABSHEET-9(structure)

a.WAP to read a record of a person & display it.Include: Name,age,roll no,address,marks of 5 subjects.

1.WAP to read a record of 5 students and print the records of student.

The record should include:Name,Age,Roll no.


2.WAP to read a record of 5 students and print the records of student according to the roll number (in ascending

order). The record should include:Name,Age,Roll no.

3.Repeat the Question no.1 and print the record according to name in alphabetical order.

4.WAP to make nested structure.put a structure(date of birth) within structure record.

5.WAP to pass a structure to a function.

6,WAP to read record of 5 employee of an office and print the record of person who have 2nd higest salary.

1.WAP to make a record of 5 students & print.(name,roll,age)

2.WAP to make record of 5 student.(name,follno marks of 3 subjects &print total)

3.WAP to make nested structure .put structure DOB within 1st structure.

4.WAP to read record of 5 employee & print the record of person which have highest & lowest

salary.(Include:name,salary,address)

ar :
1.WAP to make a record of a a student using pointer to structure.( p->name,(*p).name)

ch by
ya
2.WAP to make a record of 5 students using structure array and pointer.
. A ed
3.WAP to use pointer as a member of structure.
Pd ar
a ep

4.WAP to pass structure to function (no pointer).


hn pr

5.WAP to pass structure to function using pointer.


Lab 10(files)
is e
Kr Not

1.WAP to read character from keyboard and store in file, read it from file and display it on the screen

2.WAP to read character until the enter key is pressed and change all character to upper case and display it.

3.WAP to read name and age from the user in the user defined file and print it.

4.WAP to copy characters from one file to another file.

(1)WAP to read a simple structure and put it into a file and display on screen.

(2)WAP to make a record and put it into a file and display on screen.

(3)WAP to make menu-based program using file to append,read,delete data in file.

Use switch for append,read,delete,quit.


xyz Multiple College 2013
message should be displayed like “Record does not
exist”
Bachelor of Computer Application (BCA)/First semester/End-term 3. While user select option 2, it should able to search the
Examination item and display into screen.
Time: 3:00 Hrs. Full marks: 60/Pass: 24 4. Option 4 is to exit program.
Subject: C programming
Candidates are required to give their answers in their own words Group B
as far as practicable. Figure in the margin indicate Full marks. Answer any six 6X6=36
Attempt any two Questions 2X12=24 4. What do you mean by operator? Discuss the different types of
1. What is array? Write a program to input name, rollno, and operator with example.
marks in five subjects into arrays and calculate total, 5. Differentiate between iteration and recursion. Write a program to
percentage, result, grade and display corresponding result into calculate sum of following series with use of recursion for
screen. It should obey the following rules. factorial.
1. Result [pass or failed] based on marks. if marks Greater 2 3
than 40 in each subject considered as passed else failed. X+X /2! +X /3! + ………………. +n term.

ar :
ch by
2. Grade is based on percentage. 6. Differentiate between function call by value and function call

ya
Per grade by reference with suitable diagram and list down the

. A ed
>=80 A disadvantage of pointer.
7. Write a program to input line of text and then count the

Pd ar
>=60 and <80 B
>=50 and <60 C following with use of pointer.

a ep
>=40 and <50 D 1. Number of alphabets

hn pr
<40 *** 2. Number of vowels.
2. Write a program to create a structure cricketer with name, 3. Number of consonants.
is e
country, bat_avg, ball_avg property and input data for ‘n’ 4. Number of digits
Kr Not
players then display the information of top 10 cricketer based 5. Number of space
on their batting average in descending order. 6. Number of special characters.
3. Write a menu driven program with following menu option. 8. What do you mean by static and dynamic memory management
****************My Menu******************* in c programming? Write a program to find out the minimum
1. Add Record. and maximum of number from list of 15 items using DMA.
2. Display all Records 9. Write a program for following output.
3. Search a Record
4. Exit
Enter your Choice [1...4]
******************************************* BCA 1stSem
Criteria:
1. While user select option 1 it should stored the
information into data file called student.dat in append
mode.
2. While user select option 2, it should display all record
in screen reading from file if not available then sensible

You might also like