Académique Documents
Professionnel Documents
Culture Documents
om
Input Output
Key board Storage Program Storage Area
Storage Monitor
Mouse Area Area
.c
Working Storage Area
Printer
m
Input Devices Output Devices
Primary or Main Memory (RAM)
ru
fo
Register 1
ld
Register 2 Arithmetic
or
……
w and
……
tu
Register N
Logic Unit
.jn
Micro Processor
w
w
w
om
Step2: Take a number Step2: Read num
Step3: if the number is divisible by2 then Step3: if(num%2=0) then
.c
print that number is even print num is even
m
otherwise print that number is odd otherwise
print num is odd
ru
Step4: End Step4: STOP
fo
(Algorithm in natural language) (Algorithm by using pseudo code)
ld
#include<stdio.h> start
or
#include<conio.h> Flow chart:
main() w read num
tu
{
int num;
.jn
num%2=0
if(num%2==0)
w
printf(“%d is even”,num);
w
om
Parallegram Input/output
.c
Rectangle Process
m
ru
Document Hard copy
fo
Diamond Decision
ld
or
Circle Connector
w
tu
Double sided Rectangle Sub program
.jn
Hexagon Iteration
w
w
w
om
4 11101111 10111110 0000000000001011 4 moveb $CHAR_STRING_CON
5 11111000 10101101 11011111 0000000000010010 5
6 01100010 11011111 0000000000010101 6 pusha1 -8(fp)
.c
7 11101111 00000010 11111011 0000000000010111 7 pusha1 (r2)
m
8 11110100 10101101 11011111 0000000000011110 8 calls #2,SCANF
9 00000011 10100010 11011111 0000000000100001 9 pusha1 -12(fp)
ru
10 11101111 00000010 11011111 0000000000100100 10 pusha1 3(r2)
11 01111110 11110100 10101101 11 calls #2,SCANF
fo
12 11111000 10101110 11000101 0000000000101011 12 mull3 -8(fp),-12(fp),-
13 00000110 10100010 11111011 0000000000110001 13 pusha 6(fp)
ld
14 11101111 00000010 11111011 0000000000110100 14 calls #2,PRINTF
15 01010000 11010100 0000000000111011 15 clrl r0
or
16 00000100 0000000000111101 16 ret
w
tu
1 #include<stdio.h>
2 int main(void)
The only language the computer can understand is machine
language (binary language).
.jn
3 {
4 int n1, n2,product;
w
5 printf(“Enter two numbers : “); A high level language is an English like language where one
w
8 printf(“%d”,product);
9 return 0;
A low level language corresponds closely to machine code
1 }
0
so that a single low-level language instruction translates to a
single machine language instruction.
Structure of C program
/*Program to find
Documentation Section
area and perimeter of Circle */
#include<stdio.h
#include<stdio.h> > Linkage Section
#define PI 3.1415 Definition Section
om
float radius;
float area(); Global Declaration Section
.c
float perimeter();
m
int main()
{
ru
float a, p; Main Function Section
fo
printf(“Enter
printf(“Enter radius : “);
Local Declaration Part
ld
scanf
scanf(“%
(“%f”,&radius
f”,&radius);
);
a = area(); Executable Code Part
or
p = perimeter();
printf(“Area
printf(“Area of Circle : %%f”,a
f”,a);
); w
tu
printf(“Perimeter
printf(“Perimeter : %
%f”,p
f”,p);
);
}
.jn
float area()
Sub Program Section
{
w
Function1()
}
w
Function2()
float perimeter()
……………
{
FunctionN()
return (2 * PI * radius);
}
Program Development Steps
1)Statement of Problem 4.a)Compilation
a) Working with existing system and using proper Translate the program into machine code. This
questionnaire, the problem should be explained process is called as Compilation. Syntactic errors are
om
clearly. found quickly at the time of compiling the program.
b) What inputs are available, outputs are required These errors occur due to the usage of wrong syntaxes
.c
and what is needed for creating workable solution for the statements.
should be understood clearly. Eg: x=a*y+b
m
2)Analysis There is a syntax error in this statement, since, each
ru
a) The method of solutions to solve the problem can and every statement in C language ends with a
be identified. semicolon (;).
fo
b) We also judge that which method gives best
ld
results among different methods of solution. 4.b)Execution
or
3)Designing The next step is Program execution. In this phase, we
a) Algorithms and flow charts will be prepared. may encounter two types of errors.
w
b) Keep focus on data, architecture, user interfaces Runtime Errors: these errors occur during the
tu
and program components. execution of the program and terminates the program
abnormally.
.jn
4)Implementation
The algorithms and flow charts developed in the Logical Errors: these errors occur due to incorrect
usage of the instructions in the program. These errors
w
om
language program into
C-compiler compiles
machine-language code.
.c
Compiler : Coverts the entire
010110 100 Syntax Yes source program at a time
m
……………. Errors?
01011 101 into object code file, and
ru
No saves it in secondary storage
Object machine code permanently. The same
fo
adds prog1.obj object machine code file will
ld
Linker
be executed several times,
or
00101010
Executable whenever needed.
………….
Interpreter : Each statement of
01010101 machine code w source program is translated
tu
machine code of prog1.exe
library file into machine code and
.jn
Feeds
Runtime
each and every statement is
w
om
Digits : 0-9
Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | \ { } [ ] : ; “ ‘
.c
<>,.?/
m
White Spaces : space , Horizontal tab, Vertical tab, New Line
ru
Form Feed.
fo
ld
C-Language Keywords(C99)
or
auto double int struct
break else w long switch
tu
case enum register typedef
.jn
do if static while
_Bool _Imaginary restrict _Complex
inline
C-Tokens
Tokens : The smallest individual units of a C- program are called Tokens.
Key words, Identifiers, Constants, Operators, Delimiters.
om
Key words : have a predefined meaning and these meanings cannot be
changed. All keywords must be written in small letters (except additional
.c
c99 keywords).
m
Identifiers : names of variables, functions, structures, unions, macros, labels,
ru
arrays etc.,
fo
Rules for define identifiers :
ld
a) First character must be alphabetic character or under score
or
b) Second character onwards alphabetic character of digit or under
score. w
tu
c) First 63 characters of an identifier are significant.
.jn
score.
w
f) C – language is Case-sensitive.
w
C-Tokens
Constants : fixed values that do not change during execution of a program.
Boolean constants : 0 ( false) and 1 (true)
om
Character constants :
only one character enclosed between two single quotes
.c
( except escape characters ).
m
wide character type - wchar_t - for Unicode characters.
ru
Integer constants : +123, -3454 , 0235 (octal value),
fo
0x43d98 ( hexa - decimal value)
ld
54764U, 124356578L, 124567856UL
or
Float constants : 0.2 , 876.345, .345623 , 23.4E+8, 47.45e+6
w
String Constants : “Hello world” , “Have a nice day!”
tu
Complex Constants : real part + imaginary part * I ex : 12.3 + 3.45 * I
.jn
om
unsigned char 8 0 to 255
signed char 8 –127 to 127
.c
int 16 or 32 –32,767 to 32,767
m
unsigned int 16 or 32 0 to 65,535
ru
signed int 16 or 32 Same as int
fo
short int 16 –32,767 to 32,767
unsigned short int 16 0 to 65,535
ld
signed short int 16 Same as short int
or
long int 32 –2,147,483,647 to 2,147,483,647
long long int 64
w –(263) to 263 – 1 (Added by C99)
tu
signed long int 32 Same as long int
.jn
om
%s String of characters (until null zero is reached )
%c Character
.c
%d Decimal integer
%f Floating-point numbers
m
%e Exponential notation floating-point numbers
ru
%g Use the shorter of %f or %e
fo
%u Unsigned integer
ld
%o Octal integer
%x Hexadecimal integer
or
%i Signed decimal integer
%p Display a pointerw
tu
%n The associated argument must be a pointer to integer, This sepecifier causes
.jn
Code Meaning
om
\b Backspace
.c
\f Form feed
m
\n New line
ru
\r Carriage return
fo
\t Horizontal tab
ld
\" Double quote
or
\' Single quote
w
tu
\\ Backslash
.jn
\v Vertical tab
\a Alert
w
w
\? Question mark
w
om
Evaluation of expression
.c
m
Executes all Postfix Operations After evaluation of expression
ru
and before leaving the statement
fo
ld
/* prefix operators */ /* prefix and postfix operators */ /* postfix operators */
#include<stdio.h> #include<stdio.h> #include<stdio.h>
or
int main() { int main() { int main() {
int a = 7, b = 12, c; w
int a = 7, b = 12, c; int a = 7, b = 12, c;
tu
c = b * (++a) + 5 * (++a); c = b * (a++) + 5 * (++a); c = b * (a++) + 5 * (a++);
printf(“ a = %d”, a); printf(“ a = %d”, a); printf(“ a = %d”, a);
.jn
printf(“\
printf(“\n b = %d”,b); printf(“\
printf(“\n b = %d”,b); printf(“\
printf(“\n b = %d”,b);
w
printf(“\
printf(“\n c = %d”,c); printf(“\
printf(“\n c = %d”,c); printf(“\
printf(“\n c = %d”,c);
} } }
w
om
| -- Bitwise OR 1 1 1 1 0 0
1 0 0 1 1 0
.c
^ -- Bitwise XOR 0 1 0 1 1 1
m
~ -- Bitwise NOT 0 0 0 0 0 1
ru
fo
Bitwise AND Bitwise OR
ld
A (42) : 00000000 00101010 A (42) : 00000000 00101010
or
B (15) : 00000000 00001111 B (15) : 00000000 00001111
-----------------------------------
& (10) : 00000000 00001010
w -----------------------------------
tu
| (47) : 00000000 00101111
----------------------------------- -----------------------------------
.jn
om
----------------------------------- ----------------------------------- -----------------------------------
A << 2 : 00000000 10101100 A >> 2 : 00000000 00001010 A >> 2 : 11111111 11110101
.c
----------------------------------- ----------------------------------- -----------------------------------
m
Note : Right shift operator fills the left vacant fields with ‘zeros’ for positive numbers,
with ‘ones’ for negative numbers.
ru
fo
Opposite TYPE CONVERSION Explicit Type Conversion
ld
To
(casting)
Gravity
or
1.bool
2.char w (forcible)
(forcible)
tu
3.short int
4.int .
.jn
.
5.long int .
.
6.long long int .
w
.
w
7.float
(automatic)
w
(natural) 8.double
9.long double
Gravity Implicit Type Conversion
(automatic)
Precedence and Associativity of Operators
Precdence Group Operators Associativity
(Highest to Lowest )
(param) subscript etc., ( ) [ ] –>. LR
om
Unary operators - + ! ~ ++ – – (type) * & sizeof RL
.c
Multiplicative */% LR
m
Additive +– LR
ru
Bitwise shift << >> LR
fo
Relational < <= > >= LR
ld
Equality = = != LR
or
Bitwise AND & LR
Bitwise exclusive OR ^ w LR
tu
Bitwise OR | LR
.jn
Conditional ?: RL
w
w
om
?
False True Statement-
Statement-block
True-
True-block False-
False-block
.c
Statements Statements
m
Next statement
ru
Next statement
fo
ld
/* check a citizen is eligible for voting */ /* print a number is even or odd */
or
#include<stdio.h> #include<stdio.h>
int main() w int main()
{ {
tu
int age; int number;
.jn
getch(); else
} printf(“%d is odd number.”,number);
}
nested if…else: /* check whether a year is leap year or not */
#include<stdio.h>
Entry int main() {
om
int year;
Test printf("Enter the year ?");
False True
.c
condition1 scanf("%d",&year);
m
? if((year %100) == 0)
{
ru
Test
False True if((year % 400) == 0)
condition2
fo
? printf("%d is leap year.",year);
else
ld
Statement
Statement--3 Statement
Statement--2 Statement
Statement--1 printf("%d is not leap year.",year);
or
} else {
w if((year % 4) == 0)
printf("%d is leap year.",year);
tu
else
Next statement
.jn
getch();
w
}
w
if…else…if : /* program to print the grade of student */
om
#include<stdio.h>
Entry int main() {
.c
True
int marks;
Test
m
condition1 Statement
Statement--1 printf("Enter marks ? ");
ru
? scanf("%d", &marks);
False if(marks >= 75)
fo
Test True printf("Distinction");
ld
condition2 Statement
Statement--2 else if(marks >= 60)
or
? printf("First class");
False w else if(marks >= 50)
True
tu
Test printf("Second class");
conditionN Statement
Statement--N else if(marks >= 35)
.jn
?
printf("Third class");
w
printf("Failed");
w
}
switch statement : /* program to simulate a simple calculator */
#include<stdio.h>
Entry int main() {
float a,b;
om
switch char opr;
expression printf("Enter number1 operator number2 : ");
? scanf("%f %c %f",&a,&opr,&b);
.c
switch(opr)
m
value1 value2 valueN default {
ru
……... case '+':
printf("Sum : %f",(a + b));
fo
associate associate associate associate
break;
statement statement statement
ld
statement case ''--':
or
printf("Difference : %f",(a - b));
break;
w case '*':
tu
printf("Product : %f",(a * b));
.jn
break;
case '/':
w
break;
default:
w
om
Test False
.c
Condition Body of The loop
m
?
true Test
ru
False
Body of The loop Condition
fo
?
Following Statement
ld
True Following Statement
or
/* average of 5 numbers */
/* sum of 1 to 10 numbers */
w #include<stdio.h>
#include<stdio.h>
int main() {
tu
int main() {
int count = 1;
int i = 1,sum = 0;
.jn
float x, sum = 0;
while(i<=10){
do {
w
sum = sum + i;
printf(“x = “);
i = i + 1;
w
scanf(“%f”,&x);
}
w
sum += x;
printf(“Total : %d “,sum);
++ count;
}
} while(count <= 5);
printf(“Average = %f “, (sum/5))
}
for -- Statement Entry
Initialization Statement
Increment Statement
om
False Test
Condition
.c
?
True
m
ru
Body of The loop
Following Statement
fo
/* check whether a number is prime or not */
ld
#include<stdio.h>
or
int main() {
w
int n,i,factors = 0;
printf("Enter a number : ");
tu
scanf("%d",&n);
.jn
}
w
if (factors == 2)
w
om
equal to x
.c
floor(x) rounds down and returns the largest integer less than or equal
m
to x
ru
log(x) returns natural logarithm
fo
pow(x,y) returns the value of xy
ld
sqrt(x) returns square root of x
or
exp(x) returns natural anti logarithm
sin(x)
w
returns sine value where x in radians
tu
cos(x) returns cosine value where x in radians
.jn
om
.c
• For More Materials, Text Books, Previous
m
ru
Papers & Mobile updates of B.TECH,
fo
B.P
PHARMACY, MBA, MCA of JNTU-
ld
or
HYD,JNTU-KAKINADA & JNTU-
w
ANANTAPUR visit www.alljntuworld.in
tu
.jn
w
w
w
Modularizing and Reusing of code through Functions
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.
om
/* program to find area of a ring
.c
/* program to find area of a ring */
*/
m
#include<stdio.h>
#include<stdio.h> float area(); Function Declaration
ru
int main() Repeated & Reusable int main()
fo
{ blocks of code {
float a1,a2,a;
ld
float a1,a2,a,r1,r2;
a1 = area(); Function Calls
printf("Enter the radius : ");
or
a2 = area();
scanf("%f",&r1);
a1 = 3.14*r1*r1;
w a = a1- a2;
printf("Area of Ring : %.3f\n", a);
tu
printf("Enter the radius : "); }
.jn
scanf("%f", &r);
a);
return (3.14*r*r);
} }
A Function is an independent, reusable module of statements, that specified by a name.
This module (sub program) can be called by it’s 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
om
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
.c
the caller. The function main() is called by the operating system; main() calls other functions.
m
When main() is complete, control returns to the operating system.
ru
fo
value of ‘p’ is copied to loan’
value of ‘n’ is copied to terms’
ld
int main() {
value of ‘r’ is copied to ‘iRate’
or
int n;
float p, r, si; w
printf(“Enter Details of Loan1:“); float calcInterest(float loan , int terms , float iRate )
tu
{
scanf( “%f %d %f”, &p, &n, &r);
.jn
return ( interest );
printf(“Enter Details of Loan2:“);
w
}
}
w
Called Function
value of ‘interest’ is assigned to ‘si ’
om
readPrintHexa();
printf("Enter a number : ");
1
.c
scanf("%d",&n2);
2 printOctal(n2);
m
printf(“\n”);
3 7
ru
}
Flow of
fo
8 void printOctal(int n) Control
{
ld
printf("Number in octal form : %o \n", n); in
}
or
Multi-Function
6 void readPrintHexa() w Program
{
tu
int num;
.jn
printHexa(num);
printf(“\n”);
w
} 4
w
void printHexa(int n)
5 {
printf("Number in Hexa-Decimal form : %x \n",n);
}
/* Program demonstrates function calls */ Function-It’s Terminology
#include<stdio.h>
int add ( int n1, int n2 ) ; Function Name
int main(void)
om
{ Declaration (proto type) of Function
int a, b, sum;
.c
printf(“Enter two integers : ”); Formal Parameters
m
scanf(“%d %d”, &a, &b);
ru
Function Call
fo
sum = add ( a , b ) ;
printf(“%d + %d = %d\n”, a, b, sum);
ld
return 0; Actual Arguments
or
}
w Return Type
tu
/* adds two numbers and return the sum */
.jn
Definition of Function
int add ( int x , int y )
w
int s;
w
om
int i;
{
for(i=1; i<=35;i++) printf(“%c”, ‘-’);
float radius, area;
.c
printf(“\n”);
printMyLine();
m
}
printf(“\n\tUsage of functions\n”);
ru
printYourLine(‘-’,35); void printYourLine(char ch, int n)
fo
radius = readRadius(); {
Function with parameters
area = calcArea ( radius );
ld
and No return value
printf(“Area of Circle = %f”, int i;
or
area); for(i=1; i<=n ;i++) printf(“%c”, ch);
} w }
printf(“\n”);
tu
.jn
float calcArea(float r)
float readRadius() Function with return {
w
float r;
printf(“Enter the radius : “); a = 3.14 * r * r ;
w
om
scanf("%f %f",&length,&breadth); num++;
area(); a = (length * breadth);
.c
perimeter(); printf(“\nArea of Rectangle %d : %.2f", num, a);
m
printf(“\nEnter length, breadth: "); }
scanf("%f %f",&length,&breadth);
ru
area(); void perimeter()
fo
perimeter(); {
int no = 0;
ld
}
float p;
or
no++;
External Global Variables
Scope: Visible across multiple
w p = 2 *(length + breadth);
printf(“Perimeter of Rectangle %d: %.2f",no,p);
tu
functions Lifetime: exists till the end
}
.jn
of the program.
w
om
float p;
{
p = 2 *(length + breadth);
float peri;
return ( p );
.c
printf("Enter length, breadth : ");
}
m
scanf("%f %f",&length,&breadth);
rectangleArea();
ru
peri = rectanglePerimeter();
External Global Variables
fo
printf(“Perimeter of Rectangle : %f“, peri);
Scope: Visible to all functions across all
printf(“\nEnter base , height: ");
ld
files in the project.
scanf("%f %f",&base,&height);
or
Lifetime: exists till the end of the
triangleArea();
program.
}
void rectangleArea() {
w
tu
float a;
Static Global Variables
.jn
a = length * breadth;
Scope: Visible to all functions with in
printf(“\nArea of Rectangle : %.2f", a);
w
void triangleArea() {
program.
w
float a;
a = 0.5 * base * height ;
printf(“\nArea of Triangle : %.2f", a); Storage Classes – Scope & Lifetime
}
#include<stdio.h> Preprocessor Directives
void showSquares(int n) A function
{ #define - Define a macro substitution
calling itself
if(n == 0) #undef - Undefines a macro
is
om
return; #ifdef - Test for a macro definition
Recursion #ifndef - Tests whether a macro is not
else
defined
.c
showSquares(n-1); #include - Specifies the files to be included
m
printf(“%d “, (n*n)); #if - Test a compile-time condition
}
ru
#else - Specifies alternatives when #if
int main() test fails
fo
{ #elif - Provides alternative test facility
ld
showSquares(5); #endif - Specifies the end of #if
or
} #pragma - Specifies certain instructions
#error - Stops compilation when an error
Output : 1 4 9 16 25
w occurs
tu
# - Stringizing operator
.jn
function function
w
om
of B.TECH, B.PHARMACY, MBA,
.c
MCA of JNTU-HYD,JNTU-
m
ru
KAKINADA & JNTU-ANANTAPUR
fo
vi sitt www.a
visi j lljntuworld.in
ld
or
w
tu
.jn
w
w
w
/* Ranking of 60 students in a class */
int main() {
Array & its Advantage
/*declaring 60 varialbes */
int score0, score1,score2,……,score59; score0 scores[0]
/* Reading scores for sixty times */ score1 scores[1]
printf(“Enter the score : “);
om
score2 scores[2]
scanf(“%d”, &score0);
…. …. …. …. score3 scores[3]
.c
printf(“Enter the score : “); . .
scanf(“%d”, &score59); . .
m
/* comparing & swapping for 1770 times
score59 scores[59]
ru
* to arrange in descending order */
swap( score0, score1);
fo
swap( score1, score2); Sixty variables are replaced by one Array
ld
swap( score2, score3); #include<stdio.h>
…. …. …. …. int main() { Sixty input
or
swap( score0,score1); int scores[60] , i , j, temp; statements are
swap( score1,score2); for(i = 0; i < 60 ;i++) {
swap( score0,score1);
w printf("Enter the score : ");
called by one loop
statement
tu
/*printing 60 scores after sorting */ scanf("%d", &scores[i]);
printf(“%4d”, score0);
.jn
}
printf(“%4d”, score1); for(i=0;i<(60-1);i++) 1770 comparing
… … … … statements are
w
...
om
4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 ( memory
.c
addresses)
start here scores Array
m
ru
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.
fo
#include<stdio.h> printf("\nMean : %.2f",mean); Accessing
ld
Declaration of Array an element
#include<math.h> printf("\nDeviations : ");
or
#define SIZE 10 Initialization of Array for(i=0;i<SIZE ; i++) {
int main() { w deviation = scores[i] - mean;
tu
int scores[SIZE],sum=0,i; printf("%.2f\t", deviation);
float deviation, mean, total=0; total=total + deviation*deviation;
.jn
om
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.
.c
Integer takes 2 bytes memory as a single unit to store its value. i.e.,the value of a scalar variable
m
cannot be subdivided into a more simpler data items.
ru
The address of first byte is the address of a variable .
Vector Variables (arrays):
fo
In contrast, an array is multivariable (an aggregate data type), which is also referred to a data
ld
structure. It represents a collection of related data items of same type.
or
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.
w
All its elements are stored in consecutive memory locations, referred under a common array name.
tu
Ex : int marks[10] ; /* declaration of array */
.jn
‘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)
w
An array is a derived data type. It has additional operations for retrieve and update the individual
w
values.
The lowest address corresponds to the first element and the highest address to the last element.
w
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.
Declaration of One Dimensional Arrays Elements of
Syntax : Array [3] by [4]
arrayType arrayName [ numberOfElements ];
Example :
om
int scores [60];
[0][0] [0][1] [0][2] [0][3]
float salaries [20];
Initialization of Array while Declaration : [1][0] [1][1] [1][2] [1][3]
.c
int numbers [ ] = { 9, 4, 2, 7, 3 };
[2][0] [2][1] [2][2] [2][3]
m
char name[ ] ={‘R’,’a’,‘v’,‘i’,‘ ‘,‘T’,‘e’,‘j’,’a’,’\0’ };
ru
char greeting[ ] = “Good Morning”;
Declaration of Multi Dimensional Arrays /*passing an array to function */
fo
Syntax : #define SIZE 10
ld
arrayType arrayName [ Rows ][ Columns ]; int main() {
or
arrayType arrayName [ Planes][ Rows ][ Columns ]; float list[SIZE] ,avg;
Example : ……………
/* Each student for seven subjects */w avg = average(SIZE , list );
tu
int marks[60][7];
……………
.jn
int matrix [ ][ ] = { { 4, 2, 7, 3 } ,
{ 6, 1, 9, 5 } , for( i = 0; i < n ; i++)
w
om
name
.c
‘name’ is an array of characters has size of eleven characters including a null
m
character ‘\0’(ascii code is zero).
ru
char name[25] ;
scanf(“%s”, name); /*reading a string until a white space is encountered ( & operator is not required )*/
fo
printf(“%s”, name); /*printing a string in input window */
ld
gets(name) ; /* reading a string including white spaces until ‘\n’ is encountered. */
puts(name); /* printing a string and moves cursor to new line */
or
w
String Manipulation Functions in <string.h>
tu
strlen(s1) - returns the length of string excluding the last ‘null’ character.
strcpy(s1,s2) - copies characters in s2 into s1.
.jn
om
Memory Sections of C-Runtime
.c
RAM is temporary storage place to run programs. C-Language runtime also utilizes an
m
allotted memory block in RAM to run its programs.
ru
Text Section : Memory-area that contains the machine instructions(code).It is read
only and is shared by multiple instances of a running program.
fo
Data Section : Memory image of a running program contains storage for initialized
ld
global variables, which is separate for each running instance of a program.
or
BSS (Below Stack Segment) : Memory area contains storage for uninitialized global
w
variables. It is also separate for each running instance of a program.
tu
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
.jn
Heap : This memory region is reserved for dynamically allocating memory for
w
om
void swap(int x, int y) void swap(int *x, int *y)
{ {
.c
int temp; int temp;
m
temp = x; x = y; y = temp; temp = *x; *x = *y; *y = temp;
ru
printf(“\nIn swap() : %d %d “,x,y); printf(“\nIn swap() : %d %d “,*x,*y);
} }
fo
int main() int main()
ld
{ {
int a = 25,b = 37; int a = 25,b = 37;
or
printf(“Before swap() : %d %d”,a,b); printf(“Before swap() : %d %d”,a,b);
swap (a,b); w swap (&a , &b);
tu
printf(“\nAfter swap() : %d %d“,a,b); printf(“\nAfter swap() : %d %d“,a,b);
} }
.jn
w
w
Output : Output :
w
om
‘Y’
stores value ‘Y’ in it
option
.c
Memory Address of variable ‘option’ 4042
m
ru
Creates a pointer variable
fo
with a name ‘ptr’
char *ptr = NULL; Which can hold a
ld
Memory address ptr
or
ptr = &option;
w
Memory address of 4042 ‘Y’
tu
Variable ‘option’
Is copied to the option
.jn
ptr
Pointer ‘ptr’
4042
w
w
om
n1 = 6 ; p NULL q NULL
Prints 6 6
p = & n1;
printf (“%d %d”, n1,*p );
.c
Prints address of n1
m
printf (“%ld %ld”,&n1, p ); n1 6 n2 3
ru
p q
q = & n2; Prints 6 3
fo
*q = 3 ;
ld
printf (“ %d %d “, *p , *q ) ;
n1 6 n2 3
or
p = q; pointer ‘q’ assigned with pointer ‘q’
printf (“ %d %d “, *p , *q ) ; w p q
tu
Prints 3 3
.jn
*p = 7 ; n1 6 n2 7
w
printf (“ %d %d “, *p , *q ) ;
w
} p q
Prints 7 7
w
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.
Pointer and Arrays
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.
om
#include<stdio.h>
.c
int main()
m
Pointer is an address variable, having no
{
ru
initialized value by default. The address
int a[3] = { 12, 5 ,7}, b[3];
fo
stored in the pointer can be changed
int *p ,*q; time to time in the program.
ld
or
Prints 12 12
p = a;
printf("%d %d\n", *p, *a); w
tu
Prints 12 12
.jn
om
int arr [5] = { 12, 31, 56, 19, 42 };
int *p;
.c
p = arr + 1; Prints 31
Prints 12 31 56
m
printf("%d \n", *p);
ru
printf("%d %d %d\n", *(p-1), *(p), *(p + 1));
--p;
fo
printf("%d", *p); Prints 12
ld
or
w
arr[0] or *( arr + 0 ) 12 p - 1
tu
arr[1] or *( arr + 1 ) 31 p
.jn
arr[2] or *( arr + 2 ) 56 p +1
w
arr[3] or *( arr + 3 ) 19 p +2
w
arr[4] or *( arr + 4 ) 42 p +3
w
om
char *day[ ] = { “Sunday”, “Monday”, ”Tuesday”, “Wednesday”, “Thursday”,
“Friday”, “Saturday” };
.c
Pointer to Pointer ( Double indirection )
m
Example :
ru
int a = 25; a pa ppa
fo
int *pa = &a;
int **ppa ; 25 4024 4056
ld
*ppa = &pa;
or
printf(“%d”, *pa); prints 25 4056 4078
4024
printf(“%d”, **ppa); prints 25 w
tu
Two Dimensional Array -- Pointers
.jn
Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j )
void Pointer Function Pointers
‘void’ type pointer is a generic Function pointers are pointers, which
pointer, which can be assigned to any point to the address of a function.
om
data type without cast during Declaration :
compilation or runtime. ‘void’ pointer <return type> (* function_pointer)
.c
cannot be dereferenced unless it is (type1 arg1, type2 arg2, ……. );
cast.
m
int add ( int a, int b ) { return (a + b) ; }
ru
int main( ) { int sub ( int a, int b ) { return (a – b) ; }
fo
void* p;
int x = 7; int (*fp ) (int, int ) ; /* function pointer */
ld
float y = 23.5;
or
p = &x; int main( ) {
printf(“x contains : %d\n”, *( ( int *)p) );
w fp = add;
p = &y; printf(“Sum = %d\n”, fp( 4, 5 ) ) ;
tu
printf(“y contains : %f\n”, *( ( float *)p) ); fp = sub;
.jn
Output :
w
x contains 7 Output :
y contains 23.500000 Sum = 9
Difference = 4
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 ;
om
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.
.c
m
int main() Allocates memory in bytes and returns the address of first
byte to the pointer variable
ru
{
int *p, *q ;
fo
p = (int *) malloc ( sizeof( int ) ); Releases previously allocated memory space.
ld
if( p == NULL )
{ calloc ( ) is used for allocating memory space
or
printf(“Out of memory\n”); during the program execution for derived data types
exit(-1); w such as arrays, structures etc.,
Example :
tu
} struct book {
printf(“Address in p : %d“, p );
.jn
om
iscntrl ( ) isprint ( ) int main( int argc , char* argv [ ])
{
.c
space graphical int i ;
printf(“Number of arguments : %d“, argc );
m
isspace ( ) isgraph ()
printf(“\nName of Program : %s“, argv [0] );
ru
alpha-numeric punctuation
for ( i = 1; i < argc ; i++ )
fo
isalnum ( ) ispunct ( ) printf(“\nUser value %d : %s “,
ld
i , argv [ i ] );
alphabetic digit
or
}
isalpha( ) isdigit ()
w output
tu
upper lower
Compile the program :
.jn
isupper ( ) islower ()
c:\>tcc cmdline.c
w
om
long atol(s) Converts string s to a long integer.
float atof(s) Converts string s to a double-precision quantity.
.c
void* calloc(u1,u2) Allocate memory to an array u1, each of length u2 bytes.
m
void exit(u) Closes all files and buffers, and terminate the program.
ru
void free (p) Free block of memory.
fo
void* malloc (u) Allocate u bytes of memory.
ld
int rand(void) Return a random positive integer.
or
void* realloc(p,u) Allocate u bytes of new memory to the pointer variable p.
void srand(u) Initialize the random number generator.
w
tu
void systerm(s) Pass command string to the operating system.
.jn
<time.h>
clock_t clock() Returns clock ticks since program starts.
w
om
.c
m
Function Pointer Structure
ru
Array Type Union Type
Type Type Type
fo
ld
Array – Collection of one or more related variables of similar
or
data type grouped under a single name
Structure – Collection of one or more related variables of different
w
data types, grouped under a single name
tu
.jn
In a Library, each book is an object, and its characteristics like title, author, no of
w
different types.
w
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.
Book-1 Book-2 Book-3
BookID: 1211 BookID: 1212 BookID: 1213
Title : C Primer Plus Title : The ANSI C Programming Title : C By Example
Author : Stephen Prata Author : Dennis Ritchie Author : Greg Perry
Pages : 984 Pages : 214 Pages : 498
om
Price : Rs. 585.00 Price : Rs. 125.00 Price : Rs. 305.00
book
.c
book_id integer 2 bytes
bookid
m
title Array of 50 characters 50 bytes
title
ru
author Array of 40 characters 40 bytes
author
fo
pages integer 2 bytes
pages
ld
price price float 4 bytes
or
w Memory occupied by a Structure variable
tu
STRUCTURE- BOOK struct < structure_tag_name >
.jn
struct book { {
Structure tag
w
char title[50] ;
…. …. …. ….
w
char author[40] ;
data type < member N >
int pages ; };
float price ;
};
Declaring a Structure Type Declaring a Structure Variable
om
char name[30]; {
float percentage; int roll_no;
.c
}; char name[30];
m
float percentage;
}s1,s2,s3;
ru
fo
Initialization of structure Reading values to members at
ld
runtime:
Initialization of structure variable while
or
declaration : struct student s3;
w
struct student s2 = { 1001, “ K.Avinash ”, printf(“\nEnter the roll no”);
tu
87.25 } ; scanf(“%d”,&s3.roll_no);
Initialization of structure members individually : printf(“\nEnter the name”);
.jn
scanf(“%f”,&s3.percentage);
w
membership operator
Implementing a Structure
struct employee {
int empid;
char name[35];
om
int age; Declaration of Structure Type
float salary;
Declaration of Structure variables
.c
};
m
int main() {
struct employee emp1,emp2 ; Declaration and initialization of Structure variable
ru
fo
struct employee emp3 = { 1213 , ” S.Murali ” , 31 , 32000.00 } ;
emp1.empid=1211;
ld
strcpy(emp1.name, “K.Ravi”);
or
emp1.age = 27;
Initialization of Structure members individually
emp1.salary=30000.00; w
printf(“Enter the details of employee 2”); Reading values to members of Structure
tu
scanf(“%d %s %d %f “ , &emp2.empid, emp2.name, &emp2.age, &emp2.salary);
.jn
else
w
om
int total ; int year ;
}; };
struct person {
.c
char name[40];
m
int main( ) { int age ;
struct student s[3]; struct date b_day ;
ru
int i,j; };
fo
for(i=0;i<3;i++) { int main( ) { Inner Structure
printf(“\n\nEnter student %d marks:”,i+1); struct person p1;
ld
for(j=0;j<3;j++) { strcpy ( p1.name , “S. Ramesh “ ) ;
scanf(“%d”,&s[i].sub[j]); p1. age = 32 ;
or
} p1.b_day.day = 25 ; Accessing Inner
}
for(i=0;i<3;i++) {
w p1.b_day. month = 8 ; Structure members
p1.b_day. year = 1978 ;
tu
s[i].total =0; }
.jn
for(j=0;j<3;j++) {
s[i].total +=s[i].sub[j]; OUTPUT:
w
}
} Total marks of student 1 is: 180
Total marks of student 2 is: 240
Total marks of student 3 is: 270
structures and functions Self referential structures
struct fraction { struct student_node {
int numerator ; int roll_no ;
int denominator ; char name [25] ;
om
}; struct student_node *next ;
};
void show ( struct fraction f ) int main( )
.c
{ {
printf ( “ %d / %d “, f.numerator,
m
struct student_node s1 ;
f.denominator ) ; struct student_node s2 = { 1111, “B.Mahesh”, NULL } ;
ru
} s1. roll_no = 1234 ;
fo
strcpy ( s1.name , “P.Kiran “ ) ;
int main ( ) {
ld
struct fraction f1 = { 7, 12 } ; s1. next = & s2 ; s2 node is linked to s1 node
show ( f1 ) ;
or
} printf ( “ %s “, s1. name ) ; Prints P.Kiran
OUTPUT:
w printf ( “ %s “ , s1.next - > name ) ;
tu
7 / 12
Prints B.Mahesh
}
.jn
w
w
om
char name[20]; i) Using . ( dot ) operator :
}; ( *ptr ) . prodid = 111 ;
.c
strcpy ( ( *ptr ) . Name, “Pen”) ;
int main()
m
{ ii) Using - > ( arrow ) operator :
struct product inventory[3];
ru
ptr - > prodid = 111 ;
struct product *ptr; strcpy( ptr - > name , “Pencil”) ;
fo
printf(“Read Product Details : \n");
for(ptr = inventory;ptr<inventory +3;ptr++) {
ld
scanf("%d %s", &ptr->prodid, ptr->name); Read Product Details :
or
}
111 Pen
printf("\noutput\n"); w
for(ptr=inventory;ptr<inventory+3;ptr++)
112 Pencil
tu
113 Book
{
.jn
} Product ID : 111
w
} Name : Pen
w
Product ID : 112
Name : Pencil
Product ID : 113
Name : Book
A union is a structure all of whose members share the same memory
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
om
share the same memory. The amount of storage allocated to a union is sufficient to hold its
largest member.
.c
struct student {
Memory allotted to structure student
m
int rollno;
float avg ;
ru
char grade ; Address 5000 5001 5002 5003 5004 5005 5006
fo
};
union pupil {
ld
int rollno;
or
float avg ; rollno avg grade
char grade; Total memory occupied : 7 bytes
}; w
tu
int main() {
struct student s1 ; Memory allotted to union pupil
.jn
printf ( “ %d bytes “,
sizeof ( union pupil ) ) ;
w
} rollno
Output : avg
7 bytes 4 bytes grade
Total memory occupied : 4 bytes
www.alljntuworld.in
om
• For More Materials, Text Books, Previous
.c
m
Papers & Mobile updates of B.TECH,
ru
B.PHARMACY, MBA, MCA of JNTU-
fo
HYD,JNTU-KKAKINADA & JNTU-ANANTAPUR
ld
or
visit w
www.alljntuworld.in
tu
.jn
w
w
w
om
INTRODUCTION:
.c
A structure is a collection of elements of different types of data.
m
ru
Ex: consider the student information roll number, gender, age,
fo
height and weight of different types.
ld
main()
or
{ struct student w rno gender
tu
2 1
.jn
{
w
2 4 4
w
char gender;
int age;
13 bytes of memory is allocated in s1
13 bytes of memory is allocated to s2
om
float wt; 2 1
.c
m
}; age ht wt
ru
struct student s1,s2; 2 4 4
fo
ld
}
or
w
When all these data items are grouped under on single variable
tu
name, we can get some meaningful information.
.jn
w
om
syntax:
Example:
.c
struct user defined datatype struct student
m
{
ru
{
int rno;
fo
datatype member1; int age;
ld
or
char gender;
datatype member2;
w float ht;
tu
……………. float wt;
.jn
};
…………
w
w
datatype membern:
w
};
In the given syntax struct is keyword used to create new user defined
om
data type.
.c
An user defined data type name may be any valid ‘c’ identifier ( user
m
defined name).
ru
The data type may be a valid simple data type or compound data type.
fo
ld
The member names may be any valid ‘C’ identifiers .in the given
or
example student is a new user defined data type name.
w
tu
The variable rno, age, gender, ht, wt, are the structure members.
.jn
braces.
w
w
om
Once a new user defined datatype is created by using the
.c
keyboard struct then we can create any no. of structure variables of that
m
type.
ru
syntax:
fo
ld
struct user defined_data type name
or
structure var1, structure var2,……….. Struct varn;
w
tu
Above statement is called declarative statement of structure variables
.jn
definition.
ACCESSING STRUCTURE MEMBERS:
om
Structure member accessing operator
.c
m
S1.gender=‘m’; s1.age=25;
ru
Structure
fo
S1.rno=100 S1.ht=5.5; s1.wt=60.2;
variable
ld
or
Structure member
w
tu
•Two operators are used to access member of structure. The structure
.jn
member operator(.) also called dot operator and the structure pointer
w
om
S1.rno=100; s1.gender=M; s1.age=25; s1.ht=5.5; s1.wt=60.2
.c
s1 s2
m
rno
ru
gender rno gender
100
fo
M
ld
age ht wt
or
age ht wt
25 5.5 60.2 w
tu
.jn
om
initialize a structure follow the variable name in the structure
declaration with an equal sign and brace enclosed comma separated
.c
m
list of initializes.
ru
Ex: struct student s1={100, 25,’M’, 5.5,65.2};
fo
ld
int x = 10;
or
int a[10]={ 10,20,30}; w
tu
READING AND DISPLAYING THE STRUCTURE VARIABLES:
.jn
The ‘C’ will not read or write an entire structure as a single command. It
w
w
om
marks of 2 students.
#include<stdio.h>
.c
m
#include<conio.h>
ru
void main()
fo
ld
{ /* defining a structure */
or
struct student
w
tu
{ int rno;
.jn
char name[30];
w
w
float m1,m2,m3;
w
om
/* 3.reading 1st student details*/
.c
printf(“ enter rno,name,m1,m2,m3 of first student \n”);
m
ru
scanf(“ %d %s %f %f %f ”,
fo
&s1.rno,&s1.name,&s1.m1,&s1.m2,&s1.m3);
ld
/* 4. reading 2nd student details*/
or
w
printf(“ enter rno, name, m1, m2, m3,of second student \n);
tu
.jn
s1.tot= s1.m1+s1.m2+s1.m3;
s1.avg = s1.tot/3;
/* 6.calculate total and avg of first student marks*/
s2.tot= s2.m1+s2.m2+s2.m3;
om
s2.avg = s2.tot/3;
/* displaying first student details*/
.c
printf(“ first student details are \n”);
m
printf( “roll no:%d\n, name:%s \n, m1: %f \n. m2:%f, m3:%f \n”, s1.rno,
ru
s1.name, s1.m1, s1.m2, s1.m3);
fo
printf(“ total :%f \n , average: %f \n”, s1.tot, s1.avg);
ld
or
/* 8. displaying second student details*/
w
printf(“ second student details are:\n);
tu
printf( “roll no:%d\n, name:%s \n, m1: %f \n. m2:%f, m3:%f \n”,
.jn
}
w
Array of Structures:
Perhaps the most common usage of structures is an array of
structures.
om
->To declare an array of structures you must first define a structure
and then declare an array variable of that type.
.c
m
For example to declare a 100 element array of structures of type
ru
“student” write
fo
ld
struct student
or
{ w
tu
int rno;
.jn
int m1,m2,m3;
w
w
int tot,avg;
w
}
struct student s[100];-Structure Variable Declaration
DEMONSTRATING ARRAY OF STRUCTURES:
#include<stdio.h>
om
#include <conio.h>
.c
void main()
m
ru
{
fo
/*1.Defining an array of structures*/
ld
or
struct student
{
w
tu
.jn
int rno;
w
int m1,m2,m3;
w
w
int tot,avg;
};
/*2.Creating an array of Structures*/
struct student s[100];
om
int i,n;
.c
clrscr();
m
ru
printf(“Enter n value\n”);
fo
/*3.Read total no.of students to n*/
ld
or
scanf(“%d”,&n);
w
tu
/*4.Reading student details*/
.jn
for(i=0;i<n;i++)
w
w
{
w
om
for(i=0;i<n;i++)
.c
{
m
ru
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
fo
s[i].avg=s[i].tot/3;
ld
or
}
w
/*6.Display the student details*/
tu
.jn
for(i=0;i<n;i++)
w
{
w
w
om
printf(“M2:%d\n”,s[i].m2);
.c
printf(“M3:%d\n”,s[i].m3);
m
ru
printf(“Total:%d\n”,s[i].tot);
fo
printf(“Average:%d\n”,s[i].avg);
ld
or
}
}
w
tu
.jn
w
w
w
Arrays with in Structures:
A member of a structure may be either a simple or compound type.A
om
simple member is one that is of any of the built-in datatypes such as integer or
character.
.c
m
->The compound datatypes include one dimensional and multidimensional
ru
arrays of other datatypes and structures.
fo
For example consider this Structure:
ld
or
struct x
{
w
tu
.jn
int rno;
w
int tot,avg;
}
Nested Structures:
when a structure variable is a member of another structure, it is
om
called a Nested structure.
.c
->In the below example structure variable ‘z’ is declared as structure
m
Member to another structure.
ru
EX:struct Test
fo
{
ld
or
int a;
int b; w
tu
};
.jn
Struct Exam
{
w
w
int x;
w
int y;
struct Test z;
};
Structures and Function:
A Structure can be passed to a function as a one variable or
om
as an individual member. The scope of a structure declaration should
be external storage class whenever a function in the main().
.c
m
Program Using a Structure datatype:
ru
#include<stdio.h>
fo
ld
/*Defining a Structure*/
or
struct Test w
tu
{
.jn
int a;
w
w
int b;
w
};
/*Prototype*/
struct Test Modify(struct Test s2);
void main()
om
{
.c
struct Test T1={10,20};
m
ru
T1=Modify(T1);
fo
printf(“After calling modify\n”);
ld
or
printf(“T1.a=%d\n”,T1.a);
printf(“T1.b=%d\n”,T1.b);
w
tu
.jn
}
w
{
s2.a=s2.a+10;
S2.b=s2.b+10;
om
return s2;
.c
}
m
a b
ru
a b 10
fo
20
ld
10 20 20+10
10+10
or
1
200 30 w =20 =30
tu
.jn
w
w
w
Union:
Union is another datatype with two or more members,similar to
structure.But in this case all the members share a common
om
memory location.The members of a union can be refered by using
.c
dot operator as in the case of structure.
m
The size of union can contain only one type of member at any
ru
one time.
fo
ld
The size of union corresponds to the length of the longest
or
member.
w
tu
Syntax:
.jn
Union Userdefined_datatype
w
w
{
w
datatype member 1;
datatype member n;};
Union Test
om
{
.c
char a;
m
int b;
ru
fo
float c;
ld
};
or
w
We may have structures with unions and unions with in structures.
tu
Unions may also be intialized like structures.However,Since only
.jn
.c
m
ru
Disk I/O functions
fo
ld
High level Low level
or
w
tu
.jn
Text Binary
w
w
w
om
problems.
.c
1. It becomes cumbersome and time consuming to handle large
m
volumes of data through terminals.
ru
2. The entire data is lost when either the program is terminated
fo
or computer is turned off.
ld
or
o It is therefore necessary to have a more flexible approach
w
where data can be stored on the disks and read whenever
tu
necessary, without destroying the data.
.jn
w
om
include.
.c
naming a file
m
opening a file
ru
reading data from a file
fo
writing data to a file and
ld
closing a file.
or
w
There are two distinct ways to perform file operations.
tu
--The first one is known as the low level I/O and uses
.jn
om
fopen () creates a new file for use.
.c
m
Opens an existing file for use.
ru
fclose() closes a file which has been opened for use.
fo
ld
getc() reads a character from a file .
or
putc() writes a character to a file.
w
tu
fprintf() writes a set of data values to a file.
.jn
om
ftell() gives the current position in file.
.c
rewind() sets the position to beginning of the file.
m
ru
DEFINING AND OPENING A FILE:
fo
If we want to store data in a file in the secondary memory, we must
ld
specify certain thing about a file to operating system they are
or
w
1.File name 2. data structure 3. purpose
tu
For file name general format of declaring and opening a file is
.jn
w
om
w: opens the text file for writing only.
.c
a : open the file for appending data to it.
m
ru
r+: the existing file is opened for both reading and writing.
fo
w+ : this mode allow you to open a file as text file for
ld
reading as well as writing a data to a file.
or
w
a+ : this mode allows you to open a file as a text file for
tu
both reading and writing to a file.
.jn
One other hand we need to add ‘b’ for binary file i.e., rb,
w
om
wb: this mode allows to open a file as a binary file for writing
.c
data to it.
m
ab: this mode allows to open a file as a binary file for
ru
appending data at the end of the file.
fo
ld
rb+: this mode allows to open a file as a binary file for reading
or
as well as writing data to a file.
w
tu
wb+ : this mode allows to open a file as a binary file for writing
.jn
data to a file.
w
ab+: this mode allows to open a file as a binary file for both
w
om
P1= fopen (“data.c”, “r”);
.c
m
P2= fopen (“result.c”, “w”);
ru
fo
CLOSING A FILE:
ld
A file must be closed as soon as all operations on it
or
have been completed. This ensures that all outstanding
w
information associated with the file is flushed out from the
tu
buffer and all links to a file are broken.
.jn
w
fclose (P1);
getc() and putc():
om
The getc() is an input function is used to read a single
character from a file.
.c
Syntax : charvar=getc (file pointer);
m
ch=getc (fp);
ru
The putc() is an output function used to write a single
fo
character into a file.
ld
Syntax : putc (charvar, file pointer);
or
putc (ch, fp); w
tu
.jn
w
w
w
Program to count character, spaces, tabs, and numbers in a file.
#include<stdio.h>
om
Void main()
.c
{ char ch;
m
int nol=0, not=0, nos=0, noc=0;
ru
fo
fp=fopen(“pri.c”, “r”);
ld
or
while(1)
{ ch=getc (fp);
w
tu
.jn
if ( ch== EOF)
w
break;
w
w
noc++;
if ( ch==‘ ‘)
nos++;
om
if (ch== ‘\t’)
.c
not++;
m
ru
If ( ch==‘\n’)
fo
nol++;
ld
or
}
w
tu
fclose (fp);
.jn
om
}
.c
m
ru
OUTPUT:
fo
number of characters =125
ld
or
number of blanks =25
w
tu
number of tabs =13
.jn
om
The putw() function is an output function and is used
to write an integer into a file.
.c
m
Syntax: putw( integer, file pointer)
ru
ex: putw (x,pf);
fo
ld
or
The getw() function is an input function and is used to read
w
an integer from a file.
tu
.jn
ex: x= getw(fp);
w
w
Program for demonstrating putw() and getw() function
#include<stdio.h>
om
#include<stdlib.h>
.c
Void main()
m
ru
{
fo
FILE *f;
ld
or
int word1, word2;
w
fp=fopen ( “ number.c”, “w”);
tu
.jn
if(fp==NULL)
w
{
w
w
om
word1=94;
.c
putw(word1,fp);
m
ru
if ( ferror(fp))
fo
printf(“ error writing to file \n”);
ld
or
else
w
printf( “ sucessful write \n” );
tu
.jn
fclose(fp);
w
om
printf(“ error opening file “);
.c
exit(1);
m
ru
}
fo
/*extract the word */
ld
or
Word =getw (fp);
if (ferror (fp))
w
tu
.jn
else
w
w
om
return 0;
.c
m
}
ru
fo
ld
word1
or
Successfully
Number file 94
w wrote
tu
94
.jn
word2
w
94 Successful read
getw
w
w
pf f()
fprintf() and fscanf() functions:
The fprintf() and fscanf() functions group of mixed data
om
simultaneously.
.c
Syntax: fprintf( fp, “ control string “, list);
m
ex: fprintf( %s %d %f “, name, age, 7.5);
ru
fo
Syntax: fscanf(fp, “control string “, list);
ld
or
ex: fscanf(“ %s %d”, item, &quantity);
w
Demonstrating frpintf () and fscanf() functions:
tu
.jn
#include<stdio.h>
w
#include<conio.h>
w
w
Void main()
{
FILE *fp;
om
int rno;
.c
char name[30];
m
ru
float marks;
fo
fp=fopen(“ student.c”, “w”);
ld
or
printf( “ enter student record \n”);
w
tu
scanf(“ %d %s %f “,& rno, name, &marks);
.jn
fclose( fp);
w
om
fscanf (fp, “%d %s %f”, &rno, name, &marks);
printf(“ %d %s %f”, rno, name, marks);
.c
m
fclose (fp);
ru
fo
} scanf()
ld
or
H.D
w
fprintf()
Enter students
tu
student rno name marks
1.Ravi 30.5
.jn
1 ravi 30.5
1. Ravi 30.5
w
w
1 ravi 30.5
w
fscanf() prinf()
RANDOM ACCESS TO FILES:
Sometimes it is required to access only a particular part
om
of the file and not the complete file.
.c
This can be accomplished by using following function.
m
fseek(): it is a file function. It positions file pointer on the
ru
stream. We can pass three arguments through this
fo
function.
ld
or
The general format of fseek function is as follows:
w
tu
fseek( file pointer, offset, position);
.jn
om
3. Position in an integer number.
.c
Offset specifies the number of positions (bytes) to be moved
m
from the location specified at position.
ru
fo
integer
Constant Location in file
ld
value
or
0 SEEK_SET Beginning of file
w
tu
1 SEEK_CUR Current position of file
.jn
om
Void main()
.c
{
m
ru
FILE *fp;
fo
int n, ch;
ld
or
clrscr();
w
tu
fp=fopen( “ text.txt”, “r”);
.jn
while ((ch=fgetc(fp))!=EOF)
w
om
scanf(“%d”, &n);
.c
fseek ( fp, n, SEEK_SET)
m
printf(“\n information after %d byte \n”,n);
ru
fo
while (( ch=fgetc(fp)) !=EOF)
ld
or
printf(“%c”, ch);
fclose(fp);
w
tu
.jn
}
w
w
w
typedef – to define new datatype bitfieds
om
Syntax: };
typedef <datatype> <newname> Above structure occupies 4 bytes of
.c
/* Re-defining int type as Integer type */ memory. But the member pips accepts a
value between 1 to 13 and the member suit
m
typedef int Integer;
int main( ) { accepts any value of 0, 1, 2 and 3 .
ru
Interger a ,b , sub; So we can create a more packed
fo
a = 20,b = 10; representation of above structure with bitfields.
sub = a - b; struct playcard {
ld
printf(“%d - %d = %d”, a, b, sub); unsigned pips : 4;
or
} unsigned suit : 2;
/* Defining structure with typedef to avoid w };
repeated usage of struct keyword */ A bitfield is a set of adjacent bits within
tu
a single machine word.
.jn
om
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 } ;
.c
Now EAST has value 1, SOUTH has value 2, WEST has value 6, and NORTH has value 7.
m
Enumerated types can be converted implicitly or cast explicitly.
int x = WEST ; /* Valid. x contains 6. */
ru
enum direction y ; y = (enum direction ) 2 ; /* Valid. Y contains SOUTH */
fo
#include<stdio.h> #include<stdio.h>
ld
int main() { enum color {RED = 1,ORANGE,GREEN };
int signal; int main() {
or
printf ("\t\t\t MENU \n\t1.RED \n"); enum color signal;
printf ("\t2.ORANGE\n\t3.GREEN \n“ ); w printf ("\t\t\t MENU \n\t1.RED \n");
printf ("\n\t Enter the signal : “ ); printf ("\t2.ORANGE\n\t3.GREEN\n");
tu
scanf (“%d”, &signal ); printf ("\n\t Enter the signal : ");
.jn
om
through terminals.
The entire data is lost when either program terminates or computer is
.c
turned off.
m
Some times it may be necessary to store data in a manner that can be
ru
later retrieved and processed.
fo
This leads to employ the concept of FILES to store data permanently
in the system.
ld
or
w File Operations
Record is logical group of data fields that
tu
comprise a single row of information, which 1. Creating a new file
.jn
m
and an input/output Device.
ru
Stream is a Sequence of data bytes, which is used to read and write data to a file.
fo
The streams that represent the input data of a program are known as Input Streams, where
ld
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
or
provide input data to the program.
w
Output Streams obtain data from the program and write that on different Output Devices
tu
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
w
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.
Steps involved using files
/*program to write and read data from file*/ 1. Declaring FILE pointer variable :
#include<stdio.h> Syntax :
om
void main() { FILE *file_pointer1;
FILE *fp;
.c
char ch; 2. Open a file using fopen() function :
fp = fopen(“data.txt”, “w”);
m
Syntax :
if(fp == NULL) { fp= fopen(“filename”,“mode of access”);
ru
printf(“Cannot open file.”);
fo
exit(0); 3. fputc() – Used to write a character to
}
ld
the file.
printf(“Type text ( to stop press ‘.’ ) : ”); Syntax :
or
while(ch != ‘.’) { fputc(character, file_pointer);
ch = getche(); w
fputc(ch,fp);
tu
4. fgetc() – Used to read a character to the
} file.
.jn
fclose(fp); Syntax :
printf(“\nContants read : “); fgetc(file_pointer);
w
fp = fopen(“data.txt”,”r”);
w
om
printf("\nEnter the text\n");
printf("\n\t(Press ctrl+Z after
.c
completing text)\n"); putc(character,filepointer);
fp=fopen("str.txt","w");
m
while((ch=getchar())!=EOF) fclose(filepointer);
ru
putc(ch,fp);
fo
fclose(fp);
}
ld
or
/* Reading the contents of existing file */ /* appending data to an existing file */
#include<stdio.h> w int main() {
tu
int main() { FILE *fp; char ch;
FILE *fp; printf("\nEnter the text\n");
.jn
while((ch=getc(fp))!=EOF) fp=fopen("str.txt","a");
printf("%c",ch); while((ch=getchar())!=EOF)
w
fclose(fp); putc(ch,fp);
} fclose(fp);
}
r -- open a file in read mode r+ -- open a file in read and write mode
-- if file exits, the marker is positioned at -- if file exits, the marker is positioned
beginning. at beginning.
-- if file does not exist, error returned. -- if file does not exist, NULL returned.
om
w -- open a file in write mode w+ -- open a file in read and write mode
-- if file exits, all its data is erased. -- if file exits, all its data is erased.
-- if file does not exist, it is created. -- if file does not exist, it is created.
.c
a -- open a file in append mode a+ -- open a file in read and append mode
m
-- if file exits, the marker is positioned -- if file exits, the marker is positioned
ru
at end. at end.
-- if file does not exist, it is created. -- if file does not exist, it is created.
fo
ld
rb , wb , ab, rb+ , wb+ , ab+ are modes to operate a file as binary file.
or
int main( ) { /* Without using w+ */ /* open a file in read and write mode */
FILE *fp; char ch; w int main( ) {
tu
printf("\nEnter the text\n"); FILE *fp; char ch;
fp=fopen("str1.txt","w");
.jn
fp=fopen("str1.txt","r"); rewind(fp);
while((ch=getc(fp))!=EOF) while((ch=getc(fp))!=EOF)
w
printf("%c",ch); printf("%c",ch);
fclose(fp); fclose(fp);
} }
File Input / Output Functions
fopen(fp, mode) Open existing file / Create new file
fclose(fp) Closes a file associated with file pointer.
closeall ( ) Closes all opened files with fopen()
om
fgetc(ch, fp) Reads character from current position and advances the pointer to
next character.
.c
fprintf( ) Writes all types of data values to the file.
m
fscanf() Reads all types of data values from a file.
ru
gets() Reads string from a file.
fo
puts() Writes string to a file.
ld
getw() Reads integer from a file.
or
putw() Writes integer to a file.
w
tu
fread() Reads structured data written by fwrite() function
.jn
/* Copying one binary file to other */ “rb” open a file in read mode
“wb” open a file in write mode
om
#include<stdio.h>
int main( ) “ab” open a file in append mode
{ “rb+” open a pre-existing file in read and
.c
FILE *fs,*ft; write mode
m
char ch;
“wb+” open a file in read and write mode
ru
fs=fopen("pr1.exe","rb");
if(fs==NULL){ “ab+” open a file in read and append mode
fo
printf("\nCannot Open the file"); Text File :
ld
exit(0); i) Data are human readable characters.
}
or
ii) Each line ends with a newline character.
ft=fopen("newpr1.exe","wb"); iii) Ctrl+z or Ctrl+d is end of file character.
if(ft==NULL) { w iv) Data is read in forward direction only.
tu
printf("\nCannot open the file"); v) Data is converted into the internal format
fclose(fs);
.jn
om
FILE *fp = fopen("notes.txt","w"); beginning.
if(fp==NULL){ rewind(file-pointer)
printf("\nCannot open file."); exit(0);
.c
-- moves the file pointer to the
} starting of the file, and reset it.
m
fprintf(fp,"%s",str); fseek(fileptr, offset, position)
ru
fclose(fp); – moves the file pointer to the
fp = fopen("notes.txt","r"); location (position + offset)
fo
printf("\nText from position %d : \n\t“,ftell(fp)); position :
ld
fseek(fp, 3 ,SEEK_SET); SEEK_SET – beginning of file
or
for(i=0; i < 5; i++) putchar(getc(fp)); SEEK_CUR – current position
printf("\nText from position %d : \n\t“,ftell(fp)); SEEK_END – end of the file
fseek(fp, 4 ,SEEK_CUR);
w
tu
for(i=0; i < 6; i++) putchar(getc(fp)); output :
Text from position 3 :
.jn
fseek(fp, - 10 , SEEK_END);
printf("\nText from position %d : \n\t“,ftell(fp)); defgh
w
om
int main( ) { int main( ) {
FILE *fp; FILE *fp;
int rno , i; char s[80];
.c
float avg; fp=fopen(“poem.txt","w");
m
char name[20] , filename[15]; if(fp==NULL) {
ru
printf("\nEnter the filename\n"); puts("Cannot open file");exit(0);
scanf("%s",filename); }
fo
fp=fopen(filename,"w"); printf("\nEnter a few lines of text:\n");
ld
for(i=1;i<=3;i++) { while(strlen(gets(s))>0){
printf("Enter rno,name,average fputs(s,fp);
or
of student no:%d",i); fputs("\n",fp);
w
scanf("%d %s %f",&rno,name,&avg); }
tu
fprintf(fp,"%d %s %f\n",rno,name,avg); fclose(fp);
} fp=fopen(“poem.txt","r");
.jn
fclose(fp); if(fp==NULL){
w
om
char *filename; fputs() fgets() Character Strings
clrscr(); fprintf() fscanf() Formatted ASCII
.c
fp1=fopen("test.txt","w");
for(i=10;i<=50;i+=10) fwrite() fread() Binary files
m
putw(i,fp1); write() read() Low-level binary
ru
fclose(fp1);
do {
fo
printf("\nEnter the filename : \n");
Predefined Streams
ld
scanf("%s",filename);
or
fp2=fopen(filename,"r");
if(fp2==NULL) w
printf("\nCannot open the file"); NAME MEANING
tu
} while(fp2==NULL); stdin Standard input (from keyboard)
.jn
while(!feof(fp2)) {
stdout Standard output (to monitor)
n=getw(fp2);
w
if(n==-1) printf("\nRan out of data"); stderr Standard error output (to monitor)
w
else printf("\n%d",n);
stdaux Standard auxiliary (both input and
w
}
fclose(fp2); output)
getch(); stdprn Standard printer output(to printer)
}
Handling Records (structures) in a File
struct player {
char name[40]; int age; int runs;
} p1,p2;
om
void main() {
int i ; FILE *fp = fopen ( "player.txt", "w");
.c
if(fp == NULL) {
m
printf ("\nCannot open file."); exit(0);
ru
}
for(i=0;i<3;i++) {
fo
printf("Enter name, age, runs of a player : ");
ld
scanf("%s %d %d",p1.name, &p1.age,&p1.runs);
or
fwrite(&p1,sizeof(p1),1,fp);
} w
tu
fclose(fp);
fp = fopen("player.txt","r");
.jn
for(i=0;i<3;i++) {
w
fread(&p2,sizeof(p2),1,fp);
w
om
2)Trying to read beyond the end of file mark.
3)Device overflow.
4)Trying to use a file that has not been opened.
.c
5)Trying to perform an operation on a file when the file is opened for another type of
m
operation.
ru
6)Attempting to write to a write-protected file.
fo
feof(fp)
returns non-zero integer value if /* program on ferror( ) and perror ( ) */
ld
we reach end of the file otherwise zero. #include<stdio.h>
or
ferror(fp)
returns non-zero integer value int main(){
if an error has been detected otherwise w FILE *fp;
char ch;
tu
zero
fp=fopen("str.txt","w");
.jn
perror(string)
prints the string, a colon ch=getc(fp);
and an error message specified by the if(ferror(fp))
w
om
fp1=fopen("TEST.txt","w"); file otherwise 0.
for(i=10;i<=50;i+=10)
.c
putw(i,fp1);
fclose(fp1);
m
file:
ru
printf("\nEnter the filename\n");
fo
scanf("%s",filename);
fp2=fopen(filename,"r");
Output:
ld
Enter the filename
if(fp2==NULL){
TETS.txt
or
printf("\nCannot open the file");
Cannot open the file
printf("\nType File name again"); w Type the File name again
goto file;}
tu
Enter the filename
else{
TEST.txt
.jn
for(i=1;i<=10;i++){
10
number=getw(fp2);
w
20
if(feof(fp2)){
30
w
break;}
50
else
Ran out of data.
printf("\n%d",number); } }
fclose(fp2);}
Structure of FILE pointer File Management Functions
om
typedef struct {
short level; remove(“filename")
.c
unsigned flags; -- It removes the file specified (macro)
char fd;
m
unsigned char hold; unlink(“filename");
ru
short bsize; -- It also removes the file name
unsigned char *buffer, *curp;
fo
unsigned istemp; fcloseall();
ld
short token; -- Closes all the opened streams in the
or
} FILE; program except standard streams.
feof(file_pointer)
-- to check if end of file has been tmpfile ()
w
om
HYD,JNTU-KAKINADA & JNTU-ANANTAPUR
.c
m
visit
ru
www.alljntuworld.in
fo
ld
or
w
tu
.jn
w
w
w
Searching techniques
Searching :
It is a process to find whether a particular value with specified properties is present or not
among a collection of items.
om
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
.c
appropriate message and in this case searching is said to be unsuccessful.
m
1) Linear or Sequential Searching 2) Binary Searching
ru
int main( ) { Linear_Search (A[ ], N, val , pos )
fo
int arr [ 50 ] , num , i , n , pos = -1; Step 1 : Set pos = -1 and k = 0
printf ("How many elements to sort : "); Step 2 : Repeat while k < N
ld
scanf ("%d", &n); Begin
or
printf ("\n Enter the elements : \n\n"); Step 3 : if A[ k ] = val
for( i = 0; i < n; i++ ) { Set pos = k
printf (“arr [%d ] : “ , i );
w print pos
tu
scanf( "%d", &arr[ i ] ); Goto step 5
} End while
.jn
printf(“\nEnter the number to be searched : “); Step 4 : print “Value is not present”
scanf(“%d”,&num); Step 5 : Exit
w
for(i=0;i<n;i++)
w
pos = i ; break; -- for each item one by one in the list from
} the first, until the match is found.
if ( pos == -1 ) printf(“ %d does not exist ”,num); Efficiency of Linear search :
else -- Executes in O ( n ) times where n is the
printf(“ %d is found at location : %d”, num , pos); number of elements in the list.
Binary Searching
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.
om
• 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
.c
the upper half of the array.
m
• We repeat the above procedure on the lower half or upper half of the array.
ru
Binary_Search (A [ ], U_bound, VAL)
fo
Step 1 : set BEG = 0 , END = U_bound , POS = -1
Step 2 : Repeat while (BEG <= END ) void binary_serch ( int a [], int n, int val ) {
ld
Step 3 : set MID = ( BEG + END ) / 2 int end = n - 1, beg = 0, pos = -1;
or
Step 4 : if A [ MID ] == VAL then while( beg <= end ) {
POS = MID mid = ( beg + end ) / 2;
w
print VAL “ is available at “, POS if ( val == a [ mid ] ) {
pos = mid;
tu
GoTo Step 6
End if printf(“%d is available at %d”,val, pos );
.jn
om
EMCET Ranking is an example for sorting with user-defined order.
EMCET Ranking is done with the following priorities.
.c
i) First priority is marks obtained in EMCET.
m
ii) If marks are same, the ranking will be done with comparing marks obtained in
ru
the Mathematics subject.
iii) If marks in Mathematics subject are also same, then the date of births will be
fo
compared.
ld
or
Internal Sorting : w Types of Internal Sortings
tu
If all the data that is to be sorted can be accommodated
at a time in memory is called internal sorting. Bubble Sort
.jn
Insertion Sort
External Sorting :
w
or file is loaded into memory part by part. Each part that Quick Sort
is loaded is sorted separately, and stored in an
Merge Sort
intermediate file and all parts are merged into one single
sorted list.
Bubble Sort
Bubbles up the highest
om
.c
Unsorted Sorted
m
Bubble_Sort ( A [ ] , N )
ru
Step 1 : Repeat For P = 1 to N – 1
10 54 54 54 54 54 Begin
fo
Step 2 : Repeat For J = 1 to N – P
47 10 47 47 47 47
ld
Begin
Step 3 : If ( A [ J ] < A [ J – 1 ] )
or
12 47 10 23 23 23 Swap ( A [ J ] , A [ J – 1 ] )
w End For
54 12 23 10 19 19 End For
tu
Step 4 : Exit
.jn
19 23 12 19 10 12
Complexity of Bubble_Sort
w
List Pass 1 Pass 2 Pass 3 Pass 4 Pass 5 Total comparisons in Bubble sort is
n ( n – 1) / 2 ≈ n 2 – n
Complexity = O ( n 2 )
void print_array (int a[ ], int n) {
int i;
for (i=0;I < n ; i++) printf("%5d",a[ i ]);
Bubble Sort
}
void bubble_sort ( int arr [ ], int n) {
int pass, current, temp;
om
For pass = 1 to N - 1
for ( pass=1;(pass < n) ;pass++) {
for ( current=1;current <= n – pass ; current++) {
.c
if ( arr[ current - 1 ] > arr[ current ] ) {
temp = arr[ current - 1 ]; For J = 1 to N - pass
m
arr[ current - 1 ] = arr[ current ];
ru
arr[ current ] = temp;
} T
fo
A[J–1]>A[J]
}
ld
}
} F
or
int main() { Temp = A [ J – 1 ]
int count,num[50],i ; A[J–1]=A[J]
w
printf ("How many elements to be sorted : "); A [ J ] = Temp
tu
scanf ("%d", &count);
printf("\n Enter the elements : \n\n");
.jn
}
w
om
Step 2 : Set Temp = A [ K ]
Step 3 : Set J = K – 1
23 78 45 8 32 36 Step 4 : Repeat while Temp < A [ J ] AND J >= 0
.c
45 Begin
m
Set A [ J + 1 ] = A [ J ]
Set J = J - 1
ru
23 45 78 8 32 36 End While
fo
Step 5 : Set A [ J + 1 ] = Temp
8
End For
ld
Step 4 : Exit
8 23 45 78 32 36
or
32 w insertion_sort ( int A[ ] , int n ) {
int k , j , temp ;
tu
8 23 32 45 78 36 for ( k = 1 ; k < n ; k++ ) {
.jn
temp = A [ k ] ;
36 j = k - 1;
w
j--;
w
om
Step 2 : Set POS = K
Step 3 : Repeat for J = K + 1 to N – 1
23 8 78 45 23 32 56 Begin
.c
If A[ J ] < A [ POS ]
m
Set POS = J
End For
ru
32 8 23 45 78 32 56 Step 5 : Swap A [ K ] with A [ POS ]
fo
End For
Step 6 : Exit
ld
45 8 23 32 78 45 56
or
selection_sort ( int A[ ] , int n ) {
int k , j , pos , temp ;
w for ( k = 0 ; k < n - 1 ; k++ ) {
tu
56 8 23 32 45 78 56 pos = k ;
for ( j = k + 1 ; j <= n ; j ++ ) {
.jn
if ( A [ j ] < A [ pos ] )
8 23 32 45 56 78 pos = j ;
w
}
w
temp = A [ k ] ;
Complexity of Selection Sort
w
A [ k ] = A [ pos ] ;
Best Case : O ( n2 )
A [ pos ] = temp ;
Average Case : O ( n2 )
}
Worst Case : O ( n2 )
}
Selection sort
Insertion sort
om
k = 0; k < n - 1 ; k++
k = 1; k < n ; k++
.c
m
pos = k
temp = a [ k ]
ru
j=k-1
j = k + 1 ; j < n ; j++
fo
ld
temp < a [ j ] && j >= 0
or
a[ j ] < a[ pos ]
a[j+1]=a[j]
w pos = j
tu
j=j-1
.jn
a [ j + 1 ] = temp temp = a[ k ]
w
a [ k ] = a [ pos ]
w
a [ pos ] = temp
w
return
return
Bubble sort – Insertion sort – Selection sort
Bubble Sort :
om
-- 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.
.c
Insertion Sort :
m
-- sorted by considering one item at a time.
-- efficient to use on small sets of data.
ru
-- twice as fast as the bubble sort.
-- 40% faster than the selection sort.
fo
-- no swapping is required.
ld
-- It is said to be online sorting because it continues the sorting a list as and when it receives
new elements.
or
-- it does not change the relative order of elements with equal keys.
w
-- reduces unnecessary travel through the array.
-- requires low and constant amount of extra memory space.
tu
-- less efficient for larger lists.
.jn
Selection sort :
-- No of swappings will be minimized. i.e., one swap on one pass.
w
-- 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.
w
-- It is preferred over bubble sort for jumbled array as it requires less items to be exchanged.
w
Original-list of 11 elements :
om
Set list [ 0 ] as pivot : -- set the element A [ start_index ] as pivot.
-- rearrange the array so that :
.c
pivot
-- all elements which are less than the pivot
m
come left ( before ) to the pivot.
8 3 2 11 5 14 0 2 9 4 20 -- all elements which are greater than the pivot
ru
come right ( after ) to the pivot.
fo
Rearrange ( partition ) the elements -- recursively apply quick-sort on the sub-list of
into two sub lists : lesser elements.
ld
pivot -- recursively apply quick-sort on the sub-list of
or
greater elements.
8 -- the base case of the recursion is lists of size
4 3 2 2 5 0 11 9 14 20
w zero or one, which are always sorted.
tu
.jn
Sub-list of Sub-list of
lesser elements greater elements
w
Pivot
9 12 8 16 1 25 10 3
om
9
.c
12 8 16 1 25 10 3
m
ru
fo
3 12 8 16 1 25 10
ld
or
3 w 8 16 1 25 10 12
tu
.jn
3 1 8 16 25 10 12
w
w
w
3 1 8 16 25 10 12
Quick Sort – Program
int partition ( int a [ ], int beg, int end ) { void quick_sort(int a[ ] , int beg , int end ) {
int left , right , loc , flag = 0, pivot ; int loc;
loc = left = beg; if ( beg < end ) {
om
right = end; loc = partition( a , beg , end );
pivot = a [ loc ] ; quick_sort ( a , beg , loc – 1 );
.c
while ( flag == 0 ) quick_sort ( a , loc + 1 , end );
{ }
m
while( (pivot <= a [ right ] )&&( loc != right ) ) }
ru
right - - ; void print_array (int a [ ],int n) {
if( loc == right ) flag = 1; int i;
fo
else { for ( i = 0 ; I < n ; i++ ) printf( "%5d“ ,a [ i ] ) ;
a [ loc ] = a [ right ] ; }
ld
left = loc + 1 ; int main () {
or
loc = right; int count , num[ 50 ] , i ;
} printf ("How many elements to sort : ");
w
while ( (pivot >= a [ left ] ) && ( loc != left ) ) scanf ("%d", &count );
tu
left++; printf ("\n Enter the elements : \n\n");
if( loc == left ) flag = 1; for( i = 0; i < count; i++ ) {
.jn
right = loc - 1; }
w
om
a [ loc ] = a [ left ] flag = 1
Flag == 0 right = loc - 1 ;
loc = left;
.c
pivot <= a [ right ]
m
&& loc != right
ru
a[ loc ] = pivot
right = right - 1
fo
return loc
ld
F T
or
loc == right quick_sort ( int a [ ], int beg, int end )
a [ loc ] = a [ right ] w
flag = 1 F T
tu
left = loc + 1 ; loc == left
loc = right;
.jn
&&loc != left
w
return
A B
Merge Sort ( Divide and conquer )
Divide the array
-- Merge sort technique sorts a given set
39 9 81 45 90 27 72 18 of values by combining two sorted
arrays into one larger sorted arrays.
om
-- A small list will take fewer steps to sort
39 9 81 45 90 27 72 18 than a large list.
.c
-- Fewer steps are required to construct
m
a sorted list from two sorted lists than
39 9 81 45 90 27 72 18
two unsorted lists.
ru
-- You only have to traverse each list
fo
39 9 81 45 90 27 72 18 once if they're already sorted .
ld
Merge_sort Algorithm
or
Merge the elements to sorted array
1. If the list is of length 0 or 1, then it is already
39 9 81 45 90 27 w
72 18
sorted.
Otherwise:
tu
2. Divide the unsorted list into two sublists of
.jn
merge sort.
4. Merge the two sublists back into one
w
9 39 45 81 18 27 72 90 sorted list.
w
Time complexity
9 18 27 39 45 72 81 90 Worst case - O(n log n)
Best case - O(nlogn) typical, O(n) natural variant
Average case - O( n log n )
Merge Sort - Program
om
i=low; j=mid+1; k=low;
while( ( i<=mid )&&( j <= high ) ) { void print_array (int a [ ],int n) {
int i;
if( a[ i ]<a[ j ] ){
.c
for ( i = 0 ; I < n ; i++ ) printf( "%5d“ ,a [ i ] ) ;
c[ k ]=a[ i ]; k++; i++; }
m
}else { int main () {
ru
c[ k ]=a[ j ]; k++; j++; int count , num[ 50 ] , i ;
} printf ("How many elements to sort : ");
fo
} scanf ("%d", &count );
ld
while( i<=mid ) { c[k]=a[ i ]; k++; i++; } printf ("\n Enter the elements : \n\n");
for( i = 0; i < count; i++ ) {
or
while(j<=high) { c[k]=a[ j ]; k++; j++; } printf ("num [%d ] : “ , i );
for(i=low;i<k;i++) a[ i ]=c[ i ]; scanf( "%d", &num[ i ] );
} w }
tu
printf (“ \n Array Before Sorting : \n\n\n“ );
void merge_sort(int a[ ], int low, int high){
print_array ( num , count ) ;
.jn
int mid;
merge_sort ( num ,0 , count-1) ;
if( low < high) {
printf ( "\n\n\n Array After Sorting : \n\n\n“ );
w
om
F T F T
a[ i ] < a[ j ] low < high
.c
m
c[ k ] =a [ i ] ; c[ k ] =a [ j ] ; mid = ( low + high ) / 2
ru
k++ ; i++ k++ ; j++
fo
merge_sort (a, low, mid)
ld
i <= mid
or
merge_sort (a, mid, high )
c[ k ] =a [ i ] ; k++ ; i++
w
tu
Merge (a, low,high , mid)
j <= high
.jn
c[ k ] =a [ j ] ; k++ ; j++
w
w
i = low ; i < k ; i ++
Return
w
a[ i ] = c [ i ]
return
www.alljntuworld.in
om
• For More Materials, Text Books, Previous
.c
m
Papers & Mobile updates of B.TECH,
ru
B.PHARMACY, MBA, MCA of JNTU-
fo
HYD,JNTU-KKAKINADA & JNTU-ANANTAPUR
ld
or
visit w
www.alljntuworld.in
tu
.jn
w
w
w
Data Structures
-- 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.
om
-- 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.
.c
-- 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 ) .
m
-- Data structure is described as an instance of Abstract Data Type ( ADT ).
ru
-- 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
fo
carried out between the logically related data elements.
ld
Data Structure Some Data structures
or
Arrays
Strings
Linear w Non-Linear Lists
tu
Stacks
Queues
.jn
Hash Tables
Traversal : access and examine each element in collection. Sets
Search : find whether an element is present or not. Lattice
Sorting : rearranging elements in a particular order. Neural-Nets
Merging : combining two collections into one collection.
Arrays – Linked Lists
What is a Linked List
Limitations of Arrays The elements of a linked list are not constrained to
1) Fixed in size : be stored in adjacent locations. The individual
Once an array is created, the size of array
om
elements are stored “somewhere” in memory, rather
cannot be increased or decreased. like a family dispersed, but still bound together. The
2) Wastage of space : order of the elements is maintained by explicit links
.c
If no. of elements are less, leads to wastage of between them.
space.
m
3) Sequential Storage :
ru
Array elements are stored in contiguous
memory locations. At the times it might so
fo
happen that enough contiguous locations might
not be available. Even though the total space
ld
The Linked List is a collection of elements called
requirement of an array can be met through a nodes, each node of which stores two items of
or
combination of non-contiguous blocks of information, i.e., data part and link field.
memory, we would still not be allowed to create
the array. w -- The data part of each node consists the data
record of an entity.
tu
4) Possibility of overflow : -- The link field is a pointer and contains the
If program ever needs to process more than the
.jn
element after the specified location has to be -- First node contains a pointer to second node,
shifted one position to the right. In case of second node contains a pointer to the third node and
deletion of an element, each element after the so on.
specified location has to be shifted one position -- The last node in the list has its next field set to
to the left. NULL to mark the end of the list.
struct node {
int rollno; struct node *next;
Creating a Singly Linked List
}; /* deleting n2 node */
int main() { n1->next = n4;
struct node *head,*n1,*n2,*n3,*n4; free(n2);
/* creating a new node */ }
om
n1=(struct node *) malloc(sizeof(struct node));
n1->rollno=101; 150 101 NULL
.c
n1->next = NULL; head 150 n1-node
/* referencing the first node to head pointer */
m
head = n1; 150 101 720 102 NULL
ru
/* creating a new node */ 720
150
n2=(struct node *)malloc(sizeof(struct node)); n1-node n2-node
fo
n2->rollno=102;
n2->next = NULL; 150 101 720 102 910 104 NULL
ld
/* linking the second node after first node */ 150 720 910
n3-node
or
n1-node n2-node
n1->next = n2;
/* creating a new node * /
w
n3=(struct node *)malloc(sizeof(struct node)); 150 101 400 102 720 104 NULL
tu
n3->rollno=104; head 150 400 910
n3->next=NULL; n1-node n2-node 103 910 n3-node
.jn
n4=(struct node *)malloc (sizeof (struct node)); 150 101 720 103 910 104 NULL
n4->rollno=103;
w
struct node { }
int data; }
struct node *next; void insert_after(struct node **h) {
om
}; struct node *new,*temp; int k;
struct node *createnode() { if(*h == NULL) return;
struct node *new; printf("\nEnter data of node after which node : ");
.c
new = (struct node *)malloc(sizeof(struct node)); scanf("%d",&k);
m
printf("\nEnter the data : "); temp = *h;
scanf("%d",&new->data); while(temp!=NULL && temp->data!=k)
ru
new->next = NULL; temp = temp->next;
return new; if(temp!=NULL) {
fo
} new=createnode();
ld
void append(struct node **h) { new->next = temp->next;
struct node *new,*temp; temp->next = new;
or
new = createnode(); }
if(*h == NULL) {
*h = new;
w }
void insert_before(struct node **h) {
tu
return; struct node *new,*temp,*prev ;
.jn
} int k;
temp = *h; if(*h==NULL) return;
w
while(temp->next!=NULL) temp = temp->next; printf("\nEnter data of node before which node : ");
temp->next = new; scanf("%d",&k);
w
} if((*h)->data == k) {
w
om
} }
if(temp!=NULL) { }
new = createnode(); void search(struct node *h) {
.c
new->next = temp; struct node *temp;
m
prev->next = new; int k;
} if(h==NULL)return;
ru
} printf("\nEnter the data to be searched : ");
void delnode(struct node **h) { scanf("%d",&k);
fo
struct node *temp,*prev; temp=h;
ld
int k; while(temp!=NULL && temp->data!=k)
if(*h==NULL) return; temp=temp->next;
or
printf("\nEnter the data of node to be removed : "); (temp==NULL)?
scanf("%d",&k);
if((*h)->data==k) {
w printf("\n\t=>Node does not exist") :
printf("\n\t=>Node exists");
tu
temp=*h; }
.jn
temp=(*h)->next; p = (*h)->next;
w
prev=*h; free(*h);
while(temp!=NULL && temp->data!=k) { *h=p;
prev=temp; }
temp=temp->next; printf("\n\n ******Linked List is destroyed******");
} }
Implementing Singly Linked List ( continued )
int main() { /* function to sort linked list */
struct node *head=NULL; void sort(struct node *h) {
int ch; struct node *p,*temp;
om
while(1) { int i, j, n, t, sorted=0;
printf("\n1.Append"); temp=h;
printf("\n2.Display All"); for(n=0 ; temp!=NULL ; temp=temp->next) n++;
.c
printf("\n3.Insert after a specified node"); for(i=0;i<n-1&&!sorted;i++) {
m
printf("\n4.Insert before a specified node"); p=h; sorted=1;
printf("\n5.Delete a node"); for(j=0;j<n-(i+1);j++) {
ru
printf("\n6.Search for a node"); if ( p->data > ( p->next )->data ) {
printf("\n7.Distroy the list"); t=p->data;
fo
printf("\n8.Exit program"); p->data =(p->next)->data;
ld
printf("\n\n\tEnter your choice : "); (p->next)->data = t;
scanf("%d",&ch); sorted=0;
or
switch(ch) { }
case 1:append(&head);break;
case 2:display(head);break;
w }
p=p->next;
tu
case 3:insert_after(&head);break; }
.jn
case 4:insert_before(&head);break; }
case 5:delnode(&head);break;
w
case 8:exit(0);break; {
w
default : int i;
printf( "Wrong Choice, Enter correct one : "); for( i=0 ; h!=NULL ; h=h->next)
} i++;
} return i;
} }
Algorithm for adding two polynomials in linked lists
om
initialize a linked list r for a zero polynomial
while p != null and q != null
.c
if p.exp > q.exp
m
create a node storing p.coeff and p.exp
insert at the end of list r
ru
advance p
fo
else if q.exp > p.exp
create a node storing q.coeff and q.exp
ld
insert at the end of list r
or
advance q
else if p.exp == q.exp
if p.coeff + q.coeff != 0
w
tu
create a node storing p.coeff + q.coeff and p.exp
.jn
end while
w
if p != null
w
om
These problems of singly linked lists can be overcome by doubly linked list.
.c
A Doubly Linked List is a data structure having an ordered list of nodes, in which each node consists
m
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.
ru
The specialty of DLL is that the list can be traversed in forward as well as backward directions.
fo
The concept of DLL is also used to representing tree data structures.
ld
or
head tail
A
w B C
tu
.jn
B
{
w
A D
int data ;
struct node *next; C
}
q
A B D
om
C
.c
p q
m
ru
A B C D
fo
ld
Deletion of node in Doubly Linked List
or
w
tu
.jn
A B C
p
w
w
D
w
A B C
Implementing Doubly Linked List
struct node { void forward_display(struct node *p)
struct node *prev; {
int data; printf("\nContents of the List : \n\n");
om
struct node *next; while(p!=NULL)
}; {
struct node *createnode() { printf("\t%d",p->data);
.c
struct node *new; p = p->next;
m
new = (struct node *)malloc(sizeof(struct node)); }
printf("\nEnter the data : "); printf("\n");
ru
scanf("%d",&new->data); }
new->prev = NULL; void insert_after(struct node **h) {
fo
new->next = NULL; struct node *new,*temp;
ld
return new; int k;
} if(*h == NULL) return;
or
void append(struct node **h) { printf("\nEnter data of node after which node : ");
struct node *new,*temp;
new = createnode();
w scanf("%d",&k);
temp = *h;
tu
if(*h == NULL) while(temp!=NULL && temp->data!=k)
.jn
{ temp = temp->next;
*h = new; if(temp!=NULL) {
w
return; new=createnode();
} new->next = temp->next;
w
om
int k; int k;
if(*h==NULL) return; if(*h==NULL)
printf("\nEnter data of node before which node : "); return;
.c
scanf("%d",&k); printf("\nEnter the data of node to be removed : ");
m
if((*h)->data == k) { scanf("%d",&k);
new = createnode(); if((*h)->data==k)
ru
new->next = *h; {
new->next->prev=new; temp=*h;
fo
*h = new; *h=(*h)->next;
ld
return; (*h)->prev=NULL;
} free(temp);
or
temp = *h; return;
while(temp!=NULL && temp->data!=k)
{
w }
temp=*h;
tu
temp=temp->next; while(temp!=NULL && temp->data!=k)
.jn
} {
if(temp!=NULL) temp=temp->next;
w
{ }
new = createnode(); if(temp!=NULL)
w
new->next = temp; {
w
om
int k; while(1) {
if(h==NULL) printf("\n1.Append");
return; printf("\n2.Display All");
.c
printf("\nEnter the data to be searched : "); printf("\n3.Insert after a specified node");
m
scanf("%d",&k); printf("\n4.Insert before a specified node");
temp=h; printf("\n5.Delete a node");
ru
while(temp!=NULL && temp->data!=k) printf("\n6.Search for a node");
temp=temp->next; printf("\n7.Distroy the list");
fo
if (temp==NULL) printf("\n8.Exit program");
ld
printf("\n\t=>Node does not exist") printf("\n\n\tEnter your choice : ");
else scanf("%d",&ch);
or
printf("\n\t=>Node exists"); switch(ch) {
}
void destroy(struct node **h)
w case 1:append(&head);break;
case 2:forward_display(head);break;
tu
{ case 3:insert_after(&head);break;
.jn
free(*h); default :
*h=p; printf("Wrong Choice, Enter correct choice : ");
} }
printf("\n\n ******Linked List is destroyed******"); }
} }
910
101 400 102 720 103 910 104 150
Circular Singly tail
Linked List 150 400 720 910
n1-node n2-node n3-node n4-node
om
-- 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
.c
circular linked list.
m
-- 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.
ru
-- 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.
fo
-- If the tail pointer refers to NULL, means the circular linked list is empty.
ld
or
Circular Doubly Linked List
w
tu
prev 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 vice-
w
versa.
w
-- The ‘ prev ’ link of first node contains the address of last node and ‘ next ’ link of last node contains
w
om
struct node *new; if(*t == NULL) return;
new = (struct node *)malloc(sizeof(struct node)); printf("\nEnter data of node after which node : ");
printf("\nEnter the data : "); scanf("%d",&k);
.c
scanf("%d",&new->data); if((*t)->data==k)
m
new->next = NULL; {
return new; new = createnode();
ru
} new->next = (*t)->next;
fo
void append(struct node **t) { (*t)->next = new;
struct node *new,*head; *t=new;
ld
new = createnode(); return;
or
if(*t == NULL) { }
*t = new; new->next = *t; temp=(*t)->next;
return; w while(temp!=*t)
tu
} {
head = (*t)->next; (*t)->next = new; if(temp->data == k) {
.jn
do { }
printf("\t%d",temp->data);temp = temp->next; temp=temp->next;
}while(temp!=head); }
printf(“\n”); if(found==0) printf("\nNode does not exist..");
} }
Implementing Circular Singly Linked List ( continued )
void insert_before(struct node **t) { void delnode(struct node **t) {
struct node *new,*temp,*prev,*head; struct node *temp,*prev,*head;
int k,found=0; int k,found=0;
if(*t==NULL) return; if(*t==NULL) return;
om
printf("\nEnter data of node before which node : "); printf("\nEnter the data of node to be removed : ");
scanf("%d",&k); scanf("%d",&k);
head=(*t)->next; head=(*t)->next;
.c
if(head->data == k) { if(head->data==k) {
m
new = createnode(); temp=head;
new->next = head; if(temp->next!=head) (*t)->next=head->next;
ru
(*t)->next = new; else *t = NULL;
fo
return; free(temp);
} return;
ld
temp = head->next; }
or
prev = head; temp=head->next; prev=head;
while(temp!=head) { while(temp!=head) {
if(temp->data==k) { w if(temp->data == k) {
tu
new = createnode(); prev->next = temp->next;
prev->next = new; if(temp==*t) *t = prev;
.jn
break; break;
w
} else { } else {
prev=temp; prev=temp;
w
temp=temp->next; temp=temp->next;
} }
} }
if(found==0) printf("\nNode does not exist.."); if(found==0) printf("\nNode does not exist..");
} }
Implementing Circular Singly
Linked List ( continued )
om
int main() {
struct node *tail=NULL; Types of Data Structures
int ch;
.c
while(1) {
printf("\n1.Append");
m
Data structures are classified in several ways :
printf("\n2.Display All"); Linear : Elements are arranged in sequential
ru
printf("\n3.Insert after a specified node"); fashion. Ex : Array, Linear list, stack, queue
printf("\n4.Insert before a specified node"); Non-Linear : Elements are not arranged in
fo
printf("\n5.Delete a node"); sequence. Ex : trees, graphs
ld
printf("\n6.Exit program"); Homogenous : All Elements are belongs to same
printf("\n\n\tEnter your choice : "); data type. Ex : Arrays
or
scanf("%d",&ch); Non-Homogenous : Different types of Elements
switch(ch)
{
w are grouped and form a data structure. Ex:
classes
tu
case 1:append(&tail);break; Dynamic : Memory allocation of each element in
case 2:display(tail);break;
.jn
default :
printf(“\n\tWrong Choice… “);
}
}
}
Stacks
-- 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”.
om
-- The most accessible element in the stack is the element at the position “TOP”.
-- Stack must be created as empty.
.c
-- 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.
m
-- We can implement the stack ADT either with array or linked list.
ru
Stack ADT
fo
Applications of stack struct stackNode {
ld
int data; struct stackNode *next;
Reversing Data series };
or
Conversion decimal to binary init_stack( )
Parsing into tokens
Backtracking the operations
w push ( )
pop ( )
tu
Undo operations in Text Editor isEmpty ( )
.jn
om
c d d d
b b b b b b b
.c
a a a a a a a a a
m
ru
Operations on Stack
fo
Operation Stack’s contents TOP value Output
ld
or
1. Init_stack( ) <empty> -1
2. Push( ‘a’ ) a w 0
3. Push( ‘b’ ) ab 1
tu
4. Push( ‘c’ ) abc 2
.jn
5. Pop( ) ab 1 c
w
8. Pop( ) abd 2 ce
9. Pop( ) ab 1 ced
10. Pop( ) a 0 cedb
11. Pop( ) <empty> -1 cedba
Implementing Stack ADT using Array
#define SIZE 50 int main() {
int stack[SIZE]; int top; int choice,item;
void init_stack() { init_stack();
top=-1; do
om
} {
void push( int n ) { printf("\n\t\t\tMenu\n\t1.Push.\n\t2.Pop.");
if( top==SIZE-1) printf("\nStack is full"); printf("\n\t3.Peek.\n\t4.Display.\n\t5.Exit.\n");
.c
else stack[++top]= n; printf("\nYour Choice: ");
m
} scanf("%d",&choice);
int pop( ) { switch(choice)
ru
if(top== -1) { {
fo
printf("\nStack is empty"); case 1:printf("\nEnter the element to push : ");
return -1; scanf("%d",&item);
ld
} else return stack[top--]; push(item); break;
or
} case 2:item = pop();
void display( ) { printf("\nElement poped : %d",item);
int i; w printf("\nPress a key to continue...");
tu
if(top== -1) printf("\nStack is empty."); getche(); break;
else { case 3:item = peek();
.jn
} case 4:display();
} printf("\nPress a key to continue...");
w
om
void push(int j) { }
struct s_node *m; void main() {
m=(struct s_node*)malloc(sizeof(struct s_node)); int choice,num,i;
.c
m->data= j ; m->link=stack; while(1) {
m
stack=m; return; printf("\n\t\t MENU\n1. Push\n2. Pop\n3. Peek");
} printf("\n4. Elements in Stack\n5. Exit\n");
ru
int pop( ) { printf("\n\tEnter your choice: ");
fo
struct s_node *temp=NULL; scanf("%d",&choice);
if(stack==NULL) { switch(choice) {
ld
printf("\nSTACK is Empty."); getch(); case 1: printf("\nElement to be pushed:");
or
} else { scanf("%d",&num);
int i=stack->data; push(num); break;
temp = stack ; stack=stack->link; w case 2: num=pop();
tu
free(temp); return (i); printf("\nElement popped: %d ",num);
} getch(); break;
.jn
} case 3: num=peek();
int peek( ) { printf("\nElement peeked : %d ",num);
w
om
-- 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.
.c
-- Queue must be created as empty.
-- Whenever an element is inserted into queue, it must be checked whether the queue is full or not.
m
-- Whenever an element is deleted form queue, it must be checked whether the queue is empty or not.
ru
-- We can implement the queue ADT either with array or linked list.
fo
Queue ADT
4
ld
rear front struct queueNode {
int data; struct queueNode *next;
or
3 6 8 2 5 };
addq (4)
w
delq ( )
init_queue( )
addq ( )
tu
7 delq ( )
.jn
isEmpty ( )
printQueue ( )
w
Applications of Queues
w
Types of Queues
Execution of Threads
w
Job Scheduling
circular queues
Event queuing
priority queues
Message Queueing
double-ended queues
Implementing Queue ADT using Array
int queue[10] ,front, rear ; printf("\nElements are : \n");
void init_queue() { for (i=front;i<=rear;i++)
front = rear = -1 ; printf("%5d",queue[i]);
} }
om
void addq ( int item ){ }
if ( rear == 9 ) { int main() {
printf("\nQueue is full"); int ch,num;
.c
return ; init_queue();
m
} do
rear++ ; {
ru
queue [ rear ] = item ; printf("\n\tMENU\n\n1. Add to Queue”);
fo
if ( front == -1 )front = 0 ; printf(“\n2. Delete form Queue");
} printf("\n3. Display Queue\n4. Exit.");
ld
int delq( ){ printf("\n\n\tYour Choice: ");
or
int data ; scanf("%d",&ch);
if ( front == -1 ) { switch(ch)
printf("\nQueue is Empty"); w {
tu
return 0; case 1: printf("\nEnter an element : ");
} scanf("%d",&num);
.jn
} case 4: exit(0);
void display() { default: printf("\nInvalid option..");
int i; }
if(front==-1) printf("\nQueue is empty."); }while(1);
else { }
Implementing Queue ADT using Liked List
om
rear=NULL; front=NULL; temp=temp->next;
} }
.c
void addq(int item) { }
struct q_node *t; }
m
t=(struct q_node*)malloc(sizeof(struct q_node)); int main() {
ru
t->data=item; t->next=NULL; int ch,num;
if(front==NULL) rear=front=t; init_queue();
fo
else { do {
ld
rear->next=t; rear=rear->next; printf("\n\tMENU\n\n1. Add\n2. Delete");
} printf("\n3. Display Queue\n4. Exit.");
or
} printf("\n\n\tYour Choice: ");
int delq() { scanf("%d",&ch);
struct q_node *temp;
w switch(ch) {
tu
if(front==NULL) { case 1: printf("\nEnter an element : ");
printf("\nQueue is empty."); return 0; scanf("%d",&num);
.jn
} else { addq(num);break;
int num = front->data; case 2: num=delq();
w
} case 4: exit(0);
} default:printf("\nInvalid option..");
void display() { }
struct q_node *temp=front; }while(1);
if(front==NULL) printf("\nQueue is empty."); }
--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.
om
Ex: +AB *A+BC +*AB*CD
-- In Postfix notation, the operator is placed after the two operands.
Ex: AB+ ABC+* AB*CD*+
.c
m
Algorithm to Infix to Postfix Conversion
ru
In-To-Post ( infix-expression )
fo
Scan the Infix expression left to right
If the character x is an operand
ld
Output the character into the Postfix Expression
or
If the character x is a left or right parenthesis
If the character is “(
Push it into the stack w
tu
If the character is “)”
Repeatedly pop and output all the operators/characters until “(“ is popped from the stack.
.jn
om
/*pushes ps into stack*/ }
void push(STACK *sptr, char ps) { } else {
if(sptr->top == STACKSIZE-1) { if(s.top ==-1 || s.items[s.top] == '(')
.c
printf("Stack is full\n"); exit(1); push(&s ,x);
m
} else else {
sptr->items[++sptr->top]= ps; /* y is the top operator in the stack*/
ru
} y = s.items[s.top];
fo
char pop(STACK *sptr) { /* precedence of y is higher/equal to x*/
if(sptr->top == -1) { if( y=='*' || y=='/'){
ld
printf("Stack is empty\n"); exit(1); printf("%c", pop(&s));
or
} else push(&s ,x);
return sptr->items[sptr->top--]; } else if ( y=='+' || y=='-')
} w /* precedence of y is equal to x*/
tu
int main() { if( x=='+' || x=='-') {
int i; STACK s; char x, y, E[20] ; printf("%c", pop(&s));
.jn
om
int top=-1; }
void push(char c) }
{ j++;
.c
stack[++top]=c; }
m
} return pop();
float pop() { }
ru
float n; int main() {
fo
n=stack[top--]; int j=0;
return (n); char expr[20];
ld
} float number[20],result;
or
float evaluate(char expr[], float data[]) printf("\nEnter a post fix expression : ");
{ gets(expr);
int j=0; w while(expr[j]!='\0')
tu
float op1=0,op2=0; {
char ch; if(isalpha(expr[j]))
.jn
while(expr[j]!='\0') { {
ch = expr[j]; fflush(stdin);
w
push(data[j]); scanf("%f",&number[j]);
} else { }
w
op2=pop(); j++;
op1=pop(); }
switch(ch) { result = evaluate(expr,number);
case '+':push(op1+op2);break; printf("\nThe result of %s is %f",expr,result);
case '-':push(op1-op2);break; }
w
w
w
.jn
tu
w
or
ld
fo
ru
m
.c
om