Professional Documents
Culture Documents
CPDS Material PDF
CPDS Material PDF
in
JNTU World
Mouse
Output
Storage
Area
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
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
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
Parallegram
Input/output
or
Oval
Rectangle
Diamond
Decision
Connector
TU
Circle
Hard copy
Document
Process
Sub program
Hexagon
Iteration
Trapezoid
Manual Operation
Cylinder
JN
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
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
www.alljntuworld.in
JNTU World
Documentation Section
or
Linkage Section
Definition 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
JN
TU
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
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
or
compiles
C-compiler
Text
Editor
ld
Executing a C program
Output
JNTU World
www.alljntuworld.in
JNTU World
ld
or
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
JNTU World
www.alljntuworld.in
JNTU World
ld
C-Tokens
JN
TU
or
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
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
JNTU World
www.alljntuworld.in
JNTU World
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)
Evaluation of expression
Executes all Postfix Operations
or
ld
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
ld
Bitwise OR
Bitwise XOR
Bitwise NOT
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
ld
TYPE CONVERSION
1.bool
(forcible)
.
.
.
2.char
TU
Opposite
To
Gravity
or
(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
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
False
Test
Expression
?
or
simple if:
FalseFalse-block
Statements
Next statement
JNTU World
JNTU World
ld
www.alljntuworld.in
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
?
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
ld
switch statement :
JN
Exit
Next statement
JNTU World
www.alljntuworld.in
JNTU World
Loop Statements
ld
or
Test
Condition
?
true
Entry
False
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
Following Statement
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
ld
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
JNTU World
www.alljntuworld.in
JNTU World
ld
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.
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
or
ld
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:);
}
Called Function
Calling Function
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
Formal Parameters
Function Call
Actual Arguments
TU
}
Return Type
JN
int s;
s = x + y;
return ( s );
Definition of Function
Parameter List used in 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);
}
ld
Categories of Functions
TU
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();
}
or
float a;
num++;
a = (length * breadth);
printf(\nArea of Rectangle %d : %.2f", num, a);
TU
JN
void perimeter()
{
int no = 0;
float p;
no++;
p = 2 *(length + breadth);
printf(Perimeter of Rectangle %d: %.2f",no,p);
}
www.alljntuworld.in
JNTU World
File2.c
File1.c
ld
or
#include<stdio.h>
float length, breadth;
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
ld
Preprocessor Directives
A function
showSquares(1)
showSquares(2)
showSquares(3)
JN
showSquares(4)
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
www.alljntuworld.in
JNTU World
JN
TU
or
ld
JNTU World
www.alljntuworld.in
JNTU World
#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
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
JNTU World
}
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
or
ld
\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
JNTU World
www.alljntuworld.in
JNTU World
ld
or
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
or
TU
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
or
char option = Y;
ptr = &option;
JN
*ptr = N;
4042
TU
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
q NULL
Prints address of n1
n1
q = & n2;
*q = 3 ;
printf ( %d %d , *p , *q ) ;
Prints 6 3
TU
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
#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 */
JNTU World
www.alljntuworld.in
JNTU World
ld
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 )
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 };
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
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]
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
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) );
}
JN
Output :
x contains 7
y contains 23.500000
JNTU World
Output :
Sum = 9
Difference = 4
www.alljntuworld.in
JNTU World
ld
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
free ( p );
p = NULL;
JN
};
struct book b1 ;
b1 *ptr ;
ptr = (book *) calloc ( 10, sizeof ( book ) );
JNTU World
www.alljntuworld.in
JNTU World
printable
isprint ( )
or
graphical
isgraph ()
alpha-numeric
isalnum ( )
digit
isdigit ()
punctuation
ispunct ( )
TU
alphabetic
isalpha( )
space
isspace ( )
upper
isupper ( )
ld
control
iscntrl ( )
lower
islower ()
JN
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
long atol(s)
float atof(s)
void* calloc(u1,u2)
void exit(u)
int rand(void)
void* realloc(p,u)
void srand(u)
void systerm(s)
TU
or
int atoi(s)
<time.h>
Sets time.
double difftime(t1,t2)
JN
clock_t clock()
JNTU World
www.alljntuworld.in
JNTU World
or
Array Type
Pointer
Type
Function
Type
Derived
Types
ld
C Data Types:
Structure
Type
Union Type
TU
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
STRUCTURE- BOOK
Structure tag
JN
struct book {
int book_id ;
char title[50] ;
char author[40] ;
int pages ;
float price ;
};
JNTU World
www.alljntuworld.in
JNTU World
ld
or
struct student
{
int roll_no;
char name[30];
float percentage;
};
Initialization of structure
JN
TU
membership operator
JNTU World
www.alljntuworld.in
JNTU World
or
struct employee {
int empid;
char name[35];
int age;
float salary;
};
int main() {
struct employee emp1,emp2 ;
ld
Implementing a Structure
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
Nesting of structures
ld
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:
7 / 12
TU
int main ( ) {
struct fraction f1 = { 7, 12 } ;
show ( f1 ) ;
}
or
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 ;
};
ld
Prints P.Kiran
Prints B.Mahesh
JN
JNTU World
www.alljntuworld.in
JNTU World
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
JNTU World
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
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.
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
JNTU World
JNTU World
ld
www.alljntuworld.in
or
INTRODUCTION:
rno
TU
{ struct student
JN
int age;
2
ht
age
int rno;
char gender;
gender
wt
4
www.alljntuworld.in
JNTU World
ld
gender
or
float ht;
2
float wt;
};
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
JNTU World
JNTU World
ld
www.alljntuworld.in
or
DEFINING A STRUCTURE:
syntax:
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
JNTU World
JNTU World
ld
www.alljntuworld.in
or
TU
JN
JNTU World
JNTU World
ld
www.alljntuworld.in
or
S1.gender=m; s1.age=25;
Structure
S1.rno=100
variable
Structure member
TU
S1.ht=5.5;
s1.wt=60.2;
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
syntax:
or
rno
100
25
ht
5.5
wt
rno
age
gender
ht
wt
60.2
TU
age
gender
M
s1
JN
JNTU World
ld
www.alljntuworld.in
or
TU
JN
JNTU World
ld
www.alljntuworld.in
or
#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
or
ld
www.alljntuworld.in
TU
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
JNTU World
ld
www.alljntuworld.in
or
TU
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
Array of Structures:
Perhaps the most common usage of structures is an array of
structures.
or
TU
struct student
int rno;
int m1,m2,m3;
JN
int tot,avg;
}
www.alljntuworld.in
JNTU World
ld
or
#include <conio.h>
void main()
TU
struct student
int rno;
JN
int m1,m2,m3;
int tot,avg;
};
JNTU World
JNTU World
or
ld
www.alljntuworld.in
int i,n;
clrscr();
printf(Enter n value\n);
TU
scanf(%d,&n);
JN
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
JN
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
or
TU
struct x
int rno;
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
Nested Structures:
or
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
ld
or
#include<stdio.h>
/*Defining a Structure*/
TU
struct Test
int a;
JN
int b;
};
/*Prototype*/
JNTU World
JNTU World
or
TU
printf(T1.a=%d\n,T1.a);
printf(T1.b=%d\n,T1.b);
}
ld
www.alljntuworld.in
JN
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
The size of union can contain only one type of member at any
one time.
TU
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
JNTU World
JNTU World
or
ld
www.alljntuworld.in
FILE HANDLING IN C
TU
High level
Text
Un formatted
JN
Formatted
Low level
Binary
formatted
JNTU World
Un formatted
www.alljntuworld.in
JNTU World
or
ld
TU
JN
JNTU World
JNTU World
ld
www.alljntuworld.in
or
TU
naming a file
opening a file
reading data from a file
writing data to a file and
closing a file.
JN
JNTU World
JNTU World
ld
www.alljntuworld.in
or
TU
JN
JNTU World
JNTU World
ld
www.alljntuworld.in
or
TU
JN
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
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
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.
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
CLOSING A FILE:
TU
JN
fclose (P1);
JNTU World
JNTU World
ld
www.alljntuworld.in
JN
TU
or
JNTU World
www.alljntuworld.in
JNTU World
ld
or
Void main()
char ch;
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);
JN
JNTU World
JNTU World
ld
www.alljntuworld.in
or
getch();
OUTPUT:
TU
JN
JNTU World
JNTU World
ld
www.alljntuworld.in
or
TU
JN
ex: x= getw(fp);
JNTU World
www.alljntuworld.in
JNTU World
ld
or
#include<stdlib.h>
{
FILE *f;
TU
Void main()
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
exit(1);
}
or
word1=94;
if ( ferror(fp))
putw(word1,fp);
TU
else
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
if ( fp== NULL)
exit(1);
or
TU
JN
else
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
ld
www.alljntuworld.in
or
TU
#include<conio.h>
JN
Void main()
JNTU World
www.alljntuworld.in
JNTU World
ld
or
FILE *fp;
int rno;
float marks;
char name[30];
TU
JN
fclose( fp);
JNTU World
JNTU World
ld
www.alljntuworld.in
or
fclose (fp);
}
student
JN
1. Ravi 30.5
fprintf()
scanf()
Enter students
TU
H.D
fscanf()
JNTU World
1.Ravi 30.5
1 ravi 30.5
prinf()
JNTU World
ld
www.alljntuworld.in
or
TU
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
or
TU
0
1
JN
JNTU World
www.alljntuworld.in
JNTU World
or
ld
FILE *fp;
int n, ch;
TU
clrscr();
fp=fopen( text.txt, r);
JN
while ((ch=fgetc(fp))!=EOF)
printf( %c, ch);
JNTU World
www.alljntuworld.in
JNTU World
ld
or
scanf(%d, &n);
fseek ( fp, n, SEEK_SET)
TU
printf(%c, ch);
fclose(fp);
JN
JNTU World
www.alljntuworld.in
JNTU World
bitfieds
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
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
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
JNTU World
1.
2.
3.
4.
5.
JNTU World
or
ld
www.alljntuworld.in
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
or
ld
JN
TU
JNTU World
JNTU World
ld
www.alljntuworld.in
or
filepointer=fopen(filename,mode);
putc(character,filepointer);
fclose(filepointer);
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
or
ld
rb , wb , ab, rb+ , wb+ , ab+ are modes to operate a file as binary file.
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
fclose(fp)
closeall ( )
fgetc(ch, fp)
fprintf( )
fscanf()
gets()
puts()
getw()
putw()
fwrite()
fseek()
feof()
or
JN
rewind()
TU
fread()
ld
fopen(fp, mode)
ferror()
fflush()
ftell()
www.alljntuworld.in
JNTU World
rb
or
ab
#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
JN
TU
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
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
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
NAME
Predefined Streams
MEANING
stdin
stdout
stderr
stdaux
stdprn
JNTU World
www.alljntuworld.in
JNTU World
ld
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
JNTU World
www.alljntuworld.in
JNTU World
ld
or
#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
www.alljntuworld.in
JNTU World
ld
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.
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
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
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
JNTU World
www.alljntuworld.in
JNTU World
ld
Sorting
or
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
Bubble Sort
Insertion Sort
Selection Sort
Quick Sort
Merge Sort
www.alljntuworld.in
JNTU World
ld
Bubble Sort
or
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
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
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
Smallest
56
45
56
TU
32
JN
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
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
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
2 11 5 14 0
4 20
or
2 11 5 14 0
4 20
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
JNTU World
www.alljntuworld.in
JNTU World
Pivot
16
12
16
25 10
25 10
12
or
ld
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
JN
TU
ld
JNTU World
www.alljntuworld.in
JNTU World
ld
F
a [ loc ] = a [ right ]
left = loc + 1 ;
loc = right;
a[ loc ] = pivot
return loc
flag = 1
JN
flag = 1
or
T
TU
loc == right
loc == left
a [ loc ] = a [ left ]
right = loc - 1 ;
loc = left;
Flag == 0
right = right - 1
loc == left
JNTU World
www.alljntuworld.in
JNTU World
ld
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
39
45
90
45 81
39 45 81
9
27
27 90
72
18
18 72
18 27 72 90
JN
81
TU
39
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
TU
or
ld
JN
JNTU World
www.alljntuworld.in
JNTU World
ld
merge
Merge_Sort
a[ i ] < a[ j ]
c[ k ] =a [ i ] ;
k++ ; i++
c[ k ] =a [ j ] ;
k++ ; j++
i <= mid
or
TU
c[ k ] =a [ i ] ; k++ ; i++
j <= high
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
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
JNTU World
Graphs
www.alljntuworld.in
JNTU World
2)
4)
JN
5)
TU
3)
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
JNTU World
www.alljntuworld.in
JNTU World
ld
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
JNTU World
www.alljntuworld.in
JNTU World
ld
or
}
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
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
JNTU World
www.alljntuworld.in
JNTU World
ld
JN
TU
or
JNTU World
www.alljntuworld.in
JNTU World
or
ld
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
tail
C
B
D
C
JNTU World
www.alljntuworld.in
JNTU World
ld
or
p
A
TU
JN
p
D
B
JNTU World
www.alljntuworld.in
JNTU World
or
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
JNTU World
www.alljntuworld.in
JNTU World
or
JN
TU
ld
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
ld
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
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
or
ld
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
or
ld
JN
TU
JNTU World
www.alljntuworld.in
JNTU World
or
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
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
JNTU World
Stack ADT
struct stackNode {
int data; struct stackNode *next;
};
init_stack( )
push ( )
pop ( )
isEmpty ( )
display ( )
peek ( )
www.alljntuworld.in
JNTU World
e
b
Pop( )
Pop( )
or
Pop( )
ld
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
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
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
ld
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
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
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*+
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
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
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