Você está na página 1de 167

www.alljntuworld.

in

JNTU World

Mouse

Program Storage Area

Output
Storage
Area

Working Storage Area

Primary or Main Memory (RAM)

Input Devices

Input
Storage
Area

Monitor

or

Key board

ld

Computer -- Hardware

Register 1
Register 2

TU

Register N

Arithmetic
and
Logic Unit

JN

Micro Processor

Secondary Storage Devices

JNTU World

Printer

Output Devices

www.alljntuworld.in

JNTU World

JN

start

Flow chart:

TU

#include<stdio.h>
#include<conio.h>
main()
{
int num;
printf(Enter any number);
scanf(%d,&num);
if(num%2==0)
printf(%d is even,num);
else
printf(%d is odd,num);
}
(Program in C language)

or

ld

Algorithm: Step by step procedure of solving a particular problem.


Pseudo code: Artificial informal language used to develop algorithms.
Flow chart: Graphical representation of an algorithm.
Algorithm to find whether a number even or odd:
Step1: Begin
Step1: START
Step2: Take a number
Step2: Read num
Step3: if the number is divisible by2 then
Step3: if(num%2=0) then
print that number is even
print num is even
otherwise print that number is odd
otherwise
print num is odd
Step4: End
Step4: STOP
(Algorithm in natural language)
(Algorithm by using pseudo code)

read num
Yes

If
num%2=0

print num
is odd

print num
is even
stop
JNTU World

No

www.alljntuworld.in

JNTU World

ld

Flow chart symbols


Terminal

Parallegram

Input/output

or

Oval

Rectangle

Diamond

Decision

Connector

TU

Circle

Hard copy

Document

Process

Sub program

Hexagon

Iteration

Trapezoid

Manual Operation

Cylinder

Magnetic Disk Storage

JN

Double sided Rectangle

JNTU World

www.alljntuworld.in

JNTU World

entry
main,^m<r2>
sub12 #12,sp
jsb
C$MAIN_ARGS
moveb $CHAR_STRING_CON

or

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

#include<stdio.h>
int main(void)
{
int n1, n2,product;
printf(Enter two numbers : );
scanf(%d %d,&n1,&n2);
product = n1 * n2;
printf(%d,product);
return 0;
}

JN

1
2
3
4
5
6
7
8
9
1
0

00000000 00000100 0000000000000000


01011110 00001100 11000010 0000000000000010
11101111 00010110 0000000000000101
11101111 10111110 0000000000001011
11111000 10101101 11011111 0000000000010010
01100010 11011111 0000000000010101
11101111 00000010 11111011 0000000000010111
11110100 10101101 11011111 0000000000011110
00000011 10100010 11011111 0000000000100001
11101111 00000010 11011111 0000000000100100
01111110 11110100 10101101
11111000 10101110 11000101 0000000000101011
00000110 10100010 11111011 0000000000110001
11101111 00000010 11111011 0000000000110100
01010000 11010100 0000000000111011
00000100 0000000000111101

pusha1
pusha1
calls
pusha1
pusha1
calls
mull3
pusha
calls
clrl
ret

-8(fp)
(r2)
#2,SCANF
-12(fp)
3(r2)
#2,SCANF
-8(fp),-12(fp),6(fp)
#2,PRINTF
r0

TU

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

ld

Machine Language Assembly Language High-Level Language

The only language the computer can understand is machine


language (binary language).
A high level language is an English like language where one
instruction typically translates into a series of machinelanguage instructions.
A low level language corresponds closely to machine code
so that a single low-level language instruction translates to a
single machine language instruction.
JNTU World

www.alljntuworld.in

JNTU World

Documentation Section

or

Linkage Section
Definition Section

Global Declaration Section

/*Program to find
area and perimeter of Circle */
#include<stdio.h
#include<stdio.h>
>
#define PI 3.1415
float radius;
float area();
float perimeter();
int main()
{
float a, p;
printf(Enter
printf(Enter radius : );
scanf
scanf(%
(%f,&radius
f,&radius);
);
a = area();
p = perimeter();
printf(Area
printf(Area of Circle : %
%f,a
f,a);
);
printf(Perimeter
printf(Perimeter : %
%f,p
f,p);
);
}
float area()
{
return (PI * radius * radius);
}
float perimeter()
{
return (2 * PI * radius);
}

ld

Structure of C program

Main Function Section

Sub Program Section

JN

TU

Local Declaration Part


Executable Code Part

JNTU World

Function1()
Function2()

FunctionN()

www.alljntuworld.in

JNTU World

4.a)Compilation
Translate the program into machine code. This
process is called as Compilation. Syntactic errors are
found quickly at the time of compiling the program.
These errors occur due to the usage of wrong syntaxes
for the statements.
Eg: x=a*y+b
There is a syntax error in this statement, since, each
and every statement in C language ends with a
semicolon (;).

JN

TU

or

1)Statement of Problem
a) Working with existing system and using proper
questionnaire, the problem should be explained
clearly.
b) What inputs are available, outputs are required
and what is needed for creating workable solution
should be understood clearly.
2)Analysis
a) The method of solutions to solve the problem can
be identified.
b) We also judge that which method gives best
results among different methods of solution.
3)Designing
a) Algorithms and flow charts will be prepared.
b) Keep focus on data, architecture, user interfaces
and program components.
4)Implementation
The algorithms and flow charts developed in the
previous steps are converted into actual programs in
the high level languages like C.

ld

Program Development Steps

4.b)Execution
The next step is Program execution. In this phase, we
may encounter two types of errors.
Runtime Errors: these errors occur during the
execution of the program and terminates the program
abnormally.
Logical Errors: these errors occur due to incorrect
usage of the instructions in the program. These errors
are neither detected during compilation or execution
nor cause any stoppage to the program execution but
produces incorrect ouz

JNTU World

www.alljntuworld.in

JNTU World

#include<stdio.h>
int main()
{
.

prog1.c

Yes

Syntax
Errors?

010110 100
.
01011 101

No
Object machine code

00101010
.
01010101

prog1.obj

adds

Linker

machine code of
library file

TU

Executable
machine code

prog1.exe

Executes

C-Runtime

Feeds

Runtime
or Logic
Errors ?

Yes

JN

Input

Translators are system software


used to convert high-level
language program into
machine-language code.
Compiler : Coverts the entire
source program at a time
into object code file, and
saves it in secondary storage
permanently. The same
object machine code file will
be executed several times,
whenever needed.
Interpreter : Each statement of
source program is translated
into machine code and
executed immediately.
Translation and execution of
each and every statement is
repeated till the end of the
program. No object code is
saved. Translation is
repeated for every execution
of the source program.

or

compiles

C-compiler

Text
Editor

ld

Executing a C program

Output

JNTU World

www.alljntuworld.in

JNTU World

ld

Character Set of C-Language

or

Alphabets : A-Z and a-z


Digits : 0-9
Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | \ { } [ ] : ;
<>,.?/
White Spaces : space , Horizontal tab, Vertical tab, New Line
Form Feed.
C-Language Keywords(C99)
double
else
enum
extern
float
for
goto
if
_Imaginary

int
long
register
return
short
signed
sizeof
static
restrict

JN

TU

auto
break
case
char
const
continue
default
do
_Bool
inline

JNTU World

struct
switch
typedef
union
unsigned
void
volatile
while
_Complex

www.alljntuworld.in

JNTU World

ld

C-Tokens

JN

TU

or

Tokens : The smallest individual units of a C- program are called Tokens.


Key words, Identifiers, Constants, Operators, Delimiters.
Key words : have a predefined meaning and these meanings cannot be
changed. All keywords must be written in small letters (except additional
c99 keywords).
Identifiers : names of variables, functions, structures, unions, macros, labels,
arrays etc.,
Rules for define identifiers :
a) First character must be alphabetic character or under score
b) Second character onwards alphabetic character of digit or under
score.
c) First 63 characters of an identifier are significant.
d) Cannot duplicate a key word.
e) May not have a space or any other special symbol except under
score.
f) C language is Case-sensitive.

JNTU World

www.alljntuworld.in

JNTU World

ld

C-Tokens

JN

TU

or

Constants : fixed values that do not change during execution of a program.


Boolean constants : 0 ( false) and 1 (true)
Character constants :
only one character enclosed between two single quotes
( except escape characters ).
wide character type - wchar_t - for Unicode characters.
Integer constants : +123, -3454 , 0235 (octal value),
0x43d98 ( hexa - decimal value)
54764U, 124356578L, 124567856UL
Float constants : 0.2 , 876.345, .345623 , 23.4E+8, 47.45e+6
String Constants : Hello world , Have a nice day!
Complex Constants : real part + imaginary part * I ex : 12.3 + 3.45 * I
Operators : a symbol, which indicates an operation to be performed.
Operators are used to manipulate data in program.
Delimiters : Language Pattern of c-language uses special kind of symbols
: (colon, used for labels) ; (semicolon terminates statement ) ( ) parameter list
[ ] ( array declaration and subscript ), { } ( block statement )
# ( hash for preprocessor directive ) , (comma variable separator )
JNTU World

www.alljntuworld.in

JNTU World

or

Minimal Range
127 to 127
0 to 255
127 to 127
32,767 to 32,767
0 to 65,535
Same as int
32,767 to 32,767
0 to 65,535
Same as short int
2,147,483,647 to 2,147,483,647
(263) to 263 1 (Added by C99)
Same as long int
0 to 4,294,967,295
264 1 (Added by C99)
3.4e-38 to 3.4e+38
1.7e-308 to 1.7e+308
3.4e-4932 to 1.1e+4932
data type that not return any value

JN

TU

Type
Typical Size in Bits
char
8
unsigned char
8
signed char
8
int
16 or 32
unsigned int
16 or 32
signed int
16 or 32
short int
16
unsigned short int
16
signed short int
16
long int
32
long long int
64
signed long int
32
unsigned long int
32
unsigned long long int
64
float
32
double
64
long double
80
void
--

ld

Data Types ( pre defined )

JNTU World

www.alljntuworld.in

JNTU World

or

JN

%hd
%ld
%lf
%%

Format
Hexa decimal output in the form of 0xh.hhhhp+d(C99 only)
String of characters (until null zero is reached )
Character
Decimal integer
Floating-point numbers
Exponential notation floating-point numbers
Use the shorter of %f or %e
Unsigned integer
Octal integer
Hexadecimal integer
Signed decimal integer
Display a pointer
The associated argument must be a pointer to integer, This sepecifier causes
the number of characters written in to be stored in that integer.
short integer
long integer
long double
Prints a percent sign (%)

TU

Code
%a
%s
%c
%d
%f
%e
%g
%u
%o
%x
%i
%p
%n

ld

Conversion Specifiers

JNTU World

www.alljntuworld.in

JNTU World

or

Backspace
Form feed
New line
Carriage return
Horizontal tab
Double quote
Single quote
Backslash
Vertical tab
Alert
Question mark
Octal constant (N is an octal constant)
Hexadecimal constant (N is a hexadecimal constant)

JN

TU

\b
\f
\n
\r
\t
\"
\'
\\
\v
\a
\?
\N
\xN

Meaning

Code

ld

Back Slash ( Escape Sequence) Characters

JNTU World

www.alljntuworld.in

JNTU World

postfix increment (a++)

Executes all Prefix Operations

After evaluation of expression


and before leaving the statement

/* prefix and postfix operators */


#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (a++) + 5 * (++a);
printf( a = %d, a);
printf(\
printf(\n b = %d,b);
printf(\
printf(\n c = %d,c);
}
Output:
a=9
b = 12
c = 136 ( 12 * 8 + 5 * 8)

JN

TU

/* prefix operators */
#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (++a) + 5 * (++a);
printf( a = %d, a);
printf(\
printf(\n b = %d,b);
printf(\
printf(\n c = %d,c);
}
Output:
a=9
b = 12
c = 153 ( 12 * 9 + 5 * 9)

postfix decrement (a(a- -)

Before evaluation of expression

Evaluation of expression
Executes all Postfix Operations

prefix decrement(decrement(- -a)

or

prefix increment (++a)

ld

Increment and Decrement Operators

JNTU World

/* postfix operators */
#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (a++) + 5 * (a++);
printf( a = %d, a);
printf(\
printf(\n b = %d,b);
printf(\
printf(\n c = %d,c);
}
Output:
a=9
b = 12
c = 119 ( 12 * 7 + 5 * 7)

www.alljntuworld.in

JNTU World

A& B

| -- Bitwise OR

^ -- Bitwise XOR

~ -- Bitwise NOT

A^ B

~A

Bitwise AND

A| B

or

& -- Bitwise AND

ld

Bitwise Logical Operators

Bitwise OR

A (42) : 00000000 00101010


B (15) : 00000000 00001111
----------------------------------| (47) : 00000000 00101111
-----------------------------------

Bitwise XOR

Bitwise NOT

A (42) : 00000000 00101010


B (15) : 00000000 00001111
----------------------------------& (37) : 00000000 00100101
-----------------------------------

A (42) : 00000000 00101010


----------------------------------~ ((-43) : 11111111 11010101
-----------------------------------

JN

TU

A (42) : 00000000 00101010


B (15) : 00000000 00001111
----------------------------------& (10) : 00000000 00001010
-----------------------------------

JNTU World

www.alljntuworld.in

JNTU World

ld

BITWISE SHIFT OPERATORS


Bitwise Right Shift ( >> )
(positive values)
A (43) : 00000000 00101011
----------------------------------A >> 2 : 00000000 00001010
-----------------------------------

Bitwise Right Shift ( >> )


(negetive values)
A (43) : 00000000 00101011
A ((--44) : 11111111 11010100
--------------------------------------------------------------------A << 2 : 00000000 10101100
A >> 2 : 11111111 11110101
--------------------------------------------------------------------Note : Right shift operator fills the left vacant fields with zeros for positive numbers,
with ones for negative numbers.

TYPE CONVERSION
1.bool

(forcible)
.
.
.

Explicit Type Conversion


(casting)

2.char

TU

Opposite
To
Gravity

or

Bitwise Left Shift ( << )

(forcible)

3.short int
4.int
5.long int
6.long long int

JN

(natural)

Gravity

JNTU World

.
.
.

7.float
8.double
9.long double

(automatic)
Implicit Type Conversion
(automatic)

www.alljntuworld.in

JNTU World

Operators

Associativity

JN
Comma

LR
RL
LR
LR
LR
LR
LR
LR
LR
LR
LR
LR
RL
RL

or

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

TU

Precdence Group
(Highest to Lowest )
(param) subscript etc.,
Unary operators
Multiplicative
Additive
Bitwise shift
Relational
Equality
Bitwise AND
Bitwise exclusive OR
Bitwise OR
Logical AND
Logical OR
Conditional
Assignment

ld

Precedence and Associativity of Operators

JNTU World

LR

www.alljntuworld.in

JNTU World

ld

Test
Expression
?

False

Entry

if
if--else:

Entry

True

True

True StatementStatement-block

Next statement

TrueTrue-block
Statements

JN

TU

/* check a citizen is eligible for voting */


#include<stdio.h>
int main()
{
int age;
printf(Enter the age : );
scanf(%d,&age);
if(age >= 18)
printf(Eligible for voting);
getch();
}

False

Test
Expression
?

or

simple if:

FalseFalse-block
Statements

Next statement

/* print a number is even or odd */


#include<stdio.h>
int main()
{
int number;
printf(Enter a number : );
scanf(%d, &number);
if((number %2) == 0)
printf(%d is even number.,number);
else
printf(%d is odd number.,number);
}

JNTU World

JNTU World

ld

www.alljntuworld.in

/* check whether a year is leap year or not */


#include<stdio.h>
int main() {
int year;
printf("Enter the year ?");
True
scanf("%d",&year);
if((year %100) == 0)
{
Test
True
if((year % 400) == 0)
condition2
printf("%d is leap year.",year);
?
else
printf("%d is not leap year.",year);
Statement
Statement--1
} else {
if((year % 4) == 0)
printf("%d is leap year.",year);
else
printf("%d is not leap year.",year);
}
getch();
}

False

Test
condition1
?

False

Statement
Statement--2

TU

Statement
Statement--3

Entry

or

nested ifelse:

JN

Next statement

JNTU World

JNTU World

ld

www.alljntuworld.in

Entry

True
Statement
Statement--1

Test
condition1
?

False

False

True

Statement
Statement--2

TU

Test
condition2
?
Test
conditionN
?

/* program to print the grade of student */


#include<stdio.h>
int main() {
int marks;
printf("Enter marks ? ");
scanf("%d", &marks);
if(marks >= 75)
printf("Distinction");
else if(marks >= 60)
printf("First class");
else if(marks >= 50)
printf("Second class");
else if(marks >= 35)
printf("Third class");
else
printf("Failed");
}

or

ifelseif :

True

Statement
Statement--N

JN

Next statement

JNTU World

www.alljntuworld.in

JNTU World

Entry

value2

valueN

associate
statement

TU

associate
statement

...
associate
statement

or

switch
expression
?

value1

/* program to simulate a simple calculator */


#include<stdio.h>
int main() {
float a,b;
char opr;
printf("Enter number1 operator number2 : ");
scanf("%f %c %f",&a,&opr,&b);
switch(opr)
default
{
case '+':
printf("Sum : %f",(a + b));
associate
break;
statement
case ''--':
printf("Difference : %f",(a - b));
break;
case '*':
printf("Product : %f",(a * b));
break;
case '/':
printf("Quotient : %f",(a / b));
break;
default:
printf("Invalid Operation!");
}
}

ld

switch statement :

JN

Exit

Next statement

JNTU World

www.alljntuworld.in

JNTU World

Loop Statements

ld

dodo-while (Exit controlled )

while (Entry controlled )


Entry

or

Test
Condition
?
true

Entry

False

Body of The loop

Body of The loop

Following Statement

JN

TU

/* sum of 1 to 10 numbers */
#include<stdio.h>
int main() {
int i = 1,sum = 0;
while(i<=10){
sum = sum + i;
i = i + 1;
}
printf(Total : %d ,sum);
}

Test
Condition
?
True

False
Following Statement

/* average of 5 numbers */
#include<stdio.h>
int main() {
int count = 1;
float x, sum = 0;
do {
printf(x = );
scanf(%f,&x);
sum += x;
++ count;
} while(count <= 5);
printf(Average = %f , (sum/5))
}

JNTU World

www.alljntuworld.in

JNTU World

for -- Statement

ld

Entry

Initialization Statement

Increment Statement

Test
Condition
?
True

or

False

Body of The loop

Following Statement

JN

TU

/* check whether a number is prime or not */


#include<stdio.h>
int main() {
int n,i,factors = 0;
printf("Enter a number : ");
scanf("%d",&n);
for(i = 1; i <= n; i++) {
if((n % i)==0) ++factors;
}
if (factors == 2)
printf("%d is prime number.",n);
else
printf("%d is not prime number.",n);
}

JNTU World

www.alljntuworld.in

JNTU World

ld

Important Functions in math.h


absolute value of integer x
rounds up and returns the smallest integer greater than or
equal to x
rounds down and returns the largest integer less than or equal
to x
returns natural logarithm
returns the value of xy
returns square root of x
returns natural anti logarithm
returns sine value where x in radians
returns cosine value where x in radians
returns tangent values where x in radians
calculate x modulo y, where x and y are double
calculate hypotenuse of right angle where x,y are sides.
returns logarithm base 10

floor(x)

JN

TU

log(x)
pow(x,y)
sqrt(x)
exp(x)
sin(x)
cos(x)
tan(x)
fmod(x,y)
hypot(x,y)
log10(x)

or

abs(x)
ceil(x)

JNTU World

JNTU World

ld

www.alljntuworld.in

or

www.alljntuworld.in

JN

TU

For More Materials, Text Books, Previous


Papers & Mobile updates of B.TECH,
B.P
PHARMACY, MBA, MCA of JNTUHYD,JNTU-KAKINADA & JNTUANANTAPUR visit www.alljntuworld.in

JNTU World

www.alljntuworld.in

JNTU World

ld

Modularizing and Reusing of code through Functions

or

Calculation of area of Circle is separated into a separate module from Calculation of area of
Ring and the same module can be reused for multiple times.

/* program to find area of a ring */


#include<stdio.h>
float area();
Function Declaration
int main()
{
float a1,a2,a;
a1 = area();
Function Calls
a2 = area();
a = a1- a2;
printf("Area of Ring : %.3f\n", a);
}
float area()
Function Definition
{
float r;
printf("Enter the radius : ");
scanf("%f", &r);
return (3.14*r*r);
}

JN

TU

/* program to find area of a ring


*/
#include<stdio.h>
Repeated & Reusable
int main()
blocks of code
{
float a1,a2,a,r1,r2;
printf("Enter the radius : ");
scanf("%f",&r1);
a1 = 3.14*r1*r1;
printf("Enter the radius : ");
scanf("%f",&r2);
a2 = 3.14*r2*r2;
a = a1- a2;
printf("Area of Ring : %.3f\n",
a);
}

JNTU World

www.alljntuworld.in

JNTU World

or

ld

A Function is an independent, reusable module of statements, that specified by a name.


This module (sub program) can be called by its name to do a specific task. We can call the
function, for any number of times and from anywhere in the program. The purpose of a function
is to receive zero or more pieces of data, operate on them, and return at most one piece of
data.
A Called Function receives control from a Calling Function. When the called function
completes its task, it returns control to the calling function. It may or may not return a value to
the caller. The function main() is called by the operating system; main() calls other functions.
When main() is complete, control returns to the operating system.

JN

TU

int main() {
int n;
float p, r, si;
printf(Enter Details of Loan1:);
scanf( %f %d %f, &p, &n, &r);
si =calcInterest( p, n , r );
printf(Interest : Rs. %f, si);
printf(Enter Details of Loan2:);
}

value of p is copied to loan


value of n is copied to terms
value of r is copied to iRate
float calcInterest(float loan , int terms , float iRate )
{
The block is
float interest;
executed
interest = ( loan * terms * iRate )/100;
return ( interest );
}

Called Function

value of interest is assigned to si

Calling Function

Process of Execution for a Function Call


JNTU World

JNTU World

or

int main()
{
int n1, n2;
printf("Enter a number : ");
scanf("%d",&n1);
printOctal(n1);
readPrintHexa();
printf("Enter a number : ");
scanf("%d",&n2);
printOctal(n2);
printf(\n);
}

ld

www.alljntuworld.in

void printOctal(int n)
{
printf("Number in octal form : %o \n", n);
}

JN

TU

void readPrintHexa()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
printHexa(num);
printf(\n);
4
}

void printHexa(int n)
{
printf("Number in Hexa-Decimal form : %x \n",n);
}

JNTU World

Flow of
Control
in
Multi-Function
Program

www.alljntuworld.in

JNTU World

ld

Function-Its Terminology

or

Function Name

Declaration (proto type) of Function

Formal Parameters

/* Program demonstrates function calls */


#include<stdio.h>
int add ( int n1, int n2 ) ;
int main(void)
{
int a, b, sum;
printf(Enter two integers : );
scanf(%d %d, &a, &b);
sum = add ( a , b ) ;
printf(%d + %d = %d\n, a, b, sum);
return 0;

Function Call
Actual Arguments

TU

}
Return Type

/* adds two numbers and return the sum */


int
{

add ( int x , int y

JN

int s;
s = x + y;
return ( s );

Definition of Function
Parameter List used in the Function

Return statement of the Function

Return Value

JNTU World

www.alljntuworld.in

JNTU World

or

void printMyLine()
Function with No parameters
{
and No return value
int i;
for(i=1; i<=35;i++) printf(%c, -);
printf(\n);
}

/* using different functions */


int main()
{
float radius, area;
printMyLine();
printf(\n\tUsage of functions\n);
printYourLine(-,35);
radius = readRadius();
area = calcArea ( radius );
printf(Area of Circle = %f,
area);
}

ld

Categories of Functions

TU

void printYourLine(char ch, int n)


{
Function with parameters
and No return value
int i;
for(i=1; i<=n ;i++) printf(%c, ch);
printf(\n);
}

JN

float readRadius()
Function with return
{
value & No parameters
float r;
printf(Enter the radius : );
scanf(%f, &r);
return ( r );
}

float calcArea(float r)
{
Function with return
float a;
value and parameters
a = 3.14 * r * r ;
return ( a ) ;
}
Note: void means Containing nothing

JNTU World

www.alljntuworld.in

JNTU World

void area()
{
static int num = 0;

ld

#include<stdio.h>
float length, breadth;
int main()
{
printf("Enter length, breadth : ");
scanf("%f %f",&length,&breadth);
area();
perimeter();
printf(\nEnter length, breadth: ");
scanf("%f %f",&length,&breadth);
area();
perimeter();
}

Static Local Variables


Visible with in the function,
created only once when
function is called at first
time and exists between
function calls.

or

float a;
num++;
a = (length * breadth);
printf(\nArea of Rectangle %d : %.2f", num, a);

TU

External Global Variables


Scope:
Visible
across
multiple
functions Lifetime: exists till the end
of the program.

JN

Enter length, breadth : 6 4


Area of Rectangle 1 : 24.00
Perimeter of Rectangle 1 : 20.00
Enter length, breadth : 8 5
Area of Rectangle 2 : 40.00
Perimeter of Rectangle 1 : 26.00

void perimeter()
{
int no = 0;
float p;
no++;
p = 2 *(length + breadth);
printf(Perimeter of Rectangle %d: %.2f",no,p);
}

Automatic Local Variables


Scope : visible with in the function.
Lifetime: re-created for every function call and
destroyed automatically when function is exited.

Storage Classes Scope & Lifetime


JNTU World

www.alljntuworld.in

JNTU World

File2.c

File1.c

ld

static float base, height;


int main()
{
float peri;
printf("Enter length, breadth : ");
scanf("%f %f",&length,&breadth);
rectangleArea();
peri = rectanglePerimeter();
printf(Perimeter of Rectangle : %f, peri);
printf(\nEnter base , height: ");
scanf("%f %f",&base,&height);
triangleArea();
}
void rectangleArea() {
float a;
a = length * breadth;
printf(\nArea of Rectangle : %.2f", a);
}
void triangleArea() {
float a;
a = 0.5 * base * height ;
printf(\nArea of Triangle : %.2f", a);
}

extern float length, breadth ;


/* extern base , height ; --- error */
float rectanglePerimeter()
{
float p;
p = 2 *(length + breadth);
return ( p );
}

or

#include<stdio.h>
float length, breadth;

JN

TU

External Global Variables


Scope: Visible to all functions across all
files in the project.
Lifetime: exists
till the end of the
program.

Static Global Variables


Scope: Visible to all functions with in
the file only.
Lifetime: exists
till the end of the
program.

Storage Classes Scope & Lifetime

JNTU World

www.alljntuworld.in

JNTU World

ld

Preprocessor Directives

A function

showSquares(1)
showSquares(2)
showSquares(3)

JN

showSquares(4)

- Define a macro substitution


- Undefines a macro
- Test for a macro definition
- Tests whether a macro is not
defined
#include - Specifies the files to be included
#if
- Test a compile-time condition
#else
- Specifies alternatives when #if
test fails
#elif
- Provides alternative test facility
#endif
- Specifies the end of #if
#pragma - Specifies certain instructions
#error
- Stops compilation when an error
occurs
#
- Stringizing operator
##
- Token-pasting operator

or

Output : 1 4 9 16 25
addition
of
function
calls
to
callstack

#define
#undef
#ifdef
#ifndef

calling itself
is
Recursion

TU

#include<stdio.h>
void showSquares(int n)
{
if(n == 0)
return;
else
showSquares(n-1);
printf(%d , (n*n));
}
int main()
{
showSquares(5);
}

execution
of
function
calls
in
reverse

showSquares(5)
main()

call-stack
JNTU World

Preprocessor is a program that


processes the source code before it
passes through the compiler.

www.alljntuworld.in

JNTU World

JN

TU

or

ld

For More Materials, Text Books,


Previous Papers & Mobile updates
of B.TECH, B.PHARMACY, MBA,
MCA of JNTU-HYD,JNTUKAKINADA & JNTU-ANANTAPUR
vi
visi
sitt www.a
j lljntuworld.in

JNTU World

www.alljntuworld.in

JNTU World

Sixty variables are replaced by one Array

#include<stdio.h>
Sixty input
int main() {
int scores[60] , i , j, temp;
statements are
for(i = 0; i < 60 ;i++) {
called by one loop
printf("Enter the score : ");
statement
scanf("%d", &scores[i]);
}
1770 comparing
for(i=0;i<(60-1);i++)
statements are
for( j=0; j <(60 -(i+1)); j++)
included in one
if(scores[ j ] < scores[ j +1]) {
temp = scores[ j ];
loop statement
scores[ j ] = scores[ j +1];
scores[ j + 1] = temp;
}
for( i = 0; i < 60; i ++) printf("%4d", scores[i]);
}

TU

JN

scores[0]
scores[1]
scores[2]
scores[3]
.
.
scores[59]

or

score0
score1
score2
score3
.
.
score59

ld

Array & its Advantage

/* Ranking of 60 students in a class */


int main() {
/*declaring 60 varialbes */
int score0, score1,score2,,score59;
/* Reading scores for sixty times */
printf(Enter the score : );
scanf(%d, &score0);
. . . .
printf(Enter the score : );
scanf(%d, &score59);
/* comparing & swapping for 1770 times
* to arrange in descending order */
swap( score0, score1);
swap( score1, score2);
swap( score2, score3);
. . . .
swap( score0,score1);
swap( score1,score2);
swap( score0,score1);
/*printing 60 scores after sorting */
printf(%4d, score0);
printf(%4d, score1);

}
void swap ( int a, int b) {
int temp;
if( a < b) {
temp = a ; a = b ; b = temp;
}
}

JNTU World

www.alljntuworld.in

JNTU World

skyups media
scores[1]

scores[2]

scores[3]

scores[4]

ld

scores[0]

4022

4023

4024

start here

4025

4026

or

...

4027

4029

4028

4030

4031

( memory
addresses)

scores Array

Mean can be calculated only after reading all scores. Each deviation is difference of individual score and
mean. To calculate deviations of all scores, scores must be stored in an ARRAY.
Accessing
#include<stdio.h>
printf("\nMean : %.2f",mean);
Declaration of Array
an element
#include<math.h>
printf("\nDeviations : ");

for(i=0;i<SIZE ; i++) {
deviation = scores[i] - mean;
printf("%.2f\t", deviation);
total=total + deviation*deviation;
}
variance = total / SIZE;
printf("\nVariance = %.2f\n", variance);
stddev = sqrt(variance);
printf("Standard Deviation : %f", stddev);

JN

TU

#define SIZE 10
Initialization of Array
int main() {
int scores[SIZE],sum=0,i;
float deviation, mean, total=0;
float variance , stddev;
for(i=0; i < SIZE ;i++) {
printf("Enter score : );
scanf("%d", &scores[i] );
sum = sum + scores[i];
}
Input to an element
mean = (float)sum / SIZE;

JNTU World

Processing on Array

www.alljntuworld.in

JNTU World

ld

Scalar variable for single data item & Vector variable for multiple data items

JN

TU

or

Scalar Variables :
 A variable represents a data item and it can be used to store a single atomic value at a time.
These are also called scalar variables.
 Integer takes 2 bytes memory as a single unit to store its value. i.e.,the value of a scalar variable
cannot be subdivided into a more simpler data items.
 The address of first byte is the address of a variable .
Vector Variables (arrays):
 In contrast, an array is multivariable (an aggregate data type), which is also referred to a data
structure. It represents a collection of related data items of same type.
An individual data item of an array is called as element. Every element is accessed by index or
subscript enclosed in square brackets followed after the array name.
 All its elements are stored in consecutive memory locations, referred under a common array name.
Ex : int marks[10] ; /* declaration of array */
 0 is first number in computer environment. The first element of array marks is marks[0] and last
element is marks[9]. (the address of first element is the address of the array)
 An array is a derived data type. It has additional operations for retrieve and update the individual
values.
 The lowest address corresponds to the first element and the highest address to the last element.
 Arrays can have from one to several dimensions. The most common array is the string, which is
simply an array of characters terminated by a null.

JNTU World

www.alljntuworld.in

JNTU World

ld

Elements of
Array [3] by [4]

[0][0]

[0][1]

[0][2]

[0][3]

[1][0]

[1][1]

[1][2]

[1][3]

[2][0]

[2][1]

[2][2]

[2][3]

JN

TU

or

Declaration of One Dimensional Arrays


Syntax :
arrayType arrayName [ numberOfElements ];
Example :
int scores [60];
float salaries [20];
Initialization of Array while Declaration :
int numbers [ ] = { 9, 4, 2, 7, 3 };
char name[ ] ={R,a,v,i, ,T,e,j,a,\0 };
char greeting[ ] = Good Morning;
Declaration of Multi Dimensional Arrays
Syntax :
arrayType arrayName [ Rows ][ Columns ];
arrayType arrayName [ Planes][ Rows ][ Columns ];
Example :
/* Each student for seven subjects */
int marks[60][7];
/* Matrix with 3 planes and 5 rows and 4 columns */
float matrix[3][5][4];
Initialization of Array while Declaration :
int matrix [ ][ ] = { { 4, 2, 7, 3 } ,
{ 6, 1, 9, 5 } ,
{ 8, 5, 0, 1 } };

JNTU World

/*passing an array to function */


#define SIZE 10
int main() {
float list[SIZE] ,avg;

avg = average(SIZE , list );

}
float average( int n , float x[]) {
float sum=0,i;
for( i = 0; i < n ; i++)
sum = sum + x[i];
return ( sum / n ) ;
}

www.alljntuworld.in

JNTU World

Strings - One Dimensional Character Arrays

or

char name[] = Ravi Kiran;

ld

A String is sequence of characters. In C strings are implemented by an array of characters


terminated with a null character \0(back slash followed by zero ).

\0

name
name is an array of characters has size of eleven characters including a null
character \0(ascii code is zero).
char name[25] ;
scanf(%s, name); /*reading a string until a white space is encountered ( & operator is not required )*/
printf(%s, name); /*printing a string in input window */
gets(name) ; /* reading a string including white spaces until \n is encountered. */
puts(name); /* printing a string and moves cursor to new line */

JN

TU

String Manipulation Functions in <string.h>


strlen(s1)
- returns the length of string excluding the last null character.
strcpy(s1,s2)
- copies characters in s2 into s1.
strcat(s1,s2) - concatenates s2 to s1.
strcmp(s1,s2)
-compares s1 with s2 lexicographically and returns 0 if two strings are
same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2.
strcmpi(s1,s2)
-compares s1 with s2 like strcmp() but case of characters is ignored.
strchr(s1,ch)
-returns pointer to first occurrence of the character ch in s1.
strstr(s1,s2) -returns pointer to first occurrence s2 in s1.
strrev(s1)
-returns pointer to the reversed string.

JNTU World

www.alljntuworld.in

JNTU World

ld

Memory Address : Bit is a smallest unit of memory to store either 0 or 1 in memory.


Byte is unit of memory of 8 bits. Memory is a sequence of a large number of memory
locations , each of which has an address known as byte. Every byte in memory has a
sequential address number to recognized by processor.

or

Memory Sections of C-Runtime

JN

TU

RAM is temporary storage place to run programs. C-Language runtime also utilizes an
allotted memory block in RAM to run its programs.
Text Section : Memory-area that contains the machine instructions(code).It is read
only and is shared by multiple instances of a running program.
Data Section : Memory image of a running program contains storage for initialized
global variables, which is separate for each running instance of a program.
BSS (Below Stack Segment) : Memory area contains storage for uninitialized global
variables. It is also separate for each running instance of a program.
Stack : Area of memory image of a running program contains storage for automatic
variables of a function. It also stores memory address of the instruction
which is the function call, to return the value of called function.
Heap : This memory region is reserved for dynamically allocating memory for
variables at run time. Dynamic Memory Allocation calculate the required
memory size while program is being executed.
Shared Libraries: This region contains the executable image of shared libraries being used by
a program.

JNTU World

www.alljntuworld.in

JNTU World

ld

Two or more Permanent Manipulations using one Function


Passing Parameters By Reference

Passing Parameters By Value

or

/* program to swap two numbers */


#include<stdio.h>
void swap(int *x, int *y)
{
int temp;
temp = *x; *x = *y; *y = temp;
printf(\nIn swap() : %d %d ,*x,*y);
}
int main()
{
int a = 25,b = 37;
printf(Before swap() : %d %d,a,b);
swap (&a , &b);
printf(\nAfter swap() : %d %d,a,b);
}

TU

/* program to swap two numbers */


#include<stdio.h>
void swap(int x, int y)
{
int temp;
temp = x; x = y; y = temp;
printf(\nIn swap() : %d %d ,x,y);
}
int main()
{
int a = 25,b = 37;
printf(Before swap() : %d %d,a,b);
swap (a,b);
printf(\nAfter swap() : %d %d,a,b);
}

JN

Output :
Before swap() 25 37
In swap ()
37 25
After swap() 25 37

JNTU World

Output :
Before swap() 25 37
In swap ()
37 25
After swap() 37 25

www.alljntuworld.in

JNTU World

ld

Pointer variable A variable holds the address of another variable


Value in option

Allots some memory location


4042 (for example)
with a name option and
stores value Y in it

or

char option = Y;

Memory Address of variable option

ptr = &option;

JN

*ptr = N;

4042

Creates a pointer variable


with a name ptr
Which can hold a
Memory address
Memory address of
Variable option
Is copied to the
Pointer ptr

TU

char *ptr = NULL;

The value N is
stored in the variable
which has the
memory address
4042

JNTU World

Y
option

ptr

4042
ptr

Y
option
4042

4042
ptr

N
option
4042

www.alljntuworld.in

JNTU World

n2

n1

NULL

or

int main() {
pointer variables are declared
int n1, n2 ;
int *p = NULL, *q = NULL;
n1 = 6 ;
Prints 6 6
p = & n1;
printf (%d %d, n1,*p );

ld

Program with Using Pointers

q NULL

Prints address of n1

n1

q = & n2;
*q = 3 ;
printf ( %d %d , *p , *q ) ;

printf (%ld %ld,&n1, p );

Prints 6 3

TU

pointer q assigned with pointer q


p = q;
printf ( %d %d , *p , *q ) ;

n1

n2

n2

Prints 3 3

*p = 7 ;
printf ( %d %d , *p , *q ) ;

Prints 7 7

JN

n1
p

n2

When two pointers are referencing with one variable, both pointers contains address of the
same variable, and the value changed through with one pointer will reflect to both of them.

JNTU World

www.alljntuworld.in

JNTU World

ld

Pointer and Arrays

Pointer is an address variable, having no


initialized value by default. The address
stored in the pointer can be changed
time to time in the program.

#include<stdio.h>
int main()
{
int a[3] = { 12, 5 ,7}, b[3];
int *p ,*q;

or

Even though pointers and arrays work alike and strongly related,
they are not synonymous. When an array is assigned with pointer,
the address of first element of the array is copied into the pointer.

Prints 12 12

TU

p = a;
printf("%d %d\n", *p, *a);
Prints 12 12

q = p;
printf("%d %d",*p,*q);

JN

b = a; /* error */

Array name is an address constant,


initialized with the address of the first
element (base address )in the array. The
address stored in array name cannot be
changed in the program.

JNTU World

www.alljntuworld.in

JNTU World

ld

Pointer Arithmetic and Arrays

or

#include <stdio.h>
int main() {
int arr [5] = { 12, 31, 56, 19, 42 };
int *p;
Prints 31
p = arr + 1;
printf("%d \n", *p);
printf("%d %d %d\n", *(p-1), *(p), *(p + 1));
--p;
Prints 12
printf("%d", *p);

Prints 12 31 56

12

p - 1

arr[1] or *( arr + 1 )

31

arr[2] or *( arr + 2 )

56

p +1

arr[3] or *( arr + 3 )

19

p +2

arr[4] or *( arr + 4 )

42

p +3

JN

TU

arr[0] or *( arr + 0 )

Subscript operator [ ] used to access an element of array


implements address arithmetic, like pointer.
JNTU World

www.alljntuworld.in

JNTU World

ld

Array of Pointers

or

The advantage of pointer array is that the length of each row in the array may
be different. The important application of pointer array is to store character strings
of different length. Example :
char *day[ ] = { Sunday, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday };

Pointer to Pointer ( Double indirection )

TU

Example :
int a = 25;
int *pa = &a;
int **ppa ;
*ppa = &pa;
printf(%d, *pa);  prints 25
printf(%d, **ppa);  prints 25

pa

ppa

25

4024

4056

4024

4056

4078

Two Dimensional Array -- Pointers

a[0][1]

a[0][2]

a[1][0]

JN

a[0][0]

base_address

a[1][1]

a[1][2]

a[2][0]

a[2][1]

a[2][2]

a[3][0]

a[3][1]

Array name contains base address

Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j )

JNTU World

a[3][2]

www.alljntuworld.in

JNTU World

Function Pointers

ld

void Pointer
void type pointer is a generic
pointer, which can be assigned to any
data type without cast during
compilation or runtime. void pointer
cannot be dereferenced unless it is
cast.

or

Function pointers are pointers, which


point to the address of a function.
Declaration :
<return type> (* function_pointer)
(type1 arg1, type2 arg2, . );

int add ( int a, int b ) { return (a + b) ; }


int sub ( int a, int b ) { return (a b) ; }

TU

int main( ) {
void* p;
int x = 7;
float y = 23.5;
p = &x;
printf(x contains : %d\n, *( ( int *)p) );
p = &y;
printf(y contains : %f\n, *( ( float *)p) );
}

int (*fp ) (int, int ) ; /* function pointer */


int main( ) {
fp = add;
printf(Sum = %d\n, fp( 4, 5 ) ) ;
fp = sub;
printf(Difference = %d\n, fp( 6 , 2 ) ) ;
}

JN

Output :
x contains 7
y contains 23.500000

JNTU World

Output :
Sum = 9
Difference = 4

www.alljntuworld.in

JNTU World

ld

Dynamic Memory Allocation (DMA) of pointers


Static memory allocation means allocating memory by compiler. When using address operator,
the address of a variable is assigned to a pointer.
Ex : int a = 20 ; int *p = &a ;

or

Dynamic memory allocation means allocating memory using functions like malloc() and calloc().
The values returned by these functions are assigned to pointer variables only after execution of
these functions. Memory is assigned at run time.

TU

Allocates memory in bytes and returns the address of first


int main()
byte to the pointer variable
{
int *p, *q ;
Releases previously allocated memory space.
p = (int *) malloc ( sizeof( int ) );
if( p == NULL )
calloc ( ) is used for allocating memory space
{
during the program execution for derived data types
printf(Out of memory\n);
such as arrays, structures etc.,
exit(-1);
Example :
}
struct book {
printf(Address in p : %d, p );
int no ; char name[20] ; float price ;

free ( p );
p = NULL;

JN

};
struct book b1 ;
b1 *ptr ;
ptr = (book *) calloc ( 10, sizeof ( book ) );

ptr = (book * ) realloc ( ptr , 35 * sizeof ( book ) );


Modifies the size of previously allocated memory to
new size.

JNTU World

www.alljntuworld.in

JNTU World

Standard Character Functions


Classification of Characters

File Name : cmdline.c

printable
isprint ( )

or

graphical
isgraph ()

alpha-numeric
isalnum ( )
digit
isdigit ()

punctuation
ispunct ( )

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


printf(\nUser value %d : %s ,
i , argv [ i ] );

TU

alphabetic
isalpha( )

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


{
int i ;
printf(Number of arguments : %d, argc );
printf(\nName of Program : %s, argv [0] );

space
isspace ( )

upper
isupper ( )

ld

control
iscntrl ( )

Command Line Arguments

lower
islower ()

Other character functions in <ctype.h>

JN

toupper( ) converts to uppercase.


tolower ( ) converts to lowercase.
toascii ( ) converts greater than 127 to
with in the range 0 127

output
Compile the program :
c:\>tcc cmdline.c
c:\>cmdline welcome to c-programming
c:\>Number of arguments : 4
Name of Program : c:\cmdline.exe
User value 1 : welcome
User value 2 : to
User value 3 : c-programming

JNTU World

www.alljntuworld.in

JNTU World

<stdlib.h>

ld

Standard C-Library Functions


Converts string s to an integer

long atol(s)

Converts string s to a long integer.

float atof(s)

Converts string s to a double-precision quantity.

void* calloc(u1,u2)

Allocate memory to an array u1, each of length u2 bytes.

void exit(u)

Closes all files and buffers, and terminate the program.

void free (p)

Free block of memory.

void* malloc (u)

Allocate u bytes of memory.

int rand(void)

Return a random positive integer.

void* realloc(p,u)

Allocate u bytes of new memory to the pointer variable p.

void srand(u)

Initialize the random number generator.

void systerm(s)

Pass command string to the operating system.

TU

or

int atoi(s)

<time.h>

Returns clock ticks since program starts.

char *asctime(stuct tm)

Converts date and time into ascii.

int stime(time_t *tp)

Sets time.

time_t time(time_t *timer)

Gets time of day.

double difftime(t1,t2)

Returns difference time between two times t1 and t2.

JN

clock_t clock()

JNTU World

www.alljntuworld.in

JNTU World

Primary data types


Derived data types
User-defined data types

or

Array Type

Pointer
Type

Function
Type

Derived
Types

ld

C Data Types:

Structure
Type

Union Type

TU

Array Collection of one or more related variables of similar


data type grouped under a single name
Structure Collection of one or more related variables of different
data types, grouped under a single name

JN

In a Library, each book is an object, and its characteristics like title, author, no of
pages, price are grouped and represented by one record.
The characteristics are different types and grouped under a aggregate variable of
different types.
A record is group of fields and each field represents one characteristic. In C, a record
is implemented with a derived data type called structure. The characteristics of record are
called the members of the structure.

JNTU World

www.alljntuworld.in

JNTU World

book

book_id
bookid
author
pages
price

title

integer

2 bytes

50 bytes

Array of 50 characters

title

Book-3
BookID: 1213
Title : C By Example
Author : Greg Perry
Pages : 498
Price : Rs. 305.00

ld

Book-2
BookID: 1212
Title : The ANSI C Programming
Author : Dennis Ritchie
Pages : 214
Price : Rs. 125.00

or

Book-1
BookID: 1211
Title : C Primer Plus
Author : Stephen Prata
Pages : 984
Price : Rs. 585.00

author

Array of 40 characters

pages

integer

price

float

40 bytes

2 bytes
4 bytes

TU

Memory occupied by a Structure variable

STRUCTURE- BOOK

Structure tag

JN

struct book {
int book_id ;
char title[50] ;
char author[40] ;
int pages ;
float price ;
};

JNTU World

struct < structure_tag_name >


{
data type < member 1 >
data type < member 2 >
. . . .
data type < member N >
};

www.alljntuworld.in

JNTU World

Declaring a Structure Variable

ld

Declaring a Structure Type

struct student s1,s2,s3;


(or)
struct student
{
int roll_no;
char name[30];
float percentage;
}s1,s2,s3;

or

struct student
{
int roll_no;
char name[30];
float percentage;
};

Initialization of structure

Reading values to members at


runtime:

JN

TU

Initialization of structure variable while


declaration :
struct student s2 = { 1001, K.Avinash ,
87.25 } ;
Initialization of structure members individually :
s1. roll_no = 1111;
strcpy ( s1. name , B. Kishore ) ;
s1.percentage = 78.5 ;

membership operator

JNTU World

struct student s3;


printf(\nEnter the roll no);
scanf(%d,&s3.roll_no);
printf(\nEnter the name);
scanf(%s,s3.name);
printf(\nEnter the percentage);
scanf(%f,&s3.percentage);

www.alljntuworld.in

JNTU World

or

Declaration of Structure Type

Declaration of Structure variables

Declaration and initialization of Structure variable

struct employee {
int empid;
char name[35];
int age;
float salary;
};
int main() {
struct employee emp1,emp2 ;

ld

Implementing a Structure

JN

TU

struct employee emp3 = { 1213 , S.Murali , 31 , 32000.00 } ;


emp1.empid=1211;
strcpy(emp1.name, K.Ravi);
Initialization of Structure members individually
emp1.age = 27;
emp1.salary=30000.00;
Reading values to members of Structure
printf(Enter the details of employee 2);
scanf(%d %s %d %f , &emp2.empid, emp2.name, &emp2.age, &emp2.salary);
if(emp1.age > emp2.age)
printf( Employee1 is senior than Employee2\n );
else
printf(Employee1 is junior than Employee2\n);
Accessing members of Structure
printf(Emp ID:%d\n Name:%s\n Age:%d\n Salary:%f,
emp1.empid,emp1.name,emp1.age,emp1.salary);

JNTU World

www.alljntuworld.in

JNTU World

Nesting of structures

ld

Arrays And structures

struct date {
int day ;
Outer Structure
int month ;
int year ;
};
struct person {
char name[40];
int age ;
struct date b_day ;
};
int main( ) {
Inner Structure
struct person p1;
strcpy ( p1.name , S. Ramesh ) ;
p1. age = 32 ;
Accessing Inner
p1.b_day.day = 25 ;
p1.b_day. month = 8 ; Structure members
p1.b_day. year = 1978 ;
}

or

struct student
{
int sub[3] ;
int total ;
};

JN

TU

int main( ) {
struct student s[3];
int i,j;
for(i=0;i<3;i++) {
printf(\n\nEnter student %d marks:,i+1);
for(j=0;j<3;j++) {
scanf(%d,&s[i].sub[j]);
}
}
for(i=0;i<3;i++) {
s[i].total =0;
for(j=0;j<3;j++) {
s[i].total +=s[i].sub[j];
}
printf(\nTotal marks of student %d is: %d,
i+1,s[i].total );
}
}

JNTU World

OUTPUT:
Enter student 1 marks: 60 60 60
Enter student 2 marks: 70 70 70
Enter student 3 marks: 90 90 90
Total marks of student 1 is: 180
Total marks of student 2 is: 240
Total marks of student 3 is: 270

www.alljntuworld.in

JNTU World

OUTPUT:

s1. next = & s2 ;

7 / 12

s2 node is linked to s1 node

printf ( %s , s1. name ) ;

TU

int main ( ) {
struct fraction f1 = { 7, 12 } ;
show ( f1 ) ;
}

or

void show ( struct fraction f )


{
printf ( %d / %d , f.numerator,
f.denominator ) ;
}

struct student_node {
int roll_no ;
char name [25] ;
struct student_node *next ;
};
int main( )
{
struct student_node s1 ;
struct student_node s2 = { 1111, B.Mahesh, NULL } ;
s1. roll_no = 1234 ;
strcpy ( s1.name , P.Kiran ) ;

struct fraction {
int numerator ;
int denominator ;
};

Self referential structures

ld

structures and functions

Prints P.Kiran

printf ( %s , s1.next - > name ) ;

Prints B.Mahesh

JN

A self referential structure is one that includes at least one member


which is a pointer to the same structure type.
With self referential structures, we can create very useful data
structures such as linked -lists, trees and graphs.

JNTU World

www.alljntuworld.in

JNTU World

Accessing structure members through


pointer :
i) Using . ( dot ) operator :
( *ptr ) . prodid = 111 ;
strcpy ( ( *ptr ) . Name, Pen) ;

or

struct product
{
int prodid;
char name[20];
};
int main()
{
struct product inventory[3];
struct product *ptr;
printf(Read Product Details : \n");
for(ptr = inventory;ptr<inventory +3;ptr++) {
scanf("%d %s", &ptr->prodid, ptr->name);
}
printf("\noutput\n");
for(ptr=inventory;ptr<inventory+3;ptr++)
{
printf("\n\nProduct ID :%5d",ptr->prodid);
printf("\nName: %s",ptr->name);
}
}

ld

Pointer to a structure

JN

TU

ii) Using - > ( arrow ) operator :


ptr - > prodid = 111 ;
strcpy( ptr - > name , Pencil) ;

JNTU World

Read Product Details :

111 Pen
112 Pencil
113 Book
Print Product Details :
Product ID : 111
Name : Pen
Product ID : 112
Name : Pencil
Product ID : 113
Name : Book

www.alljntuworld.in

JNTU World

ld

A union is a structure all of whose members share the same memory

Memory allotted to structure student


Address 5000

5001

JN

5002

5003

5004

5005

avg
rollno
Total memory occupied : 7 bytes

TU

struct student {
int rollno;
float avg ;
char grade ;
};
union pupil {
int rollno;
float avg ;
char grade;
};
int main() {
struct student s1 ;
union pupil p1;
printf ( %d bytes ,
sizeof ( struct student ) ) ;
printf ( %d bytes ,
sizeof ( union pupil ) ) ;
}
Output :
7 bytes 4 bytes

or

Union is a variable, which is similar to the structure and contains number of members
like structure.
In the structure each member has its own memory location whereas, members of union
share the same memory. The amount of storage allocated to a union is sufficient to hold its
largest member.

Memory allotted to union pupil

Address

5000

5001

5002

5003

rollno
avg

grade
Total memory occupied : 4 bytes

JNTU World

5006

grade

JNTU World

ld

www.alljntuworld.in

or

www.alljntuworld.in

JN

TU

For More Materials, Text Books, Previous


Papers & Mobile updates of B.TECH,
B.PHARMACY, MBA, MCA of JNTUHYD,JNTU-K
KAKINADA & JNTU-ANANTAPUR
visit
www.alljntuworld.in

JNTU World

JNTU World

ld

www.alljntuworld.in

or

INTRODUCTION:

A structure is a collection of elements of different types of data.


Ex: consider the student information roll number, gender, age,
height and weight of different types.
main()

rno

TU

{ struct student

JN
int age;

2
ht

age

int rno;

char gender;

gender

wt
4

13 bytes of memory is allocated in s1


JNTU World

www.alljntuworld.in

JNTU World

ld

13 bytes of memory is allocated to s2


age

gender

or

float ht;
2

float wt;
};

struct student s1,s2;

TU

age

ht

wt
4

When all these data items are grouped under on single variable
name, we can get some meaningful information.
struct is a keyword used to create a new user defined data type.

JN

In some other high level programming languages the structures


are named as records

JNTU World

JNTU World

ld

www.alljntuworld.in

or

DEFINING A STRUCTURE:
syntax:

struct user defined datatype

Example:
struct student
{
int rno;
int age;
char gender;
float ht;
float wt;
};

datatype member1;

TU

datatype member2;
.

JN

datatype membern:

};

JNTU World

JNTU World

ld

www.alljntuworld.in

or

In the given syntax struct is keyword used to create new user defined
data type.

An user defined data type name may be any valid c identifier ( user
defined name).
The data type may be a valid simple data type or compound data type.

TU

The member names may be any valid C identifiers .in the given
example student is a new user defined data type name.

The variable rno, age, gender, ht, wt, are the structure members.
All these structure members must be enclosed within a pair of curly
braces.

JN

The structure definition should be terminated with semicolon.

JNTU World

JNTU World

ld

www.alljntuworld.in

DECLARING STRUCTURE VARIABLE:

or

Once a new user defined datatype is created by using the


keyboard struct then we can create any no. of structure variables of that
type.
syntax:

struct user defined_data type name

TU

structure var1, structure var2,.. Struct varn;

Above statement is called declarative statement of structure variables


and it allocates memory space to these variables.

JN

We can also declare structure variables immediately after structure


definition.

JNTU World

JNTU World

ld

www.alljntuworld.in

or

ACCESSING STRUCTURE MEMBERS:

Structure member accessing operator

S1.gender=m; s1.age=25;

Structure
S1.rno=100
variable
Structure member

TU

S1.ht=5.5;

s1.wt=60.2;

Two operators are used to access member of structure. The structure


member operator(.) also called dot operator and the structure pointer
operator () also called the arrow operator.

JN

The structure member operator accesses a structure member via structure


variable name.

JNTU World

www.alljntuworld.in

JNTU World

ld

syntax:

or

Ex: s1.rno, s1.age, s1.gender, s1.ht, s1.wt


S1.rno=100; s1.gender=M; s1.age=25; s1.ht=5.5; s1.wt=60.2
s2

rno
100
25

ht
5.5

wt

rno

age

gender
ht

wt

60.2

TU

age

gender
M

s1

ASSIGNING VALUES TO STRUCTURE MEMBERS:

JN

By using the assignment operator(=) we can assign values to all


structure members of a structure variable.
Syntax: structure variable.member = value;
Ex: s1.rno= 100; s1.age=25
JNTU World

JNTU World

ld

www.alljntuworld.in

INITIALIZING A STRUCTURE VARIABLE:

or

Structures can be initialized using initialize lists as with arrays. To


initialize a structure follow the variable name in the structure
declaration with an equal sign and brace enclosed comma separated
list of initializes.
Ex: struct student s1={100, 25,M, 5.5,65.2};
int x = 10;

TU

int a[10]={ 10,20,30};

READING AND DISPLAYING THE STRUCTURE VARIABLES:

JN

The C will not read or write an entire structure as a single command. It


will read or write the members of a structure as follows:
ex: scanf( %d, %d, %c, %f ,&s1.rno,&s1.age,&s1.gender,&s1.ht);
printf( %d %d %c %f, s1.rno, s1.age, s1.gender, s1.ht);
JNTU World

JNTU World

PROGRAM USING STRUCTURES:

ld

www.alljntuworld.in

or

 Reads the details of 2 students and calculate total and average


marks of 2 students.
#include<stdio.h>

#include<conio.h>
void main()

{ /* defining a structure */

TU

struct student

{ int rno;

JN

char name[30];
float m1,m2,m3;
float tot, avg;

};
JNTU World

JNTU World

/* 2. declaration of structure var*/

or

struct student s1,s2; (1st executed)

ld

www.alljntuworld.in

/* 3.reading 1st student details*/

printf( enter rno,name,m1,m2,m3 of first student \n);


scanf( %d %s %f %f %f ,
&s1.rno,&s1.name,&s1.m1,&s1.m2,&s1.m3);

TU

/* 4. reading 2nd student details*/

printf( enter rno, name, m1, m2, m3,of second student \n);
scanf( %d %s%f %f %f, &s2.rno,
&s2.name,&s2.m1,&s2.m2,&s2.m3);

JN

/* calculate total and avg of first student marks*/


s1.tot= s1.m1+s1.m2+s1.m3;
s1.avg = s1.tot/3;
JNTU World

JNTU World

ld

www.alljntuworld.in

or

/* 6.calculate total and avg of first student marks*/


s2.tot= s2.m1+s2.m2+s2.m3;
s2.avg = s2.tot/3;
/* displaying first student details*/
printf( first student details are \n);
printf( roll no:%d\n, name:%s \n, m1: %f \n. m2:%f, m3:%f \n, s1.rno,
s1.name, s1.m1, s1.m2, s1.m3);
printf( total :%f \n , average: %f \n, s1.tot, s1.avg);

TU

/* 8. displaying second student details*/

JN

printf( second student details are:\n);


printf( roll no:%d\n, name:%s \n, m1: %f \n. m2:%f, m3:%f \n,
s2.rno, s2.name, s2.m1, s2.m2, s2.m3);
printf( total :%f \n , average: %f \n, s2.tot, s2.avg);
}

JNTU World

www.alljntuworld.in

JNTU World

ld

Array of Structures:
Perhaps the most common usage of structures is an array of
structures.

or

->To declare an array of structures you must first define a structure


and then declare an array variable of that type.

TU

struct student

For example to declare a 100 element array of structures of type


student write

int rno;

int m1,m2,m3;

JN

int tot,avg;
}

struct student s[100];-Structure Variable Declaration


JNTU World

www.alljntuworld.in

JNTU World

ld

DEMONSTRATING ARRAY OF STRUCTURES:


#include<stdio.h>

or

#include <conio.h>

void main()

/*1.Defining an array of structures*/

TU

struct student

int rno;

JN

int m1,m2,m3;
int tot,avg;

};

JNTU World

JNTU World

/*2.Creating an array of Structures*/

or

struct student s[100];

ld

www.alljntuworld.in

int i,n;

clrscr();
printf(Enter n value\n);

/*3.Read total no.of students to n*/

TU

scanf(%d,&n);

/*4.Reading student details*/


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

JN

printf(Enter details of %d student\n,i+1);


scanf(%d,&s[i].rno);
JNTU World

www.alljntuworld.in

JNTU World

ld

scanf(%d%d%d,&s[i].m1,&s[i].m1,&s[i].m2,&s[i].m3);
/*5.Calculate tot,avg marks */

or

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

s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;

TU

/*6.Display the student details*/


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

JN

printf(The following are the %d student details\n,i+1);


printf(Rollno:%d\n,s[i].rno);
JNTU World

JNTU World

ld

www.alljntuworld.in

printf(M1:%d\n,s[i].m1);

or

printf(M2:%d\n,s[i].m2);
printf(M3:%d\n,s[i].m3);

printf(Total:%d\n,s[i].tot);

printf(Average:%d\n,s[i].avg);

JN

TU

JNTU World

www.alljntuworld.in

JNTU World

ld

Arrays with in Structures:

or

A member of a structure may be either a simple or compound type.A


simple member is one that is of any of the built-in datatypes such as integer or
character.

->The compound datatypes include one dimensional and multidimensional


arrays of other datatypes and structures.
For example consider this Structure:

TU

struct x

int rno;

JN

int m[3];/* An Array is described as a structure member*/


int tot,avg;

JNTU World

www.alljntuworld.in

JNTU World

ld

Nested Structures:

or

when a structure variable is a member of another structure, it is


called a Nested structure.
->In the below example structure variable z is declared as structure

JN

TU

Member to another structure.


EX:struct Test
{
int a;
int b;
};
Struct Exam
{
int x;
int y;
struct Test z;
};

JNTU World

www.alljntuworld.in

JNTU World

ld

Structures and Function:

or

A Structure can be passed to a function as a one variable or


as an individual member. The scope of a structure declaration should
be external storage class whenever a function in the main().

#include<stdio.h>
/*Defining a Structure*/

Program Using a Structure datatype:

TU

struct Test

int a;

JN

int b;
};

/*Prototype*/

JNTU World

JNTU World

struct Test Modify(struct Test s2);


void main()

or

struct Test T1={10,20};


T1=Modify(T1);

printf(After calling modify\n);

TU

printf(T1.a=%d\n,T1.a);

printf(T1.b=%d\n,T1.b);
}

ld

www.alljntuworld.in

JN

Stuct Test Modify(struct Test s2)


{

s2.a=s2.a+10;

JNTU World

JNTU World

ld

www.alljntuworld.in

S2.b=s2.b+10;

or

return s2;
}
b

10
1
200

20

a
10

JN

TU

30

JNTU World

10+10
=20

20
20+10

=30

www.alljntuworld.in

JNTU World

ld

Union:

or

Union is another datatype with two or more members,similar to


structure.But in this case all the members share a common
memory location.The members of a union can be refered by using
dot operator as in the case of structure.

The size of union can contain only one type of member at any
one time.

TU

The size of union corresponds to the length of the longest


member.

Syntax:

Union Userdefined_datatype

JN

datatype member 1;
datatype member n;};
JNTU World

JNTU World

ld

www.alljntuworld.in

Union Test

or

int b;
float c;
};

char a;

JN

TU

We may have structures with unions and unions with in structures.


Unions may also be intialized like structures.However,Since only
one member can be active at a time,Usually the assigned value will
go to the 1st member of union.

JNTU World

JNTU World

or

ld

www.alljntuworld.in

FILE HANDLING IN C

Disk I/O functions

TU

High level

Text

Un formatted

JN

Formatted

Low level

Binary
formatted

JNTU World

Un formatted

www.alljntuworld.in

JNTU World

or

ld

This works fine as long as the data is small.However, many real


life problems involve large volumes of data and in such
situations, the console oriented I/O operations pose two major
problems.

1. It becomes cumbersome and time consuming to handle large


volumes of data through terminals.
2. The entire data is lost when either the program is terminated
or computer is turned off.
It is therefore necessary to have a more flexible approach
where data can be stored on the disks and read whenever
necessary, without destroying the data.

TU

JN

o The method employs the concept of files to store data. A file is


place on the disk where a group of related data is stored.

JNTU World

JNTU World

ld

www.alljntuworld.in

or

Like most other languages, c supports a number of functions


that have the ability to perform basic file operations, which
include.

TU

 naming a file
 opening a file
 reading data from a file
 writing data to a file and
 closing a file.

JN

There are two distinct ways to perform file operations.


--The first one is known as the low level I/O and uses
UNIX system calls.
--The second method is referred to as the high level
operation and uses functions in c standard I/O library.

JNTU World

JNTU World

ld

www.alljntuworld.in

or

HIGH LEVEL I/O FUNCTIONS


fopen ()  creates a new file for use.

Opens an existing file for use.

fclose()  closes a file which has been opened for use.


getc()  reads a character from a file .

TU

putc()  writes a character to a file.


fprintf()  writes a set of data values to a file.
fscanf()  reads a set of data value from a file.

JN

getw()  reads an integer from a file.

JNTU World

JNTU World

putw()  writes an integer to a file.

ld

www.alljntuworld.in

or

fseek()  sets the position to a desired point in the file.


ftell()  gives the current position in file.

rewind()  sets the position to beginning of the file.

DEFINING AND OPENING A FILE:


If we want to store data in a file in the secondary memory, we must
specify certain thing about a file to operating system they are

TU

1.File name 2. data structure 3. purpose


For file name general format of declaring and opening a file is
FILE *fp;  specifies the file name.

JN

fp= fopen ( Filename, mode);  specifies the purpose of file.

JNTU World

www.alljntuworld.in

JNTU World

ld

The mode does this job. Mode can be one of the following
r: opens the text file for reading only.

or

w: opens the text file for writing only.

a : open the file for appending data to it.

r+: the existing file is opened for both reading and writing.
w+ : this mode allow you to open a file as text file for
reading as well as writing a data to a file.

TU

a+ : this mode allows you to open a file as a text file for


both reading and writing to a file.

JN

 One other hand we need to add b for binary file i.e., rb,
wb, rb+, wb+, a, ab+, ab.

JNTU World

JNTU World

ld

www.alljntuworld.in

or

rb: this mode allows to open a file as a binary file for reading
data from it.
wb: this mode allows to open a file as a binary file for writing
data to it.

ab: this mode allows to open a file as a binary file for


appending data at the end of the file.

TU

rb+: this mode allows to open a file as a binary file for reading
as well as writing data to a file.

wb+ : this mode allows to open a file as a binary file for writing
data to a file.

JN

ab+: this mode allows to open a file as a binary file for both
reading and writing data to a file.

JNTU World

JNTU World

ld

www.alljntuworld.in

Example:

or

FILE *P1, *P2;


P1= fopen (data.c, r);

CLOSING A FILE:

P2= fopen (result.c, w);

TU

A file must be closed as soon as all operations on it


have been completed. This ensures that all outstanding
information associated with the file is flushed out from the
buffer and all links to a file are broken.

Syn: fclose ( file pointer);

JN

fclose (P1);

JNTU World

JNTU World

ld

www.alljntuworld.in

getc() and putc():

JN

TU

or

The getc() is an input function is used to read a single


character from a file.
Syntax : charvar=getc (file pointer);
ch=getc (fp);
The putc() is an output function used to write a single
character into a file.
Syntax : putc (charvar, file pointer);
putc (ch, fp);

JNTU World

www.alljntuworld.in

JNTU World

ld

Program to count character, spaces, tabs, and numbers in a file.


#include<stdio.h>

or

Void main()
char ch;

int nol=0, not=0, nos=0, noc=0;


fp=fopen(pri.c, r);

TU

while(1)
{ ch=getc (fp);

if ( ch== EOF)
break;

JN

noc++;

JNTU World

www.alljntuworld.in

JNTU World

ld

if ( ch== )

or

nos++;
if (ch== \t)

If ( ch==\n)
nol++;

TU

not++;

fclose (fp);

printf ( number of characters = %d, noc);

JN

printf ( number of blanks= %d \n, nos);


printf ( number of tabs=%d \n , not);

JNTU World

JNTU World

ld

www.alljntuworld.in

printf ( number of lines = %d \n, nol);

or

getch();

OUTPUT:

number of characters =125

TU

number of blanks =25


number of tabs =13

JN

number of lines =22

JNTU World

JNTU World

ld

www.alljntuworld.in

putw() and getw():

or

The putw() function is an output function and is used


to write an integer into a file.

Syntax: putw( integer, file pointer)


ex: putw (x,pf);

TU

The getw() function is an input function and is used to read


an integer from a file.
Syntax: integervar =getw( file pointer);

JN

ex: x= getw(fp);

JNTU World

www.alljntuworld.in

JNTU World

ld

Program for demonstrating putw() and getw() function


#include<stdio.h>

or

#include<stdlib.h>

{
FILE *f;

TU

int word1, word2;

Void main()

fp=fopen ( number.c, w);


if(fp==NULL)

JN

printf ( error opening file);

JNTU World

www.alljntuworld.in

JNTU World

ld

exit(1);
}

or

word1=94;

if ( ferror(fp))

putw(word1,fp);

printf( error writing to file \n);

TU

else

printf( sucessful write \n );


fclose(fp);

JN

/* reopen the file */

fp= fopen( number.c, r);

JNTU World

www.alljntuworld.in

JNTU World

ld

if ( fp== NULL)

printf( error opening file );

exit(1);

or

/*extract the word */

TU

Word =getw (fp);


if (ferror (fp))

printf( error reading file \n);

JN

else

printf( successful read : word=%d , word2);

JNTU World

JNTU World

ld

www.alljntuworld.in

/* clean up*/

or

fclose (fp);
return 0;

TU

Number file

word1
94

94

word2
94

JN

getw

Successfully
wrote

JNTU World

Successful read
pf f()

JNTU World

fprintf() and fscanf() functions:

ld

www.alljntuworld.in

or

The fprintf() and fscanf() functions group of mixed data


simultaneously.
Syntax: fprintf( fp, control string , list);

ex: fprintf( %s %d %f , name, age, 7.5);


Syntax: fscanf(fp, control string , list);

TU

ex: fscanf( %s %d, item, &quantity);


Demonstrating frpintf () and fscanf() functions:
#include<stdio.h>

#include<conio.h>

JN

Void main()

JNTU World

www.alljntuworld.in

JNTU World

ld

or

FILE *fp;
int rno;

float marks;

char name[30];

fp=fopen( student.c, w);

TU

printf( enter student record \n);

scanf( %d %s %f ,& rno, name, &marks);


fprintf( fp, %d %s %f , rno, name, marks);

JN

fclose( fp);

fp= fopen( student.c, r);

JNTU World

JNTU World

printf( the student record \n);

ld

www.alljntuworld.in

or

fscanf (fp, %d %s %f, &rno, name, &marks);

fclose (fp);
}

student

JN

1. Ravi 30.5

fprintf()

scanf()
Enter students

TU

H.D

printf( %d %s %f, rno, name, marks);

rno name marks


1
ravi
30.5

fscanf()

JNTU World

1.Ravi 30.5
1 ravi 30.5

prinf()

JNTU World

RANDOM ACCESS TO FILES:

ld

www.alljntuworld.in

or

Sometimes it is required to access only a particular part


of the file and not the complete file.
This can be accomplished by using following function.

fseek(): it is a file function. It positions file pointer on the


stream. We can pass three arguments through this
function.

TU

The general format of fseek function is as follows:


fseek( file pointer, offset, position);

JN

This function is used to move the file position to a desired


location within the file.

JNTU World

www.alljntuworld.in

JNTU World

ld

1. Fileptr is a pointer to the file concerned.

or

2. Offset is a number or variable type long.


3. Position in an integer number.

Offset specifies the number of positions (bytes) to be moved


from the location specified at position.
integer
Constant
Location in file
value
SEEK_SET Beginning of file

TU

0
1

SEEK_CUR Current position of file

SEEK_END End of file

JN

Ex: fseek(fp,10,0) or fseek(fp, 10,SEEK_SET)


filepointer is repositioned in forward direction by 10 bytes

JNTU World

www.alljntuworld.in

JNTU World

or

ld

 Program to read the text file containing some


sentence. Using fseek() and read the text after skipping
n character from beginning of file.
Void main()

FILE *fp;
int n, ch;

TU

clrscr();
fp=fopen( text.txt, r);

printf( \n contents of file \n);

JN

while ((ch=fgetc(fp))!=EOF)
printf( %c, ch);

JNTU World

www.alljntuworld.in

JNTU World

ld

printf( \n how many characters including spaces


would you like to skip?);

or

scanf(%d, &n);
fseek ( fp, n, SEEK_SET)

printf(\n information after %d byte \n,n);


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

TU

printf(%c, ch);
fclose(fp);

JN

JNTU World

www.alljntuworld.in

JNTU World

bitfieds

typedef is a keyword,which allows you to


specify a new name for a datatype which is
already defined in c language program.
Syntax:
typedef <datatype> <newname>
/* Re-defining int type as Integer type */
typedef int Integer;
int main( ) {
Interger a ,b , sub;
a = 20,b = 10;
sub = a - b;
printf(%d - %d = %d, a, b, sub);
}
/* Defining structure with typedef to avoid
repeated usage of struct keyword */

struct playcard {
unsigned pips ;
unsigned suit ;
};
Above structure occupies 4 bytes of
memory. But the member pips accepts a
value between 1 to 13 and the member suit
accepts any value of 0, 1, 2 and 3 .
So we can create a more packed
representation of above structure with bitfields.
struct playcard {
unsigned pips : 4;
unsigned suit : 2;
};
A bitfield is a set of adjacent bits within
a single machine word.
4-bit field called pips that is capable of
storing the 16 values 0 to 15, and a 2-bit
field called suit that is capable of storing
values 0, 1, 2, and 3. So the entire structure
variable occupies only one byte.
Note : arrays of bit fields and a pointer to
address a bit field is not permitted.

TU

or

ld

typedef to define new datatype

JN

typedef struct {
int hours;
int minutes;
} TIME ;
int main( ) {
TIME t1, t2 , *t;
t = (TIME *) calloc (10, sizeof( TIME ));
}

JNTU World

www.alljntuworld.in

JNTU World

ld

Enumeration a set of named integers, makes program more readable

or

Declaration of enumeration :
enum <enum_name> { member1, member2, . . . } ;
Example :
enum option { YES, NO, CANCEL } ;
By default YES has value 0, NO has value 1 and CANCEL has 2.
enum direction { EAST = 1, SOUTH, WEST = 6, NORTH } ;
Now EAST has value 1, SOUTH has value 2, WEST has value 6, and NORTH has value 7.
Enumerated types can be converted implicitly or cast explicitly.
int x = WEST ; /* Valid. x contains 6. */
enum direction y ; y = (enum direction ) 2 ;
/* Valid. Y contains SOUTH */

JN

TU

#include<stdio.h>
int main() {
int signal;
printf ("\t\t\t MENU \n\t1.RED \n");
printf ("\t2.ORANGE\n\t3.GREEN \n );
printf ("\n\t Enter the signal : );
scanf (%d, &signal );
switch(signal)
{
case 1:
printf(\t Stop and Wait!"); break;
case 2:
printf(\t Ready to start!"); break;
case 3:
printf(\t Start and go!"); break;
}
}

JNTU World

#include<stdio.h>
enum color {RED = 1,ORANGE,GREEN };
int main() {
enum color signal;
printf ("\t\t\t MENU \n\t1.RED \n");
printf ("\t2.ORANGE\n\t3.GREEN\n");
printf ("\n\t Enter the signal : ");
scanf ("%d", &signal);
switch(signal) {
case RED:
printf("\t Stop and Wait!"); break;
case ORANGE:
printf("\t Ready to start!"); break;
case GREEN:
printf("\t Start and go!"); break;
}
}

www.alljntuworld.in

JNTU World

ld

Console I / O Vs File I / O

or

 scanf( ) and printf( ) functions read and write data which always uses the
terminal (keyboard and screen) as the target.
 It becomes confusing and time consuming to use large volumes of data
through terminals.
 The entire data is lost when either program terminates or computer is
turned off.
 Some times it may be necessary to store data in a manner that can be
later retrieved and processed.
This leads to employ the concept of FILES to store data permanently
in the system.

TU

File Operations

JN

Record is logical group of data fields that


comprise a single row of information, which
describes the characteristics of an object.
File is a set of records that can be accessed
through the set of library functions.
A File is a place on disk where a group of
related data ( records ) can be stored

JNTU World

1.
2.
3.
4.
5.

Creating a new file


Opening an existing file
Reading from a file
Writing to a file
Moving to a specific
location in a file (seek)
6. Closing a file

JNTU World

or

ld

www.alljntuworld.in

A Stream acts as an interface between a program


and an input/output Device.

TU

Stream is a Sequence of data bytes, which is used to read and write data to a file.
The streams that represent the input data of a program are known as Input Streams, where
as the streams that represent the output data of a program are known as Output Streams.
Input streams gets the data from different input devices such as keyboard and mouse and
provide input data to the program.
Output Streams obtain data from the program and write that on different Output Devices
such as Memory or print them on the Screen.

JN

Types of Files
1.Text file : It can be thought of as a stream of characters that can be processed sequentially
and in forward direction only.
2.Binary file : It is collection of bytes like images.
3.Sequential File: Data stored sequentially, to read the last record of the file, we need to
traverse all the previous records before it. Ex: files on magnetic tapes.
4.Random Access File: Data can be accessed and modified randomly. We can read any record
directly. Ex : files on disks.

JNTU World

www.alljntuworld.in

JNTU World

1. Declaring FILE pointer variable :


Syntax :
FILE *file_pointer1;

or

/*program to write and read data from file*/


#include<stdio.h>
void main() {
FILE *fp;
char ch;
fp = fopen(data.txt, w);
if(fp == NULL) {
printf(Cannot open file.);
exit(0);
}
printf(Type text ( to stop press . ) : );
while(ch != .) {
ch = getche();
fputc(ch,fp);
}
fclose(fp);
printf(\nContants read : );
fp = fopen(data.txt,r);
while(!feof(fp))
printf(%d, fgetc(fp));
fclose(fp);
}

ld

Steps involved using files

JN

TU

2. Open a file using fopen() function :


Syntax :
fp= fopen(filename,mode of access);

3. fputc() Used to write a character to


the file.
Syntax :
fputc(character, file_pointer);
4. fgetc() Used to read a character to the
file.
Syntax :
fgetc(file_pointer);
5. Close a file using fclose() function :
Syntax :
fclose(file_pointer);

JNTU World

JNTU World

ld

www.alljntuworld.in

file pointer used to handle files

/* creating a new file */


int main(){
char ch;FILE *fp;
printf("\nEnter the text\n");
printf("\n\t(Press ctrl+Z after
completing text)\n");
fp=fopen("str.txt","w");
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
}

or

filepointer=fopen(filename,mode);

putc(character,filepointer);

fclose(filepointer);

JN

TU

/* Reading the contents of existing file */


#include<stdio.h>
int main() {
FILE *fp;
char ch;
fp=fopen("str.txt","r");
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}

/* appending data to an existing file */


int main() {
FILE *fp; char ch;
printf("\nEnter the text\n");
printf("\n\t(Press ctrl+Z after
completing text)\n");
fp=fopen("str.txt","a");
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
}

JNTU World

www.alljntuworld.in

JNTU World

or

w -- open a file in write mode


-- if file exits, all its data is erased.
-- if file does not exist, it is created.
a -- open a file in append mode
-- if file exits, the marker is positioned
at end.
-- if file does not exist, it is created.

r+ -- open a file in read and write mode


-- if file exits, the marker is positioned
at beginning.
-- if file does not exist, NULL returned.
w+ -- open a file in read and write mode
-- if file exits, all its data is erased.
-- if file does not exist, it is created.
a+ -- open a file in read and append mode
-- if file exits, the marker is positioned
at end.
-- if file does not exist, it is created.

ld

r -- open a file in read mode


-- if file exits, the marker is positioned at
beginning.
-- if file does not exist, error returned.

rb , wb , ab, rb+ , wb+ , ab+ are modes to operate a file as binary file.

JN

TU

int main( ) { /* Without using w+ */


FILE *fp; char ch;
printf("\nEnter the text\n");
fp=fopen("str1.txt","w");
while((ch=getchar())!='\n)putc(ch,fp);
fclose(fp);
fp=fopen("str1.txt","r");
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}

/* open a file in read and write mode */


int main( ) {
FILE *fp; char ch;
printf("\nEnter the text\n");
fp=fopen("str1.txt","w+");
while((ch=getchar())!='\n') putc(ch,fp);
rewind(fp);
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}

JNTU World

www.alljntuworld.in

JNTU World

File Input / Output Functions


Open existing file / Create new file

fclose(fp)

Closes a file associated with file pointer.

closeall ( )

Closes all opened files with fopen()

fgetc(ch, fp)

Reads character from current position and advances the pointer to


next character.

fprintf( )

Writes all types of data values to the file.

fscanf()

Reads all types of data values from a file.

gets()

Reads string from a file.

puts()

Writes string to a file.

getw()

Reads integer from a file.

putw()

Writes integer to a file.

fwrite()
fseek()
feof()

or

Reads structured data written by fwrite() function


Writes block of structured data to the file.
Sets the pointer position anywhere in the file
Detects the end of file.

Sets the record pointer at the beginning of the file.

JN

rewind()

TU

fread()

ld

fopen(fp, mode)

ferror()

Reports error occurred while read/write operations

fflush()

Clears buffer of input stream and writes buffer of output stream.

ftell()

Returns the current pointer position.


JNTU World

www.alljntuworld.in

JNTU World

rb

/* Copying one binary file to other */

 open a file in read mode

wb  open a file in write mode

 open a file in append mode

or

ab

rb+  open a pre-existing file in read and


write mode
wb+ open a file in read and write mode

#include<stdio.h>
int main( )
{
FILE *fs,*ft;
char ch;
fs=fopen("pr1.exe","rb");
if(fs==NULL){
printf("\nCannot Open the file");
exit(0);
}
ft=fopen("newpr1.exe","wb");
if(ft==NULL) {
printf("\nCannot open the file");
fclose(fs);
exit( 0);
}
while((ch=getc(fs))!=EOF)
putc(ch,ft);
fclose(fs);
fclose(ft);
}

ld

Text files Vs Binary Files

JN

TU

ab+  open a file in read and append mode


Text File :
i) Data are human readable characters.
ii) Each line ends with a newline character.
iii) Ctrl+z or Ctrl+d is end of file character.
iv) Data is read in forward direction only.
v) Data is converted into the internal format
before being stored in memory.
Binary File :
i) Data is in the form of sequence of bytes.
ii) There are no lines or newline character.
iii) An EOF marker is used.
iv) Data may be read in any direction.
v) Data stored in file are in same format that
they are stored in memory.

JNTU World

www.alljntuworld.in

JNTU World

ftell(file_pointer)
-- returns the current position of file
pointer in terms of bytes from the
beginning.
rewind(file-pointer)
-- moves the file pointer to the
starting of the file, and reset it.
fseek(fileptr, offset, position)
moves the file pointer to the
location (position + offset)
position :
SEEK_SET beginning of file
SEEK_CUR current position
SEEK_END end of the file

JN

TU

or

int main() {
int n,i;
char *str="abcdefghijklmnopqrstuvwxyz";
FILE *fp = fopen("notes.txt","w");
if(fp==NULL){
printf("\nCannot open file."); exit(0);
}
fprintf(fp,"%s",str);
fclose(fp);
fp = fopen("notes.txt","r");
printf("\nText from position %d : \n\t,ftell(fp));
fseek(fp, 3 ,SEEK_SET);
for(i=0; i < 5; i++) putchar(getc(fp));
printf("\nText from position %d : \n\t,ftell(fp));
fseek(fp, 4 ,SEEK_CUR);
for(i=0; i < 6; i++) putchar(getc(fp));
fseek(fp, - 10 , SEEK_END);
printf("\nText from position %d : \n\t,ftell(fp));
for(i=0; i < 5; i++) putchar(getc(fp));
printf("\nCurrent position : %d",ftell(fp));
rewind(fp);
printf("\nText from starting : \n\t");
for(i=0;i < 8 ; i++) putchar(getc(fp));
fclose(fp);
}

ld

Random Access File

JNTU World

output :
Text from position 3 :
defgh
Text from position 12 :
mnopqr
Text from position 16 :
qrstu
Current position : 21
Text from starting :
abcdefgh

www.alljntuworld.in

JNTU World

JN

TU

or

/* using fscanf() and fprintf() functions */


#include<stdio.h>
int main( ) {
FILE *fp;
int rno , i;
float avg;
char name[20] , filename[15];
printf("\nEnter the filename\n");
scanf("%s",filename);
fp=fopen(filename,"w");
for(i=1;i<=3;i++) {
printf("Enter rno,name,average
of student no:%d",i);
scanf("%d %s %f",&rno,name,&avg);
fprintf(fp,"%d %s %f\n",rno,name,avg);
}
fclose(fp);
fp=fopen ( filename, "r );
for(i=1;i<=3;i++) {
fscanf(fp,"%d %s %f",&rno,name,&avg);
printf("\n%d %s %f",rno,name,avg);
}
fclose(fp);
}

/*Receives strings from keyboard


and writes them to file
and prints on screen*/
#include<stdio.h>
int main( ) {
FILE *fp;
char s[80];
fp=fopen(poem.txt","w");
if(fp==NULL) {
puts("Cannot open file");exit(0);
}
printf("\nEnter a few lines of text:\n");
while(strlen(gets(s))>0){
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
fp=fopen(poem.txt","r");
if(fp==NULL){
puts("Cannot open file"); exit(0);
}
printf("\nContents of file:\n");
while(fgets(s,79,fp)!=NULL)
printf("%s",s);
fclose(fp);
}

ld

Formatted I / O

JNTU World

www.alljntuworld.in

JNTU World

fputc()

ld

Standard I / O

fgetc()

Individual characters

fgets()

Character Strings

fprintf()

fscanf()

Formatted ASCII

fwrite()

fread()

Binary files

write()

read()

Low-level binary

or

fputs()

JN

TU

/* using putw() and getw() functions */


#include<stdio.h>
int main( ) {
FILE *fp1,*fp2; int i,n;
char *filename;
clrscr();
fp1=fopen("test.txt","w");
for(i=10;i<=50;i+=10)
putw(i,fp1);
fclose(fp1);
do {
printf("\nEnter the filename : \n");
scanf("%s",filename);
fp2=fopen(filename,"r");
if(fp2==NULL)
printf("\nCannot open the file");
} while(fp2==NULL);
while(!feof(fp2)) {
n=getw(fp2);
if(n==-1) printf("\nRan out of data");
else printf("\n%d",n);
}
fclose(fp2);
getch();
}

NAME

Predefined Streams

MEANING

stdin

Standard input (from keyboard)

stdout

Standard output (to monitor)

stderr

Standard error output (to monitor)

stdaux

Standard auxiliary (both input and


output)

stdprn

Standard printer output(to printer)

JNTU World

www.alljntuworld.in

JNTU World

ld

Handling Records (structures) in a File

JN

TU

or

struct player {
char name[40]; int age; int runs;
} p1,p2;
void main() {
int i ; FILE *fp = fopen ( "player.txt", "w");
if(fp == NULL) {
printf ("\nCannot open file."); exit(0);
}
for(i=0;i<3;i++) {
printf("Enter name, age, runs of a player : ");
scanf("%s %d %d",p1.name, &p1.age,&p1.runs);
fwrite(&p1,sizeof(p1),1,fp);
}
fclose(fp);
fp = fopen("player.txt","r");
printf(\nRecords Entered : \n");
for(i=0;i<3;i++) {
fread(&p2,sizeof(p2),1,fp);
printf("\nName : %s\nAge : %d\nRuns : %d",p2.name,p2.age,p2.runs);
}
fclose(fp);
}
JNTU World

www.alljntuworld.in

JNTU World

Error Handling:

or

ld

While operating on files, there may be a chance of having certain errors which will
cause abnormal behavior in our programs.
1)Opening an file that was not present in the system.
2)Trying to read beyond the end of file mark.
3)Device overflow.
4)Trying to use a file that has not been opened.
5)Trying to perform an operation on a file when the file is opened for another type of
operation.
6)Attempting to write to a write-protected file.
feof(fp)
 returns non-zero integer value if
we reach end of the file otherwise zero.

TU

ferror(fp)
 returns non-zero integer value
if an error has been detected otherwise
zero
perror(string)
prints the string, a colon
and an error message specified by the
compiler

JN

file pointer (fp) will return NULL if it


cannot open the specified file.

/* program on ferror( ) and perror ( ) */


#include<stdio.h>
int main(){
FILE *fp;
char ch;
fp=fopen("str.txt","w");
ch=getc(fp);
if(ferror(fp))
perror(Error Raised : ");
else
printf("%c",ch);
fclose(fp);
}

JNTU World

www.alljntuworld.in

JNTU World

ld

fp will return NULL if unable to open


the file

or

feof(fp) returns 1 if it reaches end of


file otherwise 0.

#include<stdio.h>
main(){
FILE *fp1,*fp2;
int i,number;
char *filename;
fp1=fopen("TEST.txt","w");
for(i=10;i<=50;i+=10)
putw(i,fp1);
fclose(fp1);
file:
printf("\nEnter the filename\n");
scanf("%s",filename);
fp2=fopen(filename,"r");
if(fp2==NULL){
printf("\nCannot open the file");
printf("\nType File name again");
goto file;}
else{
for(i=1;i<=10;i++){
number=getw(fp2);
if(feof(fp2)){
printf("\nRan out of data");
break;}
else
printf("\n%d",number); } }
fclose(fp2);}

JN

TU

Output:

JNTU World

Enter the filename


TETS.txt
Cannot open the file
Type the File name again
Enter the filename
TEST.txt
10
20
30
40
50
Ran out of data.

www.alljntuworld.in

JNTU World

Structure of FILE pointer

ld

File Management Functions

Type: FILE
File control structure for streams.
typedef struct {
short level;
unsigned
flags;
char
fd;
unsigned char hold;
short
bsize;
unsigned char *buffer, *curp;
unsigned
istemp;
short
token;
} FILE;

or

rename(old-filename",new-filename");
-- It renames the file with the new name
remove(filename")
-- It removes the file specified (macro)

unlink(filename");
-- It also removes the file name

TU

fcloseall();
-- Closes all the opened streams in the
program except standard streams.

File status functions

JN

feof(file_pointer)
-- to check if end of file has been
reached.
ferror(file_pointer)
-- to check the error status of the file
clearerr(file_pointer)
-- to reset the error status of the file

fflush(file_pointer)
-- Bytes in the buffer transferred to file.
tmpfile ()
-- creates a temporary file, to be deleted
when program is completed.
tmpnam(filename)
-- creates a unique file name

JNTU World

www.alljntuworld.in

JNTU World

JN

TU

or

ld

For More Materials, Text Books, Previous


Papers & Mobile updates of B.TECH,
B.PHARMACY, MBA, MCA of JNTUHYD,JNTU-KAKINADA & JNTU-ANANTAPUR
visit
www.alljntuworld.in

JNTU World

www.alljntuworld.in

JNTU World

ld

Searching techniques

or

Searching :
It is a process to find whether a particular value with specified properties is present or not
among a collection of items.
If the value is present in the collection, then searching is said to be successful, and it
returns the location of the value in the array.
Otherwise, if the value is not present in the array, the searching process displays the
appropriate message and in this case searching is said to be unsuccessful.
1) Linear or Sequential Searching
2) Binary Searching

JN

TU

int main( ) {
int arr [ 50 ] , num , i , n , pos = -1;
printf ("How many elements to sort : ");
scanf ("%d", &n);
printf ("\n Enter the elements : \n\n");
for( i = 0; i < n; i++ ) {
printf (arr [%d ] : , i );
scanf( "%d", &arr[ i ] );
}
printf(\nEnter the number to be searched : );
scanf(%d,&num);
for(i=0;i<n;i++)
if( arr [ i ] == num ) {
pos = i ; break;
}
if ( pos == -1 ) printf( %d does not exist ,num);
else
printf( %d is found at location : %d, num , pos);

JNTU World

Linear_Search (A[ ], N, val , pos )


Step 1 : Set pos = -1 and k = 0
Step 2 : Repeat while k < N
Begin
Step 3 : if A[ k ] = val
Set pos = k
print pos
Goto step 5
End while
Step 4 : print Value is not present
Step 5 : Exit
Searches
-- for each item one by one in the list from
the first, until the match is found.
Efficiency of Linear search :
-- Executes in O ( n ) times where n is the
number of elements in the list.

www.alljntuworld.in

JNTU World

Binary Searching

or

ld

Algorithm:
Before searching, the list of items should be sorted in ascending order.
We first compare the key value with the item in the position of the array. If there is a match, we
can return immediately the position.
if the value is less than the element in middle location of the array, the required value is lie in
the lower half of the array.
if the value is greater than the element in middle location of the array, the required value is lie in
the upper half of the array.
We repeat the above procedure on the lower half or upper half of the array.

JN

TU

Binary_Search (A [ ], U_bound, VAL)


Step 1 : set BEG = 0 , END = U_bound , POS = -1
Step 2 : Repeat while (BEG <= END )
Step 3 :
set MID = ( BEG + END ) / 2
Step 4 :
if A [ MID ] == VAL then
POS = MID
print VAL is available at , POS
GoTo Step 6
End if
if A [ MID ] > VAL then
set END = MID 1
Else
set BEG = MID + 1
End if
End while
Step 5 : if POS = -1 then
print VAL is not present
End if
Step 6 : EXIT

void binary_serch ( int a [], int n, int val ) {


int end = n - 1, beg = 0, pos = -1;
while( beg <= end ) {
mid = ( beg + end ) / 2;
if ( val == a [ mid ] ) {
pos = mid;
printf(%d is available at %d,val, pos );
break;
}
if ( a [ mid ] > val ) end = mid 1;
else beg = mid + 1;
}
if ( pos = - 1)
printf( %d does not exist , val );
}

JNTU World

www.alljntuworld.in

JNTU World

ld

Sorting

or

Sorting is a technique to rearrange the elements of a list in ascending or


descending order, which can be numerical, lexicographical, or any user-defined order.
Ranking of students is the process of sorting in descending order.
EMCET Ranking is an example for sorting with user-defined order.
EMCET Ranking is done with the following priorities.
i) First priority is marks obtained in EMCET.
ii) If marks are same, the ranking will be done with comparing marks obtained in
the Mathematics subject.
iii) If marks in Mathematics subject are also same, then the date of births will be
compared.

TU

Internal Sorting :
If all the data that is to be sorted can be accommodated
at a time in memory is called internal sorting.

JN

External Sorting :
It is applied to Huge amount of data that cannot be
accommodated in memory all at a time. So data in disk
or file is loaded into memory part by part. Each part that
is loaded is sorted separately, and stored in an
intermediate file and all parts are merged into one single
sorted list.
JNTU World

Types of Internal Sortings

Bubble Sort

Insertion Sort

Selection Sort

Quick Sort

Merge Sort

www.alljntuworld.in

JNTU World

ld

Bubble Sort

or

Bubbles up the highest

Sorted

10

54

54

54

47

10

47

47

12

47

10

23

54

12

23

10

19

19

19

23

12

19

10

12

23

19

19

12

12

10

After
Pass 2

After
Pass 3

After
Pass 4

After
Pass 5

54

54

47

47

23

23

TU

JN

Original After
List
Pass 1

Bubble_Sort ( A [ ] , N )
Step 1 : Repeat For P = 1 to N 1
Begin
Step 2 :
Repeat For J = 1 to N P
Begin
Step 3 :
If ( A [ J ] < A [ J 1 ] )
Swap ( A [ J ] , A [ J 1 ] )
End For
End For
Step 4 : Exit

Unsorted

Complexity of Bubble_Sort
The complexity of sorting algorithm is
depends upon the number of comparisons
that are made.
Total comparisons in Bubble sort is

n ( n 1) / 2 n 2 n
Complexity = O ( n 2 )

JNTU World

JNTU World

Bubble Sort

For pass = 1 to N - 1

For J = 1 to N - pass

A[J1]>A[J]

JN

TU

or

void print_array (int a[ ], int n) {


int i;
for (i=0;I < n ; i++) printf("%5d",a[ i ]);
}
void bubble_sort ( int arr [ ], int n) {
int pass, current, temp;
for ( pass=1;(pass < n) ;pass++) {
for ( current=1;current <= n pass ; current++) {
if ( arr[ current - 1 ] > arr[ current ] ) {
temp = arr[ current - 1 ];
arr[ current - 1 ] = arr[ current ];
arr[ current ] = temp;
}
}
}
}
int main() {
int count,num[50],i ;
printf ("How many elements to be sorted : ");
scanf ("%d", &count);
printf("\n Enter the elements : \n\n");
for ( i = 0; i < count; i++) {
printf ("num [%d] : ", i ); scanf( "%d", &num[ i ] );
}
printf("\n Array Before Sorting : \n\n\n");
print_array ( num, count );
bubble_sort ( num, count);
printf("\n\n\n Array After Sorting : \n\n\n");
print_array ( num, count );
}

ld

www.alljntuworld.in

JNTU World

Return

Temp = A [ J 1 ]
A[J1]=A[J]
A [ J ] = Temp

www.alljntuworld.in

JNTU World

78

23 45

32

36

23

78

45

32

36

23

45

78

23

45

78

ld

Insertion Sort

TEMP

Insertion_Sort ( A [ ] , N )
Step 1 : Repeat For K = 1 to N 1
Begin
Step 2 :
Set Temp = A [ K ]
Step 3 :
Set J = K 1
Step 4 :
Repeat while Temp < A [ J ] AND J >= 0
Begin
Set A [ J + 1 ] = A [ J ]
Set J = J - 1
End While
Step 5 :
Set A [ J + 1 ] = Temp
End For
Step 4 : Exit

or

23

32

36

32

36

23

32

45

78

36

23

32

36

45

78

JN

36

32

TU

45

Complexity of Insertion Sort


Best Case : O ( n )
Average Case : O ( n2 )
Worst Case : O ( n2 )

insertion_sort ( int A[ ] , int n ) {


int k , j , temp ;
for ( k = 1 ; k < n ; k++ ) {
temp = A [ k ] ;
j = k - 1;
while ( ( temp < A [ j ] ) && ( j >= 0 ) ) {
A[j+1] =A[j];
j--;
}
A [ j + 1 ] = temp ;
}
}

JNTU World

www.alljntuworld.in

JNTU World

78 45

32

56

23

78

45

23

32

56

32

23

45

78

45

23

32

78

56

23

32

45

78

56

23

32

45

56

78

or

23

Selection_Sort ( A [ ] , N )
Step 1 : Repeat For K = 0 to N 2
Begin
Step 2 :
Set POS = K
Step 3 :
Repeat for J = K + 1 to N 1
Begin
If A[ J ] < A [ POS ]
Set POS = J
End For
Step 5 :
Swap A [ K ] with A [ POS ]
End For
Step 6 : Exit

ld

Selection Sort ( Select the smallest and Exchange )

Smallest

56

45

56

TU

32

JN

Complexity of Selection Sort


Best Case : O ( n2 )
Average Case : O ( n2 )
Worst Case : O ( n2 )

selection_sort ( int A[ ] , int n ) {


int k , j , pos , temp ;
for ( k = 0 ; k < n - 1 ; k++ ) {
pos = k ;
for ( j = k + 1 ; j <= n ; j ++ ) {
if ( A [ j ] < A [ pos ] )
pos = j ;
}
temp = A [ k ] ;
A [ k ] = A [ pos ] ;
A [ pos ] = temp ;
}
}

JNTU World

JNTU World

ld

www.alljntuworld.in

Selection sort

or

Insertion sort

k = 0; k < n - 1 ; k++

k = 1; k < n ; k++

temp = a [ k ]
j=k-1

pos = k

j = k + 1 ; j < n ; j++

TU

temp < a [ j ] && j >= 0

a[ j ] < a[ pos ]

a[j+1]=a[j]
j=j-1

a [ j + 1 ] = temp

pos = j

temp = a[ k ]
a [ k ] = a [ pos ]
a [ pos ] = temp

JN

return

return

JNTU World

www.alljntuworld.in

JNTU World

ld

Bubble sort Insertion sort Selection sort

JN

TU

or

Bubble Sort :
-- very primitive algorithm like linear search, and least efficient .
-- No of swappings are more compare with other sorting techniques.
-- It is not capable of minimizing the travel through the array like insertion sort.
Insertion Sort :
-- sorted by considering one item at a time.
-- efficient to use on small sets of data.
-- twice as fast as the bubble sort.
-- 40% faster than the selection sort.
-- no swapping is required.
-- It is said to be online sorting because it continues the sorting a list as and when it receives
new elements.
-- it does not change the relative order of elements with equal keys.
-- reduces unnecessary travel through the array.
-- requires low and constant amount of extra memory space.
-- less efficient for larger lists.
Selection sort :
-- No of swappings will be minimized. i.e., one swap on one pass.
-- generally used for sorting files with large objects and small keys.
-- It is 60% more efficient than bubble sort and 40% less efficient than insertion sort.
-- It is preferred over bubble sort for jumbled array as it requires less items to be exchanged.
-- uses internal sorting that requires more memory space.
-- It cannot recognize sorted list and carryout the sorting from the beginning, when new elements
are added to the list.

JNTU World

www.alljntuworld.in

JNTU World

ld

Quick Sort A recursive process of sorting


Original-list of 11 elements :

2 11 5 14 0

Algorithm for Quick_Sort :

4 20

or

Set list [ 0 ] as pivot :


pivot

2 11 5 14 0

4 20

Rearrange ( partition ) the elements


into two sub lists :
pivot

11 9 14 20

TU

Sub-list of
lesser elements

Sub-list of
greater elements

Apply Quick-sort
recursively
on sub-list

JN

Apply Quick-sort
recursively
on sub-list

-- set the element A [ start_index ] as pivot.


-- rearrange the array so that :
-- all elements which are less than the pivot
come left ( before ) to the pivot.
-- all elements which are greater than the pivot
come right ( after ) to the pivot.
-- recursively apply quick-sort on the sub-list of
lesser elements.
-- recursively apply quick-sort on the sub-list of
greater elements.
-- the base case of the recursion is lists of size
zero or one, which are always sorted.

Complexity of Quick Sort


Best Case : O ( n log n )
Average Case : O ( n log n )
Worst Case : O ( n2 )

JNTU World

www.alljntuworld.in

JNTU World

Pivot

16

12

16

25 10

25 10

12

or

ld

Partitioning for One Step of Quick Sort

16

25 10

16

25 10 12

16

TU

12

JN

3
3

JNTU World

25 10 12
16 25 10 12

www.alljntuworld.in

JNTU World

or

void quick_sort(int a[ ] , int beg , int end ) {


int loc;
if ( beg < end ) {
loc = partition( a , beg , end );
quick_sort ( a , beg , loc 1 );
quick_sort ( a , loc + 1 , end );
}
}
void print_array (int a [ ],int n) {
int i;
for ( i = 0 ; I < n ; i++ ) printf( "%5d ,a [ i ] ) ;
}
int main () {
int count , num[ 50 ] , i ;
printf ("How many elements to sort : ");
scanf ("%d", &count );
printf ("\n Enter the elements : \n\n");
for( i = 0; i < count; i++ ) {
printf ("num [%d ] : , i );
scanf( "%d", &num[ i ] );
}
printf ( \n Array Before Sorting : \n\n\n );
print_array ( num , count ) ;
quick_sort ( num ,0 , count-1) ;
printf ( "\n\n\n Array After Sorting : \n\n\n );
print_array ( num , count );
}

JN

TU

int partition ( int a [ ], int beg, int end ) {


int left , right , loc , flag = 0, pivot ;
loc = left = beg;
right = end;
pivot = a [ loc ] ;
while ( flag == 0 )
{
while( (pivot <= a [ right ] )&&( loc != right ) )
right - - ;
if( loc == right ) flag = 1;
else {
a [ loc ] = a [ right ] ;
left = loc + 1 ;
loc = right;
}
while ( (pivot >= a [ left ] ) && ( loc != left ) )
left++;
if( loc == left ) flag = 1;
else {
a [ loc ] = a [ left ] ;
right = loc - 1;
loc = left;
}
}
a [ loc ] = pivot;
return loc;
}

ld

Quick Sort Program

JNTU World

www.alljntuworld.in

JNTU World

ld
F

loc = left = beg


flag = 0, right = end
pivot = a [ loc ]

a [ loc ] = a [ right ]
left = loc + 1 ;
loc = right;

a[ loc ] = pivot
return loc

quick_sort ( int a [ ], int beg, int end )

flag = 1

JN

pivot >= a [ left ]


&&loc != left
left = left + 1

flag = 1

or
T

TU

loc == right

pivot <= a [ right ]


&& loc != right

loc == left

a [ loc ] = a [ left ]
right = loc - 1 ;
loc = left;

Flag == 0

right = right - 1

partition ( int a [ ], int beg, int end )

loc == left

loc = partition( a , beg , end )


quick_sort ( a , beg , end )
quick_sort ( a , beg , end )
return

JNTU World

www.alljntuworld.in

JNTU World

ld

Merge Sort ( Divide and conquer )


Divide the array

39

9
9

39

81 45 90 27 72 18

90 27 72 18

81 45
81 45
81

45

or

39

90 27
90

27

72 18

39

72

18

Merge the elements to sorted array

39

45

90

45 81

39 45 81
9

27

27 90

72

18

18 72

18 27 72 90

JN

81

TU

39

-- Merge sort technique sorts a given set


of values by combining two sorted
arrays into one larger sorted arrays.
-- A small list will take fewer steps to sort
than a large list.
-- Fewer steps are required to construct
a sorted list from two sorted lists than
two unsorted lists.
-- You only have to traverse each list
once if they're already sorted .

18 27 39 45 72 81 90

Merge_sort Algorithm
1. If the list is of length 0 or 1, then it is already
sorted.
Otherwise:
2. Divide the unsorted list into two sublists of
about half the size.
3. Sort each sublist recursively by re-applying
merge sort.
4. Merge the two sublists back into one
sorted list.
Time complexity
Worst case - O(n log n)
Best case - O(nlogn) typical, O(n) natural variant
Average case - O( n log n )

JNTU World

www.alljntuworld.in

JNTU World

void print_array (int a [ ],int n) {


int i;
for ( i = 0 ; I < n ; i++ ) printf( "%5d ,a [ i ] ) ;
}
int main () {
int count , num[ 50 ] , i ;
printf ("How many elements to sort : ");
scanf ("%d", &count );
printf ("\n Enter the elements : \n\n");
for( i = 0; i < count; i++ ) {
printf ("num [%d ] : , i );
scanf( "%d", &num[ i ] );
}
printf ( \n Array Before Sorting : \n\n\n );
print_array ( num , count ) ;
merge_sort ( num ,0 , count-1) ;
printf ( "\n\n\n Array After Sorting : \n\n\n );
print_array ( num , count );
}

TU

or

void merge(int a[ ],int low,int high,int mid){


int i, j, k, c[50];
i=low; j=mid+1; k=low;
while( ( i<=mid )&&( j <= high ) ) {
if( a[ i ]<a[ j ] ){
c[ k ]=a[ i ]; k++; i++;
}else {
c[ k ]=a[ j ]; k++; j++;
}
}
while( i<=mid ) { c[k]=a[ i ]; k++; i++; }
while(j<=high) { c[k]=a[ j ]; k++; j++; }
for(i=low;i<k;i++) a[ i ]=c[ i ];
}

ld

Merge Sort - Program

JN

void merge_sort(int a[ ], int low, int high){


int mid;
if( low < high) {
mid=(low+high)/2;
merge_sort (a, low, mid);
merge_sort (a, mid+1 ,high);
merge (a, low, high, mid);
}
}

JNTU World

www.alljntuworld.in

JNTU World

ld

merge

i =low ; j = mid+1;k = low

Merge_Sort

a[ i ] < a[ j ]

c[ k ] =a [ i ] ;
k++ ; i++

c[ k ] =a [ j ] ;
k++ ; j++

i <= mid

or

i <= mid && j <= high

TU

c[ k ] =a [ i ] ; k++ ; i++
j <= high

low < high

mid = ( low + high ) / 2

merge_sort (a, low, mid)


merge_sort (a, mid, high )
Merge (a, low,high , mid)

c[ k ] =a [ j ] ; k++ ; j++

JN

i = low ; i < k ; i ++
a[ i ] = c [ i ]
return

JNTU World

Return

www.alljntuworld.in

JNTU World

or

ld

www.alljntuworld.in

JN

TU

For More Materials, Text Books, Previous


Papers & Mobile updates of B.TECH,
B.PHARMACY, MBA, MCA of JNTUHYD,JNTU-K
KAKINADA & JNTU-ANANTAPUR
visit
www.alljntuworld.in

JNTU World

www.alljntuworld.in

JNTU World

Data Structures

or

ld

-- Data processing often involves in processing huge volumes of data. Many Companies handle million
records of data stored in database. Many ways are formulated to handle data efficiently.
-- An User-defined data type is a combination of different primary data types, which represents a complex
entity.
-- An Abstract Data Type ( A D T ) not only represents a set of complex data objects, but also includes a
set of operations to be performed on these objects, defines that how the data objects are organized.
-- The group of methods implements a set rules, which defines a logical way of handling data.
-- The complex entity along with its group of methods is called Abstract Data Type ( A D T ) .
-- Data structure is described as an instance of Abstract Data Type ( ADT ).
-- We can define that Data structure is a kind of representation of logical relationship between related
data elements. In data structure, decision on the operations such as storage, retrieval and access must be
carried out between the logically related data elements.

Data Structure

Linear Lists

Non-Linear

TU

Linear

Stacks

Queues

Trees

JN

Some Common Operations on Data structures


Insertion : adding a new element to the collection.
Deletion : removing an element from a collection.
Traversal : access and examine each element in collection.
Search : find whether an element is present or not.
Sorting : rearranging elements in a particular order.
Merging : combining two collections into one collection.

JNTU World

Graphs

Some Data structures


Arrays
Strings
Lists
Stacks
Queues
Trees
Graphs
Dictionaries
Maps
Hash Tables
Sets
Lattice
Neural-Nets

www.alljntuworld.in

JNTU World

2)

4)

JN

5)

TU

3)

What is a Linked List


The elements of a linked list are not constrained to
be stored in adjacent locations. The individual
elements are stored somewhere in memory, rather
like a family dispersed, but still bound together. The
order of the elements is maintained by explicit links
between them.

or

1)

Limitations of Arrays
Fixed in size :
Once an array is created, the size of array
cannot be increased or decreased.
Wastage of space :
If no. of elements are less, leads to wastage of
space.
Sequential Storage :
Array elements are stored in contiguous
memory locations. At the times it might so
happen that enough contiguous locations might
not be available. Even though the total space
requirement of an array can be met through a
combination of non-contiguous blocks of
memory, we would still not be allowed to create
the array.
Possibility of overflow :
If program ever needs to process more than the
size of array, there is a possibility of overflow
and code breaks.
Difficulty in insertion and deletion :
In case of insertion of a new element, each
element after the specified location has to be
shifted one position to the right. In case of
deletion of an element, each element after the
specified location has to be shifted one position
to the left.

ld

Arrays Linked Lists

The Linked List is a collection of elements called


nodes, each node of which stores two items of
information, i.e., data part and link field.
-- The data part of each node consists the data
record of an entity.
-- The link field is a pointer and contains the
address of next node.
-- The beginning of the linked list is stored in a
pointer termed as head which points to the first node.
-- The head pointer will be passed as a parameter
to any method, to perform an operation.
-- First node contains a pointer to second node,
second node contains a pointer to the third node and
so on.
-- The last node in the list has its next field set to
NULL to mark the end of the list.

JNTU World

www.alljntuworld.in

JNTU World

ld

Creating a Singly Linked List


/* deleting n2 node */
n1->next = n4;
free(n2);

or

150

TU

JN

150

101

NULL

head

150

n1-node

720

102

150

struct node {
int rollno; struct node *next;
};
int main() {
struct node *head,*n1,*n2,*n3,*n4;
/* creating a new node */
n1=(struct node *) malloc(sizeof(struct node));
n1->rollno=101;
n1->next = NULL;
/* referencing the first node to head pointer */
head = n1;
/* creating a new node */
n2=(struct node *)malloc(sizeof(struct node));
n2->rollno=102;
n2->next = NULL;
/* linking the second node after first node */
n1->next = n2;
/* creating a new node * /
n3=(struct node *)malloc(sizeof(struct node));
n3->rollno=104;
n3->next=NULL;
/* linking the third node after second node */
n2->next = n3;
/* creating a new node */
n4=(struct node *)malloc (sizeof (struct node));
n4->rollno=103;
n4->next=NULL;
/* inserting the new node between
second node and third node */
n2->next = n4;
n4->next = n3;

101

720
n2-node

150
n1-node
101

720

102

101

head

150
n1-node

400

102

910

720
n2-node

150
n1-node

150

NULL

104 NULL
910
n3-node

720

400
n2-node

104 NULL
103

910

910
n3-node

720
n4-node

150

101

head

150

103

720

n1-node
102

720

400
n2-node

JNTU World

910
720
n4-node

104 NULL
910
n3-node

www.alljntuworld.in

JNTU World

or

}
void insert_after(struct node **h) {
struct node *new,*temp; int k;
if(*h == NULL) return;
printf("\nEnter data of node after which node : ");
scanf("%d",&k);
temp = *h;
while(temp!=NULL && temp->data!=k)
temp = temp->next;
if(temp!=NULL) {
new=createnode();
new->next = temp->next;
temp->next = new;
}
}
void insert_before(struct node **h) {
struct node *new,*temp,*prev ;
int k;
if(*h==NULL) return;
printf("\nEnter data of node before which node : ");
scanf("%d",&k);
if((*h)->data == k) {
new = createnode();
new->next = *h;
*h = new; return;
}
temp = (*h)->next; prev = *h;

JN

TU

struct node {
int data;
struct node *next;
};
struct node *createnode() {
struct node *new;
new = (struct node *)malloc(sizeof(struct node));
printf("\nEnter the data : ");
scanf("%d",&new->data);
new->next = NULL;
return new;
}
void append(struct node **h) {
struct node *new,*temp;
new = createnode();
if(*h == NULL) {
*h = new;
return;
}
temp = *h;
while(temp->next!=NULL) temp = temp->next;
temp->next = new;
}
void display(struct node *p) {
printf("\nContents of the List : \n\n");
while(p!=NULL) {
printf("\t%d",p->data);
p = p->next;

ld

Implementing Singly Linked List

JNTU World

www.alljntuworld.in

JNTU World

ld

Implementing Singly Linked List ( continued )


if(temp!=NULL) {
prev->next = temp->next;
free(temp);
}

or

while(temp!=NULL && temp->data!=k) {


prev=temp;
temp=temp->next;
}
if(temp!=NULL) {
new = createnode();
new->next = temp;
prev->next = new;
}

}
void search(struct node *h) {
struct node *temp;
int k;
if(h==NULL)return;
printf("\nEnter the data to be searched : ");
scanf("%d",&k);
temp=h;
while(temp!=NULL && temp->data!=k)
temp=temp->next;
(temp==NULL)?
printf("\n\t=>Node does not exist") :
printf("\n\t=>Node exists");
}
void destroy(struct node **h) {
struct node *p;
if(*h==NULL) return;
while(*h!=NULL) {
p = (*h)->next;
free(*h);
*h=p;
}
printf("\n\n ******Linked List is destroyed******");
}

JN

TU

}
void delnode(struct node **h) {
struct node *temp,*prev;
int k;
if(*h==NULL) return;
printf("\nEnter the data of node to be removed : ");
scanf("%d",&k);
if((*h)->data==k) {
temp=*h;
*h=(*h)->next;
free(temp);
return;
}
temp=(*h)->next;
prev=*h;
while(temp!=NULL && temp->data!=k) {
prev=temp;
temp=temp->next;
}

JNTU World

www.alljntuworld.in

JNTU World

or

/* function to sort linked list */


void sort(struct node *h) {
struct node *p,*temp;
int i, j, n, t, sorted=0;
temp=h;
for(n=0 ; temp!=NULL ; temp=temp->next) n++;
for(i=0;i<n-1&&!sorted;i++) {
p=h; sorted=1;
for(j=0;j<n-(i+1);j++) {
if ( p->data > ( p->next )->data ) {
t=p->data;
p->data =(p->next)->data;
(p->next)->data = t;
sorted=0;
}
p=p->next;
}
}
}

JN

TU

int main() {
struct node *head=NULL;
int ch;
while(1) {
printf("\n1.Append");
printf("\n2.Display All");
printf("\n3.Insert after a specified node");
printf("\n4.Insert before a specified node");
printf("\n5.Delete a node");
printf("\n6.Search for a node");
printf("\n7.Distroy the list");
printf("\n8.Exit program");
printf("\n\n\tEnter your choice : ");
scanf("%d",&ch);
switch(ch) {
case 1:append(&head);break;
case 2:display(head);break;
case 3:insert_after(&head);break;
case 4:insert_before(&head);break;
case 5:delnode(&head);break;
case 6:search(head);break;
case 7:destroy(&head);break;
case 8:exit(0);break;
default :
printf( "Wrong Choice, Enter correct one : ");
}
}

ld

Implementing Singly Linked List ( continued )

/* function to count number of node in the list */


int count ( struct node *h)
{
int i;
for( i=0 ; h!=NULL ; h=h->next)
i++;
return i;
}

JNTU World

www.alljntuworld.in

JNTU World

ld

Algorithm for adding two polynomials in linked lists

JN

TU

or

Add_Polynomial( list p, list q )


set p, q to point to the two first nodes (no headers)
initialize a linked list r for a zero polynomial
while p != null and q != null
if p.exp > q.exp
create a node storing p.coeff and p.exp
insert at the end of list r
advance p
else if q.exp > p.exp
create a node storing q.coeff and q.exp
insert at the end of list r
advance q
else if p.exp == q.exp
if p.coeff + q.coeff != 0
create a node storing p.coeff + q.coeff and p.exp
insert at the end of list r
advance p, q
end while
if p != null
copy the remaining terms of p to end of r
else if q != null
copy the remaining terms of q to end of r

JNTU World

www.alljntuworld.in

JNTU World

Doubly Linked List

or

ld

Pitfalls encountered while using singly linked list :


1) A singly linked list allows traversal of the list in forward direction, but not in backward direction.
2) Deleting a node from a list requires keeping track of the previous node,.
3) In the list any node gets corrupted, the remaining nodes of the list become unusable.
These problems of singly linked lists can be overcome by doubly linked list.

TU

head

A Doubly Linked List is a data structure having an ordered list of nodes, in which each node consists
of two pointers. One pointer is to store the address of next node like in singly linked list. The second
pointer stores the address of previous node. It is also known as two-way list.
The specialty of DLL is that the list can be traversed in forward as well as backward directions.
The concept of DLL is also used to representing tree data structures.

JN

/* a node in doubly linked list */


struct node
{
struct node *prev;
int data ;
struct node *next;
}

tail

C
B

D
C

Tree structure using Doubly Linked List

JNTU World

www.alljntuworld.in

JNTU World

ld

Insertion of node in Doubly Linked List

or

p
A

TU

Deletion of node in Doubly Linked List

JN

p
D

B
JNTU World

www.alljntuworld.in

JNTU World

or

void forward_display(struct node *p)


{
printf("\nContents of the List : \n\n");
while(p!=NULL)
{
printf("\t%d",p->data);
p = p->next;
}
printf("\n");
}
void insert_after(struct node **h) {
struct node *new,*temp;
int k;
if(*h == NULL) return;
printf("\nEnter data of node after which node : ");
scanf("%d",&k);
temp = *h;
while(temp!=NULL && temp->data!=k)
temp = temp->next;
if(temp!=NULL) {
new=createnode();
new->next = temp->next;
temp->next = new;
new->prev = temp;
if(new->next != NULL)
new->next->prev = new;
}
}

JN

TU

struct node {
struct node *prev;
int data;
struct node *next;
};
struct node *createnode() {
struct node *new;
new = (struct node *)malloc(sizeof(struct node));
printf("\nEnter the data : ");
scanf("%d",&new->data);
new->prev = NULL;
new->next = NULL;
return new;
}
void append(struct node **h) {
struct node *new,*temp;
new = createnode();
if(*h == NULL)
{
*h = new;
return;
}
temp = *h;
while(temp->next!=NULL)
temp = temp->next;
temp->next = new;
new->prev = temp;
}

ld

Implementing Doubly Linked List

JNTU World

www.alljntuworld.in

JNTU World

or

void delnode(struct node **h)


{
struct node *temp;
int k;
if(*h==NULL)
return;
printf("\nEnter the data of node to be removed : ");
scanf("%d",&k);
if((*h)->data==k)
{
temp=*h;
*h=(*h)->next;
(*h)->prev=NULL;
free(temp);
return;
}
temp=*h;
while(temp!=NULL && temp->data!=k)
{
temp=temp->next;
}
if(temp!=NULL)
{
temp->next->prev = temp->prev;
temp->prev->next = temp->next;
free(temp);
}
}

JN

TU

void insert_before(struct node **h)


{
struct node *new,*temp;
int k;
if(*h==NULL) return;
printf("\nEnter data of node before which node : ");
scanf("%d",&k);
if((*h)->data == k) {
new = createnode();
new->next = *h;
new->next->prev=new;
*h = new;
return;
}
temp = *h;
while(temp!=NULL && temp->data!=k)
{
temp=temp->next;
}
if(temp!=NULL)
{
new = createnode();
new->next = temp;
new->prev = temp->prev;
new->prev->next = new;
temp->prev = new;
}
}

ld

Implementing Doubly Linked List ( continued )

JNTU World

www.alljntuworld.in

JNTU World

or

int main() {
struct node *head=NULL;
int ch;
while(1) {
printf("\n1.Append");
printf("\n2.Display All");
printf("\n3.Insert after a specified node");
printf("\n4.Insert before a specified node");
printf("\n5.Delete a node");
printf("\n6.Search for a node");
printf("\n7.Distroy the list");
printf("\n8.Exit program");
printf("\n\n\tEnter your choice : ");
scanf("%d",&ch);
switch(ch) {
case 1:append(&head);break;
case 2:forward_display(head);break;
case 3:insert_after(&head);break;
case 4:insert_before(&head);break;
case 5:delnode(&head);break;
case 6:search(head);break;
case 7:destroy(&head);break;
case 8:exit(0);break;
default :
printf("Wrong Choice, Enter correct choice : ");
}
}
}

JN

TU

void search(struct node *h)


{
struct node *temp;
int k;
if(h==NULL)
return;
printf("\nEnter the data to be searched : ");
scanf("%d",&k);
temp=h;
while(temp!=NULL && temp->data!=k)
temp=temp->next;
if (temp==NULL)
printf("\n\t=>Node does not exist")
else
printf("\n\t=>Node exists");
}
void destroy(struct node **h)
{
struct node *p;
if(*h==NULL) return;
while(*h!=NULL)
{
p = (*h)->next;
free(*h);
*h=p;
}
printf("\n\n ******Linked List is destroyed******");
}

ld

Implementing Doubly Linked List ( continued )

JNTU World

www.alljntuworld.in

JNTU World

400

102

150
n1-node

720

400
n2-node

103

910

910

104 150

tail

ld

101

Circular Singly
Linked List

720
n3-node

910
n4-node

or

-- Singly Linked List has a major drawback. From a specified node, it is not possible to reach any of
the preceding nodes in the list. To overcome the drawback, a small change is made to the SLL so that the
next field of the last node is pointing to the first node rather than NULL. Such a linked list is called a
circular linked list.
-- Because it is a circular linked list, it is possible to reach any node in the list from a particular node.
-- There is no natural first node or last node because by virtue of the list is circular.
-- Therefore, one convention is to let the external pointer of the circular linked list, tail, point to the last
node and to allow the following node to be the first node.
-- If the tail pointer refers to NULL, means the circular linked list is empty.

prev

TU

Circular Doubly Linked List


data

next

prev

data

next

prev

data

next

prev

data

next

JN

-- A Circular Doubly Linked List ( CDL ) is a doubly linked list with first node linked to last node and viceversa.
-- The prev link of first node contains the address of last node and next link of last node contains
the address of first node.
-- Traversal through Circular Singly Linked List is possible only in one direction.
-- The main advantage of Circular Doubly Linked List ( CDL ) is that, a node can be inserted into list
without searching the complete list for finding the address of previous node.
-- We can also traversed through CDL in both directions, from first node to last node and vice-versa.

JNTU World

www.alljntuworld.in

JNTU World

Implementing Circular Singly Linked List

or

ld

void insert_after(struct node **t)


{
struct node *new,*temp;
int k, found=0;
if(*t == NULL) return;
printf("\nEnter data of node after which node : ");
scanf("%d",&k);
if((*t)->data==k)
{
new = createnode();
new->next = (*t)->next;
(*t)->next = new;
*t=new;
return;
}
temp=(*t)->next;
while(temp!=*t)
{
if(temp->data == k)
{
new = createnode();
new->next = temp->next;
temp->next = new;
found=1;
break;
}
temp=temp->next;
}
if(found==0) printf("\nNode does not exist..");
}

JN

TU

struct node {
int data; struct node *next;
};
struct node *createnode() {
struct node *new;
new = (struct node *)malloc(sizeof(struct node));
printf("\nEnter the data : ");
scanf("%d",&new->data);
new->next = NULL;
return new;
}
void append(struct node **t) {
struct node *new,*head;
new = createnode();
if(*t == NULL) {
*t = new; new->next = *t;
return;
}
head = (*t)->next; (*t)->next = new;
new->next = head; *t = new;
}
void display(struct node *t) {
struct node *temp = t->next, *head=t->next;
printf("\nContents of the List : \n\n");
do {
printf("\t%d",temp->data);temp = temp->next;
}while(temp!=head);
printf(\n);
}

JNTU World

www.alljntuworld.in

JNTU World

Implementing Circular Singly Linked List ( continued )

or

ld

void delnode(struct node **t) {


struct node *temp,*prev,*head;
int k,found=0;
if(*t==NULL) return;
printf("\nEnter the data of node to be removed : ");
scanf("%d",&k);
head=(*t)->next;
if(head->data==k) {
temp=head;
if(temp->next!=head) (*t)->next=head->next;
else *t = NULL;
free(temp);
return;
}
temp=head->next; prev=head;
while(temp!=head) {
if(temp->data == k) {
prev->next = temp->next;
if(temp==*t) *t = prev;
free(temp);
found=1;
break;
} else {
prev=temp;
temp=temp->next;
}
}
if(found==0) printf("\nNode does not exist..");
}

JN

TU

void insert_before(struct node **t) {


struct node *new,*temp,*prev,*head;
int k,found=0;
if(*t==NULL) return;
printf("\nEnter data of node before which node : ");
scanf("%d",&k);
head=(*t)->next;
if(head->data == k) {
new = createnode();
new->next = head;
(*t)->next = new;
return;
}
temp = head->next;
prev = head;
while(temp!=head) {
if(temp->data==k) {
new = createnode();
prev->next = new;
new->next = temp;
found=1;
break;
} else {
prev=temp;
temp=temp->next;
}
}
if(found==0) printf("\nNode does not exist..");
}

JNTU World

www.alljntuworld.in

JNTU World

or

Types of Data Structures

Data structures are classified in several ways :


Linear : Elements are arranged in sequential
fashion. Ex : Array, Linear list, stack, queue
Non-Linear : Elements are not arranged in
sequence. Ex : trees, graphs
Homogenous : All Elements are belongs to same
data type. Ex : Arrays
Non-Homogenous : Different types of Elements
are grouped and form a data structure. Ex:
classes
Dynamic : Memory allocation of each element in
the data structure is done before their usage
using D.M.A functions Ex : Linked Lists
Static : All elements of a data structure are created
at the beginning of the program. They cannot
be resized. Ex : Arrays

JN

TU

int main() {
struct node *tail=NULL;
int ch;
while(1) {
printf("\n1.Append");
printf("\n2.Display All");
printf("\n3.Insert after a specified node");
printf("\n4.Insert before a specified node");
printf("\n5.Delete a node");
printf("\n6.Exit program");
printf("\n\n\tEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:append(&tail);break;
case 2:display(tail);break;
case 3:insert_after(&tail);break;
case 4:insert_before(&tail);break;
case 5:delnode(&tail);break;
case 6:exit(0);break;
default :
printf(\n\tWrong Choice );
}
}
}

ld

Implementing Circular Singly


Linked List ( continued )

JNTU World

www.alljntuworld.in

JNTU World

ld

Stacks

or

-- Stack is an ordered collection of data elements into which new elements may be inserted and from
which elements may be deleted at one end called the TOP of stack.
-- A stack is a last-in-first-out ( LIFO ) structure.
-- Insertion operation is referred as PUSH and deletion operation is referred as POP.
-- The most accessible element in the stack is the element at the position TOP.
-- Stack must be created as empty.
-- Whenever an element is pushed into stack, it must be checked whether the stack is full or not.
-- Whenever an element is popped form stack, it must be checked whether the stack is empty or not.
-- We can implement the stack ADT either with array or linked list.

Applications of stack

JN

TU

 Reversing Data series


 Conversion decimal to binary
 Parsing into tokens
 Backtracking the operations
 Undo operations in Text Editor
 Page visited History in web browser
 Tracking of Function calls
 Maintaining scope and lifetime of local
variables in functions
 Infix to postfix conversion
 Evaluating postfix expression

JNTU World

Stack ADT
struct stackNode {
int data; struct stackNode *next;
};
 init_stack( )
 push ( )
 pop ( )
 isEmpty ( )
 display ( )
 peek ( )

www.alljntuworld.in

JNTU World

Pop( ) Push(d) Push(e)

e
b

Pop( )

Pop( )

or

Pop( )

ld

Push(a) Push(b) Push(c)

Operations on Stack

Operation

<empty>
a
ab
abc
ab
abd
abde
abd
ab
a
<empty>

JN

TU

1. Init_stack( )
2. Push( a )
3. Push( b )
4. Push( c )
5. Pop( )
6. Push( d )
7. Push( e )
8. Pop( )
9. Pop( )
10. Pop( )
11. Pop( )

Stacks contents

JNTU World

TOP value
-1
0
1
2
1
2
3
2
1
0
-1

Output

c
c
c
ce
ced
cedb
cedba

Pop( )

www.alljntuworld.in

JNTU World

Implementing Stack ADT using Array

or

ld

int main() {
int choice,item;
init_stack();
do
{
printf("\n\t\t\tMenu\n\t1.Push.\n\t2.Pop.");
printf("\n\t3.Peek.\n\t4.Display.\n\t5.Exit.\n");
printf("\nYour Choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("\nEnter the element to push : ");
scanf("%d",&item);
push(item); break;
case 2:item = pop();
printf("\nElement poped : %d",item);
printf("\nPress a key to continue...");
getche(); break;
case 3:item = peek();
printf("\nElement at top : %d",item);
printf("\nPress a key to continue...");
getche(); break;
case 4:display();
printf("\nPress a key to continue...");
getche(); break;
case 5:exit(0);
}
}while(1);
}

JN

TU

#define SIZE 50
int stack[SIZE]; int top;
void init_stack() {
top=-1;
}
void push( int n ) {
if( top==SIZE-1) printf("\nStack is full");
else stack[++top]= n;
}
int pop( ) {
if(top== -1) {
printf("\nStack is empty");
return -1;
} else return stack[top--];
}
void display( ) {
int i;
if(top== -1) printf("\nStack is empty.");
else {
printf("\nElements are : \n");
for(i=0;i<=top;i++)
printf("%5d ",stack[i]);
}
}
int isEmpty( ) {
if ( top== -1 ) return 1;
else return 0;
}
int peek( ){ return stack[top]; }

JNTU World

www.alljntuworld.in

JNTU World

Implementing Stack ADT using Linked List

ld

while(temp!=NULL) {
printf("%d\t",temp->data);
temp=temp->link;
}

or

}
void main() {
int choice,num,i;
while(1) {
printf("\n\t\t MENU\n1. Push\n2. Pop\n3. Peek");
printf("\n4. Elements in Stack\n5. Exit\n");
printf("\n\tEnter your choice: ");
scanf("%d",&choice);
switch(choice) {
case 1: printf("\nElement to be pushed:");
scanf("%d",&num);
push(num); break;
case 2: num=pop();
printf("\nElement popped: %d ",num);
getch(); break;
case 3: num=peek();
printf("\nElement peeked : %d ",num);
getch(); break;
case 4: printf("\nElements present in stack : ):
display();getch(); break;
case 5: exit(1);
default: printf("\nInvalid Choice\n"); break;
}
}
}

JN

TU

struct s_node {
int data;
struct s_node *link;
} *stack;
void push(int j) {
struct s_node *m;
m=(struct s_node*)malloc(sizeof(struct s_node));
m->data= j ; m->link=stack;
stack=m; return;
}
int pop( ) {
struct s_node *temp=NULL;
if(stack==NULL) {
printf("\nSTACK is Empty."); getch();
} else {
int i=stack->data;
temp = stack ; stack=stack->link;
free(temp); return (i);
}
}
int peek( ) {
if(stack==NULL) {
printf("\nSTACK is Empty."); getch();
} else
return (stack->data);
}
void display() {
struct s_node *temp=stack;

JNTU World

www.alljntuworld.in

JNTU World

ld

Queues

rear

front

TU

3
addq (4)

or

-- Queue is a linear data structure that permits insertion of new element at one end and deletion of an
element at the other end.
-- The end at which insertion of a new element can take place is called rear and the end at which
deletion of an element take place is called front .
-- The first element that gets added into queue is the first one to get removed from the list, Hence
Queue is also referred to as First-In-First-Out ( FIFO ) list.
-- Queue must be created as empty.
-- Whenever an element is inserted into queue, it must be checked whether the queue is full or not.
-- Whenever an element is deleted form queue, it must be checked whether the queue is empty or not.
-- We can implement the queue ADT either with array or linked list.

delq ( )

Queue ADT
struct queueNode {
int data; struct queueNode *next;
};
 init_queue( )
 addq ( )
 delq ( )
 isEmpty ( )
 printQueue ( )

Applications of Queues

JN

 Execution of Threads
 Job Scheduling
 Event queuing
 Message Queueing

Types of Queues
 circular queues
 priority queues
 double-ended queues

JNTU World

www.alljntuworld.in

JNTU World

Implementing Queue ADT using Array

ld

printf("\nElements are : \n");


for (i=front;i<=rear;i++)
printf("%5d",queue[i]);

or

}
int main() {
int ch,num;
init_queue();
do
{
printf("\n\tMENU\n\n1. Add to Queue);
printf(\n2. Delete form Queue");
printf("\n3. Display Queue\n4. Exit.");
printf("\n\n\tYour Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter an element : ");
scanf("%d",&num);
addq(num);break;
case 2: num=delq();
printf("\nElement deleted : %d",num);
break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nInvalid option..");
}
}while(1);
}

JN

TU

int queue[10] ,front, rear ;


void init_queue() {
front = rear = -1 ;
}
void addq ( int item ){
if ( rear == 9 ) {
printf("\nQueue is full");
return ;
}
rear++ ;
queue [ rear ] = item ;
if ( front == -1 )front = 0 ;
}
int delq( ){
int data ;
if ( front == -1 ) {
printf("\nQueue is Empty");
return 0;
}
data = queue[front] ;
queue[front] = 0 ;
if ( front == rear ) front = rear = -1 ;
else front++ ;
return data ;
}
void display() {
int i;
if(front==-1) printf("\nQueue is empty.");
else {

JNTU World

www.alljntuworld.in

JNTU World

or

else {
printf("\nElements in Queue :\n");
while(temp!=NULL) {
printf("%5d",temp->data);
temp=temp->next;
}
}

}
int main() {
int ch,num;
init_queue();
do {
printf("\n\tMENU\n\n1. Add\n2. Delete");
printf("\n3. Display Queue\n4. Exit.");
printf("\n\n\tYour Choice: ");
scanf("%d",&ch);
switch(ch) {
case 1: printf("\nEnter an element : ");
scanf("%d",&num);
addq(num);break;
case 2: num=delq();
printf("\nElement deleted : %d",num); break;
case 3: display(); break;
case 4: exit(0);
default:printf("\nInvalid option..");
}
}while(1);
}

JN

TU

struct q_node {
int data; struct q_node *next;
}*rear,*front;
void init_queue() {
rear=NULL; front=NULL;
}
void addq(int item) {
struct q_node *t;
t=(struct q_node*)malloc(sizeof(struct q_node));
t->data=item; t->next=NULL;
if(front==NULL) rear=front=t;
else {
rear->next=t; rear=rear->next;
}
}
int delq() {
struct q_node *temp;
if(front==NULL) {
printf("\nQueue is empty."); return 0;
} else {
int num = front->data;
temp = front; front=front->next;
free(temp); return num;
}
}
void display() {
struct q_node *temp=front;
if(front==NULL) printf("\nQueue is empty.");

ld

Implementing Queue ADT using Liked List

JNTU World

www.alljntuworld.in

JNTU World

or

ld

--Arithmetic Expressions are represented using three notations infix, prefix and postfix. The prefixes
pre, post, and in refer to position of operators with respect to two operands.
-- In infix notation, the operator is placed between the two operands.
Ex: A + B
A* B +C
(A * B) + (C * D)
-- In Prefix notation, the operator is placed before the two operands.
Ex: +AB
*A+BC
+*AB*CD
-- In Postfix notation, the operator is placed after the two operands.
Ex: AB+
ABC+*
AB*CD*+

Algorithm to Infix to Postfix Conversion

JN

TU

In-To-Post ( infix-expression )
Scan the Infix expression left to right
If the character x is an operand
Output the character into the Postfix Expression
If the character x is a left or right parenthesis
If the character is (
Push it into the stack
If the character is )
Repeatedly pop and output all the operators/characters until ( is popped from the stack.
If the character x is a is a regular operator
Check the character y currently at the top of the stack.
If Stack is empty or y is ( or y is an operator of lower precedence than x, then
Push x into stack.
If y is an operator of higher or equal precedence than x,
Pop and output y and push x into the stack.
When all characters in infix expression are processed
repeatedly pop the character(s) from the stack and output them until the stack is empty.

JNTU World

www.alljntuworld.in

JNTU World

In-Fix To Post-Fix convertion

or

ld

y=pop(&s) ;
while(y != '(') {
printf("%c",y);
y=pop(&s) ;
}
} else {
if(s.top ==-1 || s.items[s.top] == '(')
push(&s ,x);
else {
/* y is the top operator in the stack*/
y = s.items[s.top];
/* precedence of y is higher/equal to x*/
if( y=='*' || y=='/'){
printf("%c", pop(&s));
push(&s ,x);
} else if ( y=='+' || y=='-')
/* precedence of y is equal to x*/
if( x=='+' || x=='-') {
printf("%c", pop(&s));
push(&s ,x);
}
/* precedence of y is less than x*/
else
push(&s ,x);
}
}
}
while(s.top != -1) printf("%c",pop(&s));

JN

TU

#define STACKSIZE 20
typedef struct {
int top; char items[STACKSIZE];
}STACK;
/*pushes ps into stack*/
void push(STACK *sptr, char ps) {
if(sptr->top == STACKSIZE-1) {
printf("Stack is full\n"); exit(1);
} else
sptr->items[++sptr->top]= ps;
}
char pop(STACK *sptr) {
if(sptr->top == -1) {
printf("Stack is empty\n"); exit(1);
} else
return sptr->items[sptr->top--];
}
int main() {
int i; STACK s; char x, y, E[20] ;
s.top = -1; /* Initialize the stack is */
printf("Enter the Infix Expression:");
scanf("%s",E);
for(i=0;E[i] != '\0';i++) {
x= E[i];
/* Consider all lowercase letter
from a to z are operands */
if(x<='z' && x>='a') printf("%c",x);
else if(x == '(') push(&s ,x);
else if( x == ') ){

}
JNTU World

www.alljntuworld.in

JNTU World

Evaluation of Post-Fix Expression

or

JN

ld

case '*':push(op1*op2);break;
case '/':push(op1/op2);break;
case '^':push(pow(op1,op2));
break;
}
j++;

}
return pop();

}
int main() {
int j=0;
char expr[20];
float number[20],result;
printf("\nEnter a post fix expression : ");
gets(expr);
while(expr[j]!='\0')
{
if(isalpha(expr[j]))
{
fflush(stdin);
printf("\nEnter number for %c : ",expr[j]);
scanf("%f",&number[j]);
}
j++;
}
result = evaluate(expr,number);
printf("\nThe result of %s is %f",expr,result);
}

TU

#include<stdio.h>
#include<ctype.h>
#include<math.h>
float stack[10];
int top=-1;
void push(char c)
{
stack[++top]=c;
}
float pop() {
float n;
n=stack[top--];
return (n);
}
float evaluate(char expr[], float data[])
{
int j=0;
float op1=0,op2=0;
char ch;
while(expr[j]!='\0') {
ch = expr[j];
if(isalpha(expr[j]))
{
push(data[j]);
} else {
op2=pop();
op1=pop();
switch(ch) {
case '+':push(op1+op2);break;
case '-':push(op1-op2);break;

JNTU World

JNTU World

JN

TU

or

ld

www.alljntuworld.in

JNTU World

Você também pode gostar